-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathscript.js
More file actions
67 lines (53 loc) · 1.81 KB
/
Copy pathscript.js
File metadata and controls
67 lines (53 loc) · 1.81 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
'use strict';
// WINNING_COMBOS, checkWinner, getNextPlayer, applyMove, createInitialState
// are provided by game.js, loaded before this script.
const cells = document.querySelectorAll('.cell');
const status = document.getElementById('status');
const restartBtn = document.getElementById('restart');
let state = createInitialState();
function render() {
cells.forEach((cell, i) => {
cell.textContent = state.board[i];
cell.className = 'cell' + (state.board[i] ? ` ${state.board[i].toLowerCase()}` : '');
cell.disabled = state.board[i] !== '' || state.gameOver;
});
}
function setStatus(msg, cls = '') {
status.textContent = msg;
status.className = 'status' + (cls ? ` ${cls}` : '');
}
function handleClick(e) {
const idx = Number(e.currentTarget.dataset.index);
if (state.board[idx] || state.gameOver) return;
const nextBoard = applyMove(state.board, idx, state.current);
if (!nextBoard) return;
state.board = nextBoard;
render();
// Animate the placed cell
cells[idx].classList.add('placed');
const result = checkWinner(state.board);
if (result) {
state.gameOver = true;
if (result.winner) {
result.combo.forEach(i => cells[i].classList.add('winning'));
setStatus(`Player ${result.winner} wins!`, 'win');
} else {
setStatus("It's a draw!", 'draw');
}
// Disable all cells
cells.forEach(c => (c.disabled = true));
return;
}
state.current = getNextPlayer(state.current);
setStatus(`Player ${state.current}'s turn`);
}
function restartGame() {
state = createInitialState();
render();
setStatus(`Player ${state.current}'s turn`);
}
cells.forEach(cell => cell.addEventListener('click', handleClick));
restartBtn.addEventListener('click', restartGame);
// Initial render
render();
setStatus(`Player ${state.current}'s turn`);