-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
80 lines (66 loc) · 2.21 KB
/
Copy pathscript.js
File metadata and controls
80 lines (66 loc) · 2.21 KB
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
79
80
let board = ['', '', '', '', '', '', '', '', ''];
let currentPlayer = 'X';
let gameActive = true;
const statusDisplay = document.querySelector('#status');
function handleCellPlayed(cellIndex) {
board[cellIndex] = currentPlayer;
document.getElementById(cellIndex).innerText = currentPlayer;
}
function handlePlayerChange() {
currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
statusDisplay.innerText = `It's ${currentPlayer}'s turn`;
}
function checkWin() {
const winningConditions = [
[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 < winningConditions.length; i++) {
const [a, b, c] = winningConditions[i];
if (board[a] && board[a] === board[b] && board[a] === board[c]) {
roundWon = true;
break;
}
}
if (roundWon) {
statusDisplay.innerText = `Player ${currentPlayer} has won!`;
gameActive = false;
return true;
}
if (!board.includes('')) {
statusDisplay.innerText = 'It\'s a draw!';
gameActive = false;
return true;
}
return false;
}
function handleCellClick(event) {
const clickedCell = event.target;
const cellIndex = parseInt(clickedCell.getAttribute('id'));
if (board[cellIndex] !== '' || !gameActive) {
return;
}
handleCellPlayed(cellIndex);
if (!checkWin()) {
handlePlayerChange();
}
}
function handleRestartGame() {
board = ['', '', '', '', '', '', '', '', ''];
gameActive = true;
currentPlayer = 'X';
document.querySelectorAll('.cell').forEach(cell => cell.innerText = '');
statusDisplay.innerText = `It's ${currentPlayer}'s turn`;
}
document.querySelectorAll('.cell').forEach(cell => cell.addEventListener('click', handleCellClick));
document.querySelector('#reset').addEventListener('click', handleRestartGame);
const boardElement = document.getElementById('board');
for (let i = 0; i < 9; i++) {
const cell = document.createElement('div');
cell.classList.add('cell');
cell.setAttribute('id', i);
boardElement.appendChild(cell);
}
statusDisplay.innerText = `It's ${currentPlayer}'s turn`;