除其他事项外,我很难提醒获奖者。我还试图提醒用户何时单击已经按下的按钮,但也不知道我在这方面正在做什么。感谢所有帮助。感谢大伙们。

<table>
        <tr>
            <td id="00" onclick="makeMove(0,0)">00</td>
            <td id ="01" onclick="makeMove(0,1)">01</td>
            <td id ="02" onclick="makeMove(0,2)">02</td>
        </tr>
        <tr>
            <td id ="10" onclick="makeMove(1,0)">10</td>
            <td id ="11" onclick="makeMove(1,1)">11</td>
            <td id ="12" onclick="makeMove(1,2)">12</td>
        </tr>
        <tr>
            <td id ="20" onclick="makeMove(2,0)">20</td>
            <td id ="21" onclick="makeMove(2,1)">21</td>
            <td id ="22" onclick="makeMove(2,2)">22</td>
 </tr>
    </table>

    <hr>
    <input id="myMoveButton" type="submit">

    <script src="java.js"></script>


Javascript:

// -1 means 0's turn
// 1 means X's turn

// AFTER EVERY MOVE
// UNTIL GAME OVER
// THIS NEEDS TO BE FLIPPED
// IF IT WAS 1, now it will be -1 and vice versa

var turn = 1;

// 0 means no move has been made yet
// on that particular square
var grid = [
    [0, 0 ,0],
    [0, 0 ,0],
    [0, 0, 0]
];


function makeMove(row, column) {

    if (grid [row][column] == 0) {
        grid[row][column] = turn;

        var idOfSquareToChange = row +"" + column;

        if (turn == 1) {

            $("#"+idOfSquareToChange).html('X');
        }else {
            $("#"+idOfSquareToChange).html('O');
        }

        // CHECK IF GAME IS OVER

        // IF GAME ISN'T OVER
        if (turn == 1) {
            turn = -1;
        }else {
            turn = 1;
        }
        printGrid();
    }else {
        alert('That square has been chosen');
    }
}

function printGrid(){

    var board = grid[0][0] + " " + grid [0][1] + " " + grid[0][2];
    board += "\n";
    board += grid[1][0] + " " + grid [1][1] + " " + grid[1][2];
    board += "\n";
    board += grid[2][0] + " " + grid [2][1] + " " + grid[2][2];

    alert(board);
}

function isGameOver() {
    // HERE IS WHERE OUR LOGIC WOULD GO
    // TO SEE IF SOMEONE won

}

最佳答案

这是我想出的:

function isGameOver() {
  for (var i = 0; i < grid.length; i++) {

      if(grid[i][0] == grid[i][1] && grid[i][0]==grid[i][2] && grid[i][0]!=0){
        alert(grid[i][0]+" Wins");
        _win=1;
        return;
      }
  }
  for (var i = 0; i < grid.length; i++) {

      if(grid[0][i] == grid[1][i] && grid[0][i]==grid[2][i]  && grid[0][i]!=0){
        alert(grid[0][i]+" Wins");
        _win=1;
        return;
      }
  }

  if(grid[0][0]==grid[1][1] && grid[0][0] == grid[2][2]  && grid[0][0]!=0){
    alert(grid[0][0]+" Wins");
    _win=1;
        return;
  }

  if(grid[0][2]==grid[1][1] && grid[0][2] == grid[2][0]  && grid[2][0]!=0){
    alert(grid[1][1]+" Wins");
    _win=1;
        return;
  }

}


Working fiddle

这将检查单列,单行或对角线中的数据是否应该相同。如果用户获胜,那么他将无法点击其他任何东西。

关于javascript - 如何提醒井字游戏的获胜者?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34034984/

10-11 20:28