为什么我需要两次单击两次才能触发onclick事件-tictactoe

时间:2020-07-09 16:45:38

标签: javascript onclick

仍然尝试学习Javascript-这似乎是一个常见问题,但我无法确定分辨率。简单的tictactoe javascript和HTML,但为了使其正常工作,我必须首先在某个正方形中单击两次。在该事件之后,总是单击一次。另外,它在没有onclick=playGame()的情况下也可以工作,但是我尝试添加当前未包含的其他一些事件,并将每个事件设置为单独的函数,因此我认为我需要onclick=playGame()以后再做。预先感谢您的帮助。

// jshint esversion: 6


//Sets the number of boxes to a constant
//creats an Global immutable constant variable.  
const boxes = document.querySelectorAll("img");


//stores player turn Global variable currentPlayer
let currentPlayer = "cross.png";

//stores the status of the game, whether its over or still in play Global variable gameStatus
let gameStatus = "Game On";

//Creates a counter Global variable count
let count = 0;

//Counts number of x wins Global variable xwins
let xwins = 0;

//Counts number of o wins Global variable owins
let owins = 0;


//Counts number of draws Global variable draws
let draw = 0;


function playGame() {

  for (const box of boxes) {

    //Checking the boxes for a click
    box.addEventListener("click", () => {

      //Determine if the box is blank
      if (box.src.includes("blank.jpg") && gameStatus == "Game On") {

        //If the box is blank is change the value of the box image tag to the current player    
        box.src = currentPlayer;


        //If the box currentPlayer is cross     
        if (currentPlayer == "cross.png") {
          //Change currentPlayer to zero 
          currentPlayer = "zero.png";

        } else {
          //Change currentPlayer to cross   
          currentPlayer = "cross.png";

        }


        //increment counter
        count++;


        //run the check winner function everytime
        const winner = checkWinner();


        if (winner) {

          //ternary opertator - assigns name the value of X if true, O if false
          const name = winner.includes("cross") ? "X" : "O";

          //In the h2 html print the winnner
          document.querySelector("h2").innerHTML = `Player ${name} wins`;

          //check who one and increment their total
          if (name == "X") {

            xwins++;

          } else {

            owins++;

          }

          //Runs the function to show the stats
          showStat();

          //Tells user to start a new game
          newGame();

          gameStatus = "Game Off";
          /*document.addEventListener("click", function(){
            document.getElementById("demo").innerHTML = "New Game";})
          //reset();
             */

        }

        //Checks to see if all 9 boxes are filled and there is no winner to determine a draw
        if (count == 9 && winner === null) {
          draw++;
          document.querySelector("h2").innerHTML = "This match is a draw!";

          showStat();
          newGame();

        }
      }

    });
  }

}

//brute force function to check for a winner
function checkWinner() {

  const winning = [

    [0, 1, 2],

    [3, 4, 5],

    [6, 7, 8],

    [0, 3, 6],

    [1, 4, 7],

    [2, 5, 8],

    [0, 4, 8],

    [2, 4, 6]

  ];

  for (const possibility of winning) {

    const player = boxes[possibility[0]].src;

    let winner = true;

    for (let i = 0; i < possibility.length; i++) {

      if (boxes[possibility[i]].src.includes("blank")) {

        winner = false;

        break;

      }

      if (boxes[possibility[i]].src !== player) {

        winner = false;

        break;

      }

    }

    if (winner) {

      return player;

    }

  }

  return null;

}

//Function for printing the stats
function showStat() {

  document.querySelector(

    "p"

  ).innerHTML = `X-Wins: ${xwins} <br/>O-Wins: ${owins}<br/>Draw: ${draw}`;


}


//Function for reseting the board
function reset() {

  for (const box of boxes) {

    box.src = "blank.jpg";

  }

  count = 0;

  currentPlayer = "cross.png";

  document.querySelector("h2").innerHTML = "";

  showStat();

  gameStatus = "Game On";

  document.querySelector(

    "h3"

  ).innerHTML = ``;

}


//Function for telling the user this game is over
function newGame() {
  document.querySelector(

    "h3"

  ).innerHTML = `New Game`;


}

reset();

//Listener for if someone clicks reset button
document.querySelector("button").addEventListener("click", reset);
<!DOCTYPE html>

<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <!-- Replace this with your own information -->
  <meta name="author" content="" />
  <title>ticTacToeFireTwice</title>
  <link rel="stylesheet" href="tictactoefiretwice_style.css" type="text/css">
  <script src="tictactoefiretwice.js" defer></script>

  <!--   -->

</head>

<body>
  <h1> tictactoefiretwice </h1>

  <table>

    <tr>

      <td>

        <img id="1" onclick="playGame()" src="blank.jpg" alt="starting image of Chichen Itza" />

      </td>

      <td>

        <img id="2" onclick="playGame()" src="blank.jpg" alt="starting image of Chichen Itza" />

      </td>

      <td>

        <img id="3" onclick="playGame()" src="blank.jpg" alt="starting image of Chichen Itza" />

      </td>

    </tr>

    <tr>

      <td>

        <img id="4" onclick="playGame()" src="blank.jpg" alt="starting image of Chichen Itza" />

      </td>

      <td>

        <img id="5" onclick="playGame()" src="blank.jpg" alt="starting image of Chichen Itza" />

      </td>

      <td>

        <img id="6" onclick="playGame()" src="blank.jpg" alt="starting image of Chichen Itza" />

      </td>

    </tr>

    <tr>

      <td>

        <img id="7" onclick="playGame()" src="blank.jpg" alt="starting image of Chichen Itza" />

      </td>

      <td>

        <img id="8" onclick="playGame()" src="blank.jpg" alt="starting image of Chichen Itza" />

      </td>

      <td>

        <img id="9" onclick="playGame()" src="blank.jpg" alt="starting image of Chichen Itza" />

      </td>

    </tr>

  </table>

  <h2></h2>

  <div class="scoreboard">
    <h3 id="demo"></h3>
    <p></p>

    <button id="reset">Reset</button>
  </div>

</body>

</html>

0 个答案:

没有答案