[go: up one dir, main page]

0% found this document useful (0 votes)
31 views1 page

Script

This document contains JavaScript code to implement a tic-tac-toe game. It defines functions to handle clicks on the game board cells to place marks, toggle between players, and check for a winner. A reset button calls a function to clear the board and restart the game. Cells are added event listeners on click to handle placing marks and checking for a winner each turn.

Uploaded by

Bryan Gosti
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views1 page

Script

This document contains JavaScript code to implement a tic-tac-toe game. It defines functions to handle clicks on the game board cells to place marks, toggle between players, and check for a winner. A reset button calls a function to clear the board and restart the game. Cells are added event listeners on click to handle placing marks and checking for a winner each turn.

Uploaded by

Bryan Gosti
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

var board = document.

getElementById("board");
var turn = "X";

board.addEventListener("click", function(event) {
if (event.target.tagName === "TD") {
if (event.target.textContent === "") {
event.target.textContent = turn;
if (turn === "X") {
turn = "O";
} else {
turn = "X";
}
}
}
});

const cells = document.querySelectorAll('.cell');


const resetButton = document.querySelector('#reset-button');
let turn = 'X';

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


cells[i].addEventListener('click', handleClick);
}

resetButton.addEventListener('click', resetGame);

function handleClick(e) {
const cell = e.target;
cell.innerHTML = turn;
cell.removeEventListener('click', handleClick);
checkWinner();
turn = turn === 'X' ? 'O' : 'X';
}

function resetGame() {
turn = 'X';
for (let i = 0; i < cells.length; i++) {
cells[i].innerHTML = '';
cells[i].addEventListener('click', handleClick);
}
}

function checkWinner() {
const winningCombinations = [
[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 (let i = 0; i < winningCombinations.length; i++) {


const [a, b, c] = winningCombinations[i];
if (cells

You might also like