gpt4 book ai didi

javascript - 我如何限制功能-(老虎机游戏)仅进行 5 轮-使用 do/while 循环

转载 作者:行者123 更新时间:2023-11-30 14:13:30 24 4
gpt4 key购买 nike

我想通过 javascript 创建一个有 3 个数字的老虎机 - 但我想在三个数字相等时完成我的功能。我认为如果我用 do/while 写它会起作用,但我做不到这是我的 js 代码:

 function myF() {
var slotOne = Math.floor(Math.random() * 3) + 1;
var slotTwo = Math.floor(Math.random() * 3) + 1;
var slotThree = Math.floor(Math.random() * 3) + 1;

document.getElementById("slotOne").innerHTML = slotOne;
document.getElementById("slotTwo").innerHTML = slotTwo;
document.getElementById("slotThree").innerHTML = slotThree;

if(slotOne == slotTwo && slotTwo == slotThree) {
document.getElementById("slotOne").style.backgroundColor = "#48bd48";
document.getElementById("slotTwo").style.backgroundColor = "#48bd48";
document.getElementById("slotThree").style.backgroundColor = "#48bd48";
document.getElementById("winner").classList.add("show");
}
}

这个函数是设置按钮标签的onclick属性

最佳答案

添加评论,如果你想运行函数的次数不多,那么只需使用计数器变量来检查尝试次数:

添加了一个重置​​按钮来重置游戏。

var counter = 0;

function myF() {

if (counter != 5) {
counter++;
document.getElementById("slotLeft").innerHTML = "Try count: " + counter;
var slotOne = Math.floor(Math.random() * 3) + 1;
var slotTwo = Math.floor(Math.random() * 3) + 1;
var slotThree = Math.floor(Math.random() * 3) + 1;

document.getElementById("slotOne").innerHTML = slotOne;
document.getElementById("slotTwo").innerHTML = slotTwo;
document.getElementById("slotThree").innerHTML = slotThree;

if (slotOne == slotTwo && slotTwo == slotThree) {
document.getElementById("slotOne").style.backgroundColor = "#48bd48";
document.getElementById("slotTwo").style.backgroundColor = "#48bd48";
document.getElementById("slotThree").style.backgroundColor = "#48bd48";
document.getElementById("winner").classList.add("show");
counter = 5; // Edited this line
}
} else {
console.log('Game over');
}
}

function myF1(){
counter = 0;
document.getElementById("slotOne").innerHTML = "";
document.getElementById("slotTwo").innerHTML = "";
document.getElementById("slotThree").innerHTML = "";
}
<button onclick="myF()">Check</button>
<button onclick="myF1()">Restart Game</button>


<div id="slotLeft">
</div>
<div id="slotOne">
</div>

<div id="slotTwo">
</div>

<div id="slotThree">
</div>

<div id="winner">
</div>

关于javascript - 我如何限制功能-(老虎机游戏)仅进行 5 轮-使用 do/while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53968946/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com