【问题标题】:How can I get setInterval() to increase by 1 instead of 12?如何让 setInterval() 增加 1 而不是 12?
【发布时间】:2022-01-13 16:22:55
【问题描述】:

我的游戏有两个玩家获得随机数,拥有更大数字的人获得 1 个“胜利”。我的 while 循环用于“自动掷骰”按钮,而不是每次都单击“掷骰子”,自动掷骰会为您执行此操作,直到一名玩家获胜 == 游戏限制 # (bestof.value)。无论我把 setInterval 放在哪里,它都会一次增加一堆。如果 bestof.value = 10,则每个间隔一次显示至少 10 场胜利。

checkBox.checked = 启用自动滚动功能的输入复选标记。所以这个 setInterval 只会在自动滚动循环处于活动状态时才会被激活。

无论如何,我做错了什么?

button.addEventListener("click", myFunction);
    function myFunction() {
        let random = Math.floor((Math.random() * 6) + 1);
        let random2 = Math.floor((Math.random() * 6) + 1);
        screenID.innerHTML = random;
        screenIDD.innerHTML = random2; 
        if (random > random2){
            winNumber.innerHTML = ++a;
        } else if(random2 > random){
            winNumba1.innerHTML = ++b;
        } else {
            console.log("Draw");
        }
        if (a > b){
            winNumber.style.color = 'white';
            winNumba1.style.color = 'black';
        } else if(b > a){
            winNumba1.style.color = 'white';
            winNumber.style.color = 'black';
        } else {
            winNumber.style.color = 'black';
            winNumba1.style.color = 'black';
        }
        if (checkBox.checked){
            setInterval(myFunction, 2000)
            while(a < bestof.value && b < bestof.value){
            myFunction();
          }};
        if (winNumba1.innerHTML == bestof.value){
            winAlert.style.display = "flex";
            console.log('winNumba1 wins!');
        } else if (winNumber.innterHTML == bestof.value){
            winAlert.style.display = "flex";
            console.log('winNumber wins!');
        } else {}
};

【问题讨论】:

  • 请使用您的 IDE 提供的调试工具(vsCode 等)来调试您的代码,它是一个很好的学习工具,肯定会告诉您发生了什么以及您的代码哪里出错了跨度>

标签: javascript setinterval


【解决方案1】:

因为我手头没有 html,所以我在这里为你的游戏写了一个简化的 js 版本,但我相信你可以根据你的环境对其进行调整。

主要区别:我检查是否有人获胜并使用return 停止该功能 如果没有人获胜并激活自动播放,我会在 500 毫秒后再次自动播放。

let playerA = 0
let playerB = 0
let autoPlay = true
let bestOf = 3

function myFunction() {

  let random = Math.floor((Math.random() * 6) + 1);
  let random2 = Math.floor((Math.random() * 6) + 1);
  console.log("New Round " + random + " vs " + random2)
  if (random > random2) {
    playerA++
  } else if (random2 > random) {
    playerB++
  } else {
    console.log("Draw");
  }
  if (playerA > playerB) {
    console.log("a is winning")
  } else if (playerB > playerA) {
    console.log("b is winning")
  } else {
    console.log("There has been a draw")
  }
  if (playerA == bestOf) {
    console.log('A won');
    return
  } else if (playerB == bestOf) {
    console.log('B won');
    return
  }
  if (autoPlay) {
    setTimeout(myFunction, 500)
  };

};
myFunction()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-25
    • 1970-01-01
    • 2013-05-10
    • 2010-12-22
    • 2019-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多