【问题标题】:if conditional for background color?如果有条件的背景颜色?
【发布时间】:2017-04-24 01:01:25
【问题描述】:

我一直在尝试制作井字游戏,但由于某种原因,条件不起作用..

我试图定位第一行的前三个元素,如果它们都是相同的颜色,我想在浏览器中提醒“获胜”弹出窗口,但它没有发生。

有人知道为什么吗?

这是我的代码:

var one = document.getElementById("one");
var two = document.getElementById("two");
var three = document.getElementById("three");
var four = document.getElementById("four");
var five = document.getElementById("five");
var six = document.getElementById("six");
var seven = document.getElementById("seven");
var eight = document.getElementById("eight");
var nine = document.getElementById("nine");


var counter = 1;

//code that changes the box color
one.addEventListener("click", function() {
  if (counter < 10 && counter % 2 === 0) {
    one.style.backgroundColor = "yellow";
  } else if (counter < 10 && counter % 2 != 0) {
    one.style.backgroundColor = "red";
  }
  counter++;
  console.log(counter);
});
two.addEventListener("click", function() {
  if (counter < 10 && counter % 2 === 0) {
    two.style.backgroundColor = "yellow";
  } else if (counter < 10 && counter % 2 != 0) {
    two.style.backgroundColor = "red";
  }
  counter++;
  console.log(counter);
});
three.addEventListener("click", function() {
  if (counter < 10 && counter % 2 === 0) {
    three.style.backgroundColor = "yellow";
  } else if (counter < 10 && counter % 2 != 0) {
    three.style.backgroundColor = "red";
  }
  counter++;
  console.log(counter);
});
four.addEventListener("click", function() {
  if (counter < 10 && counter % 2 === 0) {
    four.style.backgroundColor = "yellow";
  } else if (counter < 10 && counter % 2 != 0) {
    four.style.backgroundColor = "red";
  }
  counter++;
  console.log(counter);
});
five.addEventListener("click", function() {
  if (counter < 10 && counter % 2 === 0) {
    five.style.backgroundColor = "yellow";
  } else if (counter < 10 && counter % 2 != 0) {
    five.style.backgroundColor = "red";
  }
  counter++;
  console.log(counter);
});
six.addEventListener("click", function() {
  if (counter < 10 && counter % 2 === 0) {
    six.style.backgroundColor = "yellow";
  } else if (counter < 10 && counter % 2 != 0) {
    six.style.backgroundColor = "red";
  }
  counter++;
  console.log(counter);
});
seven.addEventListener("click", function() {
  if (counter < 10 && counter % 2 === 0) {
    seven.style.backgroundColor = "yellow";
  } else if (counter < 10 && counter % 2 != 0) {
    seven.style.backgroundColor = "red";
  }
  counter++;
  console.log(counter);
});
eight.addEventListener("click", function() {
  if (counter < 10 && counter % 2 === 0) {
    eight.style.backgroundColor = "yellow";
  } else if (counter < 10 && counter % 2 != 0) {
    eight.style.backgroundColor = "red";
  }
  counter++;
  console.log(counter);
});
nine.addEventListener("click", function() {
  if (counter < 10 && counter % 2 === 0) {
    nine.style.backgroundColor = "yellow";
  } else if (counter < 10 && counter % 2 != 0) {
    nine.style.backgroundColor = "red";
  }
  counter++;
  console.log(counter);
});

//logic for winning
if (one.style.backgroundColor == "red" && two.style.backgroundColor == "red" && three.style.backgroundColor == "red") {
  console.log("red wins");
}
.knobs {
  background-color: blue;
  border: none;
  padding: 50px;
  margin: 10px;
}

.knobs:focus {
  outline: none;
}

#total {
  text-align: center;
}
<!DOCTYPE html>

<div id="total">
  <button id="one" class="knobs"></button>
  <button id="two" class="knobs"></button>
  <button id="three" class="knobs"></button>
  <br>
  <button id="four" class="knobs"></button>
  <button id="five" class="knobs"></button>
  <button id="six" class="knobs"></button>
  <br>
  <button id="seven" class="knobs"></button>
  <button id="eight" class="knobs"></button>
  <button id="nine" class="knobs"></button>
</div>

您的帮助将不胜感激!

【问题讨论】:

  • 另一件事:了解event delegation。您不需要九个不同的事件侦听器。您只需要将一个带有参数(例如e)的单个绑定到#total,并使用e.target检查单击了哪个旋钮。
  • 我为您的版本添加了一个替代解决方案并进行了一些优化

标签: javascript if-statement alert background-color tic-tac-toe


【解决方案1】:

问题是您的 if 语句在开始时只运行一次。你需要把它变成一个函数,然后在每个事件之后调用它。类似的东西

function check() {
    if (one.style.backgroundColor == "red" && two.style.backgroundColor == "red" && three.style.backgroundColor == "red"){
    console.log("red wins");
    }
}

在事件监听器的最后你可以这样称呼它:

check();

(就像 Xufox 上面所说的那样,您应该真正考虑委托,以便更易于管理,并且您不必重复所有内容。)

【讨论】:

    【解决方案2】:

    在您的代码中:

    var one = document.getElementById("one");
    var two = document.getElementById("two");
    var three = document.getElementById("three");
    var four = document.getElementById("four");
    var five = document.getElementById("five");
    var six = document.getElementById("six");
    var seven = document.getElementById("seven");
    var eight = document.getElementById("eight");
    var nine = document.getElementById("nine");
    
    1. 您不需要像这样声明每个按钮。您可以使用数组和循环优化它,例如forforEach。像这样:

      var knobs = [
          'one', 
          'two', 
          'three', 
          'four', 
          'five', 
          'six', 
          'seven', 
          'eight', 
          'nine'
      ];
      
      knobs.forEach(function(id) {
        var element = document.getElementById(id);
        element.addEventListener('click', function() {
            ...
        }
      }
      
    2. 您正在使用addEventListener 为每个按钮添加一个侦听器。正如我在第 1 点中提到的那样,这可以进行优化。您可以使用 var element = document.getElementById(id); 获得按钮元素,并且可以在同一 forEach 中添加侦听器。

    3. 我还使用相同的forEach 来初始化我的board 数组,并为每个元素使用-1。这意味着它是空的。
    4. 现在您需要添加一个方法来验证每次点击后是否有获胜者。在此代码示例中,我使用了verifyWinner(index);,并传递了按钮的索引;
    5. 另外,在这一行中one.style.backgroundColor == 'red' 只有== 是不够的,所以我建议你使用=== 来比较strings
    6. 使用这种基于CSS的方法的问题是如果你在同一个旋钮上单击两次或多次会发生什么?计数器会增加,并且旋钮会从red改变颜色以yellow 为例。这就是为什么我建议您使用board 数组来映射“游戏状态”。
    7. 最后,我创建了一个board 作为一个数组,如果是red,我把12 如果是yellow。这将帮助您简化验证过程。

    这是代码示例。快乐编码。 注意:为了在 sn-p 运行器中更好地可视化,我减小了旋钮大小。

    var knobs = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
    var board = [];
    
    var isRed = true;
    var isEndGame = false;
    var counter = 0;
    knobs.forEach(function(id) {
      var element = document.getElementById(id);
      board.push(-1);
      element.addEventListener('click', function() {
        var index = knobs.indexOf(id);
        if (!isEndGame && board[index] == -1) {
          if (isRed) {
            element.style.backgroundColor = 'red';
            board[index] = 1;
          } else {
            element.style.backgroundColor = 'yellow';
            board[index] = 2;
          }
          verifyWinner(index);
          isRed = !isRed;
          counter++;
          //console.log(counter)
        }
        if (counter == 9) {
          isEndGame = true;
          console.log('End of game.');
        }
      });
    });
    
    function verifyWinner(index) {
      //logic for winning
      var player = isRed ? 1 : 2;
    
      switch (index) {
        case 0:
        case 2:
        case 6:
        case 8:
        case 4:
          verifyVertial(index);
          verifyHorizontal(index);
          verifyDiagonal(index);
          break;
        case 1:
        case 3:
        case 5:
        case 7:
          verifyVertial(index);
          verifyHorizontal(index);
          break;
      }
      if (isEndGame) {
        console.log((isRed ? 'Red' : 'Yellow') + ' has won.');
        console.log('End of game.');
      }
    }
    
    function verifyVertial(index) {
      //logic for winning
      if (!isEndGame) {
        var player = isRed ? 1 : 2;
        switch (index) {
          case 0:
          case 3:
          case 6:
            if (board[0] == player && board[3] == player && board[6] == player) {
              isEndGame = true;
            }
            break;
          case 1:
          case 4:
          case 7:
            if (board[1] == player && board[4] == player && board[7] == player) {
              isEndGame = true;
            }
            break;
          case 2:
          case 5:
          case 8: // edges
            if (board[2] == player && board[5] == player && board[8] == player) {
              isEndGame = true;
            }
            break;
        }
      }
    }
    
    function verifyHorizontal(index) {
      //logic for winning
      if (!isEndGame) {
        var player = isRed ? 1 : 2;
        switch (index) {
          case 0:
          case 1:
          case 2: // edges
            if (board[0] == player && board[1] == player && board[2] == player) {
              isEndGame = true;
            }
            break;
          case 3:
          case 4:
          case 5:
            if (board[3] == player && board[4] == player && board[5] == player) {
              isEndGame = true;
            }
            break;
          case 6:
          case 7:
          case 8: // edges
            if (board[6] == player && board[7] == player && board[8] == player) {
              isEndGame = true;
            }
            break;
        }
      }
    }
    
    function verifyDiagonal(index) {
      //logic for winning
      if (!isEndGame) {
        var player = isRed ? 1 : 2;
        switch (index) {
          case 0:
          case 4:
          case 8: // edges
            if (board[0] == player && board[4] == player && board[8] == player) {
              isEndGame = true;
            }
            break;
          case 2:
          case 4:
          case 6: // edges
            if (board[2] == player && board[4] == player && board[6] == player) {
              isEndGame = true;
            }
            break;
        }
      }
    }
    .knobs {
      background-color: blue;
      border: none;
      padding: 25px;
      margin: 3px;
    }
    
    .knobs:focus .clear:focus {
      outline: none;
    }
    
    #total {
      text-align: center;
    }
    
    .clear {
      clear: both;
    }
    <!DOCTYPE html>
    
    <div id="total">
      <button id="one" class="knobs"></button>
      <button id="two" class="knobs"></button>
      <button id="three" class="knobs"></button>
      <div class="clearfix"></div>
      <button id="four" class="knobs"></button>
      <button id="five" class="knobs"></button>
      <button id="six" class="knobs"></button>
      <div class="clearfix"></div>
      <button id="seven" class="knobs"></button>
      <button id="eight" class="knobs"></button>
      <button id="nine" class="knobs"></button>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-16
      • 2021-04-07
      • 1970-01-01
      • 2020-11-11
      • 2017-11-17
      • 1970-01-01
      • 2013-07-12
      • 1970-01-01
      相关资源
      最近更新 更多