Все еще пытаюсь выучить 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);