-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
212 lines (175 loc) · 6.63 KB
/
Copy pathscript.js
File metadata and controls
212 lines (175 loc) · 6.63 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
class TicTacToe {
constructor() {
this.board = Array(16).fill(null);
this.currentPlayer = 'X';
this.gameActive = true;
this.humanPlayer = 'X';
this.computerPlayer = 'O';
this.serverUrl = window.location.origin;
this.initializeGame();
}
initializeGame() {
this.createBoard();
this.updateDisplay();
this.attachEventListeners();
}
createBoard() {
const gameBoard = document.getElementById('game-board');
gameBoard.innerHTML = '';
for (let i = 0; i < 16; i++) {
const cell = document.createElement('div');
cell.classList.add('cell');
cell.dataset.index = i;
cell.addEventListener('click', () => this.handleCellClick(i));
gameBoard.appendChild(cell);
}
}
attachEventListeners() {
document.getElementById('reset-button').addEventListener('click', () => this.resetGame());
}
handleCellClick(index) {
if (!this.gameActive || this.board[index] || this.currentPlayer !== this.humanPlayer) {
return;
}
this.makeMove(index, this.humanPlayer);
if (this.gameActive && !this.isBoardFull()) {
setTimeout(async () => {
await this.computerMove();
}, 500);
}
}
makeMove(index, player) {
this.board[index] = player;
this.updateCell(index, player);
if (this.checkWinner()) {
this.endGame(`${player === this.humanPlayer ? 'You' : 'Computer'} win!`);
this.highlightWinningCells();
return;
}
if (this.isBoardFull()) {
this.endGame("It's a tie!");
return;
}
this.currentPlayer = player === 'X' ? 'O' : 'X';
this.updateDisplay();
}
async computerMove() {
console.log('Computer move called', {
gameActive: this.gameActive,
currentPlayer: this.currentPlayer,
computerPlayer: this.computerPlayer
});
if (!this.gameActive || this.currentPlayer !== this.computerPlayer) {
console.log('Computer move blocked');
return;
}
try {
console.log('Requesting computer move from server...');
const response = await fetch(`${this.serverUrl}/api/computer-move`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ board: this.board })
});
if (!response.ok) {
throw new Error(`Server error: ${response.status}`);
}
const data = await response.json();
console.log('Computer move received:', data.move);
this.makeMove(data.move, this.computerPlayer);
} catch (error) {
console.error('Error getting computer move:', error);
// Fallback to random move if server is unavailable
const availableMoves = [];
for (let i = 0; i < 16; i++) {
if (!this.board[i]) {
availableMoves.push(i);
}
}
if (availableMoves.length > 0) {
const randomMove = availableMoves[Math.floor(Math.random() * availableMoves.length)];
this.makeMove(randomMove, this.computerPlayer);
}
}
}
checkWinner() {
return this.checkWinnerForBoard(this.board);
}
checkWinnerForBoard(board) {
const winPatterns = [
[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15],
[0, 4, 8, 12], [1, 5, 9, 13], [2, 6, 10, 14], [3, 7, 11, 15],
[0, 5, 10, 15], [3, 6, 9, 12]
];
for (let pattern of winPatterns) {
const [a, b, c, d] = pattern;
if (board[a] && board[a] === board[b] && board[a] === board[c] && board[a] === board[d]) {
this.winningPattern = pattern;
return board[a];
}
}
return null;
}
highlightWinningCells() {
if (this.winningPattern) {
this.winningPattern.forEach(index => {
const cell = document.querySelector(`[data-index="${index}"]`);
cell.classList.add('winning');
});
}
}
isBoardFull() {
return this.board.every(cell => cell !== null);
}
updateCell(index, player) {
const cell = document.querySelector(`[data-index="${index}"]`);
cell.textContent = player;
cell.classList.add(player.toLowerCase());
cell.classList.add('disabled');
}
updateDisplay() {
const currentPlayerElement = document.getElementById('current-player');
const gameStatusElement = document.getElementById('game-status');
if (this.gameActive) {
if (this.currentPlayer === this.humanPlayer) {
currentPlayerElement.textContent = 'X (You)';
gameStatusElement.textContent = 'Your turn!';
gameStatusElement.className = 'game-status';
} else {
currentPlayerElement.textContent = 'O (Computer)';
gameStatusElement.textContent = 'Computer is thinking...';
gameStatusElement.className = 'game-status loading';
}
}
}
endGame(message) {
this.gameActive = false;
const gameStatusElement = document.getElementById('game-status');
gameStatusElement.textContent = message;
if (message.includes('You win')) {
gameStatusElement.className = 'game-status game-won';
} else if (message.includes('Computer win')) {
gameStatusElement.className = 'game-status game-over';
} else {
gameStatusElement.className = 'game-status';
}
const cells = document.querySelectorAll('.cell');
cells.forEach(cell => cell.classList.add('disabled'));
}
resetGame() {
this.board = Array(16).fill(null);
this.currentPlayer = 'X';
this.gameActive = true;
this.winningPattern = null;
const cells = document.querySelectorAll('.cell');
cells.forEach(cell => {
cell.textContent = '';
cell.className = 'cell';
});
this.updateDisplay();
}
}
document.addEventListener('DOMContentLoaded', () => {
new TicTacToe();
});