2017-02-08 74 views
0

我正在使用JavaScript編寫簡單的tictactoe遊戲,但它顯示(有人贏了!!!)在第一次點擊板上,我知道我很接近但我無法找到我的問題碼。tictactoe with javascript using css3

<!DOCTYPE html> 
<html> 
<head> 
    <style> 
     .board{ 
      display: flex; 
      width: 600px; 
      height: 600px; 
      flex-direction: row; 
      flex-wrap: wrap; 
      justify-content: flex-start; 
     } 
     .square{ 
      width: 200px; 
      height: 200px; 
      box-sizing: border-box; 
      border: 5px solid black; 
      font-size: 5em; 
      display: flex; 
      justify-content: center; 
      align-items: center; 
     } 
     .square:hover{ 
      cursor: pointer; 
      background-color: #80cd92; 
     } 
    </style> 
</head> 
<body> 

<div class="board"> 
    <div class="square"> </div> 
    <div class="square"> </div> 
    <div class="square"> </div> 
    <div class="square"> </div> 
    <div class="square"> </div> 
    <div class="square"> </div> 
    <div class="square"> </div> 
    <div class="square"> </div> 
    <div class="square"> </div> 
</div> 

<script> 
    var PLAYER_ONE_SYMBOL = 'X' 
    var PLAYER_TWO_SYMBOL = 'O' 
    var currentTurn = PLAYER_ONE_SYMBOL 

    var board = document.querySelector('.board') 
    board.addEventListener('click',function(e) { 
     e.target.innerHTML = currentTurn 
     currentTurn = currentTurn === PLAYER_ONE_SYMBOL ? PLAYER_TWO_SYMBOL : PLAYER_ONE_SYMBOL 
     if (checkForWinner()) 
     {alert(" somebody won !!! ")} 
    }) 

    function checkForWinner(){ 
     var squares = Array.prototype.slice.call(document.querySelectorAll('.square'), 0) 
     var symbols = squares.map(function(square) { 
      return square.innerHTML 
     }) 
     var winningCombos = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]] 
      return winningCombos.find(function(combo) 
      { 
      if(symbols[combo[0]]==symbols[combo[1]]&&symbols[combo[1]]==symbols[combo[2]]) 
      {return symbols[combo[0]]} 
      else {return false} 

       }) 
    } 

</script> 
</body> 
</html> 

回答

1

您的廣場初始值都是相同的(空格),這就是爲什麼第一次評估會導致贏得組合。字段0,1和2都具有相同的值。

您不僅需要評估所有三個字段的值是否相同,而且它們是否等於XO

或者你可以不喜歡下面,依靠事實,即falsy空字符串進行評估:

if(symbols[combo[0]] == symbols[combo[1]] 
     && symbols[combo[1]] == symbols[combo[2]]) { 

    return symbols[combo[0]].trim(); // will return 'X', 'O' or empty string 
} 
+1

非常感謝羅比你解決了這個問題!我在這段代碼上花了幾個小時試圖看看有什麼不對,我很高興你能幫助我,再次感謝 – gualgui