-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtic.js
More file actions
75 lines (62 loc) · 1.9 KB
/
tic.js
File metadata and controls
75 lines (62 loc) · 1.9 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
const board = document.getElementById('board');
const resetButton = document.getElementById('reset');
const messageDisplay = document.getElementById('message');
let currentPlayer = 'X';
let gameState = Array(9).fill(null);
let isGameActive = true;
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],
];
function createBoard() {
gameState.forEach((_, index) => {
const cell = document.createElement('div');
cell.classList.add('cell');
cell.dataset.index = index;
cell.addEventListener('click', handleCellClick);
board.appendChild(cell);
});
}
function handleCellClick(event) {
const clickedCell = event.target;
const clickedCellIndex = clickedCell.dataset.index;
if (gameState[clickedCellIndex] || !isGameActive) {
return;
}
gameState[clickedCellIndex] = currentPlayer;
clickedCell.textContent = currentPlayer;
if (checkWin()) {
messageDisplay.textContent = `Player ${currentPlayer} Wins! 🎉`;
isGameActive = false;
return;
}
if (gameState.every(cell => cell)) {
messageDisplay.textContent = 'It\'s a Tie! 🤝';
isGameActive = false;
return;
}
currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
}
function checkWin() {
return winningConditions.some(condition => {
const [a, b, c] = condition;
return gameState[a] && gameState[a] === gameState[b] && gameState[a] === gameState[c];
});
}
resetButton.addEventListener('click', resetGame);
function resetGame() {
gameState.fill(null);
isGameActive = true;
currentPlayer = 'X';
messageDisplay.textContent = '';
document.querySelectorAll('.cell').forEach(cell => {
cell.textContent = '';
});
}
createBoard();