-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
78 lines (70 loc) · 2.17 KB
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
const statusDisplay = document.querySelector('.status');
const restartButton = document.getElementById('restartButton');
const gameBoard = document.getElementById('gameBoard');
const cells = document.querySelectorAll('[data-cell]');
let currentPlayer = 'X';
let gameActive = true;
function handleCellPlayed(clickedCell, clickedCellIndex) {
gameBoard.children[clickedCellIndex].textContent = currentPlayer;
}
function handlePlayerChange() {
currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
statusDisplay.textContent = `Player ${currentPlayer}'s Turn`;
}
function checkWin() {
// Win conditions: 3 rows, 3 columns, 2 diagonals
const winConditions = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6]
];
let roundWon = false;
for (let i = 0; i < winConditions.length; i++) {
const winCondition = winConditions[i];
const a = gameBoard.children[winCondition[0]].textContent;
const b = gameBoard.children[winCondition[1]].textContent;
const c = gameBoard.children[winCondition[2]].textContent;
if ([a, b, c].includes("")) {
continue;
}
if (a === b && b === c) {
roundWon = true;
break;
}
}
if (roundWon) {
statusDisplay.textContent = `Player ${currentPlayer} Wins!`;
gameActive = false;
return;
}
// Check for tie
const allPlayed = Array.from(gameBoard.children).every(cell => cell.textContent !== '');
if (allPlayed) {
statusDisplay.textContent = "Game is a Tie!";
gameActive = false;
} else {
handlePlayerChange();
}
}
function handleCellClick(event) {
const clickedCell = event.target;
const clickedCellIndex = Array.from(gameBoard.children).indexOf(clickedCell);
if (clickedCell.textContent !== '' || !gameActive) {
return;
}
handleCellPlayed(clickedCell, clickedCellIndex);
checkWin();
}
function handleRestartGame() {
gameActive = true;
currentPlayer = 'X';
statusDisplay.textContent = "Player X's Turn";
Array.from(gameBoard.children).forEach(cell => cell.textContent = '');
}
cells.forEach(cell => cell.addEventListener('click', handleCellClick));
restartButton.addEventListener('click', handleRestartGame);