-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.html
400 lines (372 loc) · 15 KB
/
index.html
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Random Walk Checkers</title>
<style>
body {
font-family: Arial, sans-serif;
display: flex;
flex-direction: column;
align-items: center;
background-color: #f0f0f0;
}
#game-container {
margin-top: 20px;
}
#checkerboard {
display: grid;
grid-template-columns: repeat(8, 50px);
grid-template-rows: repeat(8, 50px);
gap: 1px;
background-color: #ffffff;
padding: 1px;
}
.cell {
width: 50px;
height: 50px;
display: flex;
justify-content: center;
align-items: center;
font-size: 30px;
}
.light {
background-color: #f0d9b5;
}
.dark {
background-color: #b58863;
}
.highlight-red {
background-color: #ff6b6b;
}
.highlight-green {
background-color: #88cc88;
}
.piece {
width: 40px;
height: 40px;
border-radius: 50%;
border: 2px solid #000;
}
.red {
background-color: #d00;
}
.black {
background-color: #000;
}
.king::after {
content: '♔';
color: #fff;
font-size: 24px;
position: relative;
top: -5px;
}
#status {
margin-top: 10px;
font-size: 18px;
}
button {
margin: 10px;
padding: 5px 10px;
font-size: 16px;
}
#speed-control {
margin-top: 10px;
display: flex;
align-items: center;
}
#speed-slider {
width: 200px;
margin: 0 10px;
}
#win-counter {
margin-top: 10px;
font-size: 16px;
}
#last-updated {
margin-top: 5px;
font-size: 14px;
color: #555;
}
</style>
</head>
<body>
<h1>Random Walk Checkers</h1>
<div id="game-container">
<div id="checkerboard"></div>
<div id="status">Red's turn</div>
<button id="start">Start</button>
<button id="stop">Stop</button>
<button id="reset">Reset</button>
<div id="speed-control">
<label for="speed-slider">Speed: </label>
<input type="range" id="speed-slider" min="1" max="100" value="1">
<span id="speed-value">1x</span>
</div>
<div id="win-counter">
Red wins: <span id="red-wins">0</span> | Black wins: <span id="black-wins">0</span>
</div>
<div id="last-updated">Most recent global win recorded at: <span id="update-time">N/A</span></div>
</div>
<script>
const token = 'mzqtjvkjnzzze'; // Yes, you certainly could wreak havoc on the board. We each make our choices.
const baseUrl = 'https://keepthescore.com';
const getInfo = `/api/${token}/board/`;
const score = `/api/${token}/score/`;
class CheckersGame {
constructor() {
this.board = Array(8).fill().map(() => Array(8).fill(null));
this.currentPlayer = 'red';
this.currentPosition = [0, 0];
this.initializeBoard();
}
initializeBoard() {
for (let row = 0; row < 8; row++) {
for (let col = 0; col < 8; col++) {
if ((row + col) % 2 === 1) {
if (row < 3) {
this.board[row][col] = { color: 'black', king: false };
} else if (row > 4) {
this.board[row][col] = { color: 'red', king: false };
}
}
}
}
}
isValidMove(fromRow, fromCol, toRow, toCol) {
if (toRow < 0 || toRow >= 8 || toCol < 0 || toCol >= 8) return false;
if (this.board[toRow][toCol] !== null) return false;
const piece = this.board[fromRow][fromCol];
if (!piece || piece.color !== this.currentPlayer) return false;
const rowDiff = toRow - fromRow;
const colDiff = toCol - fromCol;
if (piece.king) {
if (Math.abs(rowDiff) === 1 && Math.abs(colDiff) === 1) return true;
if (Math.abs(rowDiff) === 2 && Math.abs(colDiff) === 2) {
const jumpedRow = fromRow + rowDiff / 2;
const jumpedCol = fromCol + colDiff / 2;
const jumpedPiece = this.board[jumpedRow][jumpedCol];
return jumpedPiece && jumpedPiece.color !== piece.color;
}
} else {
const direction = piece.color === 'red' ? -1 : 1;
if (rowDiff === direction && Math.abs(colDiff) === 1) return true;
if (rowDiff === 2 * direction && Math.abs(colDiff) === 2) {
const jumpedRow = fromRow + direction;
const jumpedCol = fromCol + colDiff / 2;
const jumpedPiece = this.board[jumpedRow][jumpedCol];
return jumpedPiece && jumpedPiece.color !== piece.color;
}
}
return false;
}
moveRandomly() {
const directions = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]];
let [row, col] = this.currentPosition;
let newRow, newCol;
do {
[newRow, newCol] = directions[Math.floor(Math.random() * directions.length)];
newRow += row;
newCol += col;
} while (newRow < 0 || newRow >= 8 || newCol < 0 || newCol >= 8);
this.currentPosition = [newRow, newCol];
return [newRow, newCol];
}
findValidMove() {
const [targetRow, targetCol] = this.currentPosition;
for (let fromRow = 0; fromRow < 8; fromRow++) {
for (let fromCol = 0; fromCol < 8; fromCol++) {
if (this.board[fromRow][fromCol] && this.board[fromRow][fromCol].color === this.currentPlayer) {
if (this.isValidMove(fromRow, fromCol, targetRow, targetCol)) {
return [fromRow, fromCol];
}
}
}
}
return null;
}
makeMove(fromRow, fromCol, toRow, toCol) {
const piece = this.board[fromRow][fromCol];
this.board[toRow][toCol] = piece;
this.board[fromRow][fromCol] = null;
if (Math.abs(toRow - fromRow) === 2) {
const jumpedRow = (fromRow + toRow) / 2;
const jumpedCol = (fromCol + toCol) / 2;
this.board[jumpedRow][jumpedCol] = null;
}
if ((piece.color === 'red' && toRow === 0) || (piece.color === 'black' && toRow === 7)) {
piece.king = true;
}
this.currentPlayer = this.currentPlayer === 'red' ? 'black' : 'red';
this.currentPosition = [Math.floor(Math.random() * 8), Math.floor(Math.random() * 8)];
}
reset() {
this.board = Array(8).fill().map(() => Array(8).fill(null));
this.currentPlayer = 'red';
this.currentPosition = [0, 0];
this.initializeBoard();
}
checkWinner() {
let redPieces = 0;
let blackPieces = 0;
for (let row = 0; row < 8; row++) {
for (let col = 0; col < 8; col++) {
if (this.board[row][col]) {
if (this.board[row][col].color === 'red') redPieces++;
else blackPieces++;
}
}
}
if (redPieces === 0) return 'black';
if (blackPieces === 0) return 'red';
return null;
}
}
const game = new CheckersGame();
const boardElement = document.getElementById('checkerboard');
const statusElement = document.getElementById('status');
const startButton = document.getElementById('start');
const stopButton = document.getElementById('stop');
const resetButton = document.getElementById('reset');
const speedSlider = document.getElementById('speed-slider');
const speedValue = document.getElementById('speed-value');
const redWins = document.getElementById('red-wins');
const blackWins = document.getElementById('black-wins');
const updateTime = document.getElementById('update-time');
let timeoutId = null;
let baseSpeed = 200;
async function getWinCounts() {
try {
const response = await fetch(baseUrl + getInfo);
const data = await response.json();
if (response.status === 200) {
const players = data.players;
let blackScore = 0, redScore = 0;
players.forEach(player => {
if (player.name.toLowerCase() === 'black') {
blackScore = player.score;
} else if (player.name.toLowerCase() === 'red') {
redScore = player.score;
}
});
const lastUpdated = data.board.update_date;
redWins.textContent = redScore;
blackWins.textContent = blackScore;
updateTime.textContent = lastUpdated;
}
} catch (error) {
console.error('Error fetching win counts:', error);
}
}
async function incrementScore(playerName) {
try {
const response = await fetch(baseUrl + getInfo);
const data = await response.json();
const players = data.players;
const player = players.find(p => p.name.toLowerCase() === playerName.toLowerCase());
if (player) {
const playerId = player.id;
const payload = {
player_id: playerId,
score: 1,
operation: "increment"
};
const incrementResponse = await fetch(baseUrl + score, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(payload)
});
if (incrementResponse.status === 200) {
getWinCounts(); // Refresh the counts
} else {
console.error('Error incrementing score:', incrementResponse.statusText);
}
}
} catch (error) {
console.error('Error fetching player ID:', error);
}
}
function updateBoard() {
boardElement.innerHTML = '';
for (let row = 0; row < 8; row++) {
for (let col = 0; col < 8; col++) {
const cell = document.createElement('div');
cell.className = `cell ${(row + col) % 2 === 0 ? 'light' : 'dark'}`;
if (row === game.currentPosition[0] && col === game.currentPosition[1]) {
cell.classList.add('highlight-red');
}
const piece = game.board[row][col];
if (piece) {
const pieceElement = document.createElement('div');
pieceElement.className = `piece ${piece.color}`;
if (piece.king) pieceElement.classList.add('king');
cell.appendChild(pieceElement);
}
boardElement.appendChild(cell);
}
}
statusElement.textContent = `${game.currentPlayer.charAt(0).toUpperCase() + game.currentPlayer.slice(1)}'s turn`;
}
function calculateDelay() {
const speed = parseInt(speedSlider.value);
return baseSpeed / speed;
}
function step() {
const [toRow, toCol] = game.moveRandomly();
updateBoard();
const validMove = game.findValidMove();
if (validMove) {
const [fromRow, fromCol] = validMove;
timeoutId = setTimeout(() => {
boardElement.children[toRow * 8 + toCol].classList.remove('highlight-red');
boardElement.children[toRow * 8 + toCol].classList.add('highlight-green');
timeoutId = setTimeout(() => {
game.makeMove(fromRow, fromCol, toRow, toCol);
updateBoard();
const winner = game.checkWinner();
if (winner) {
incrementScore(winner).then(() => {
statusElement.textContent = `${winner.charAt(0).toUpperCase() + winner.slice(1)} wins!`;
stopGame();
});
} else {
timeoutId = setTimeout(step, calculateDelay());
}
}, calculateDelay());
}, calculateDelay());
} else {
timeoutId = setTimeout(step, calculateDelay());
}
}
function startGame() {
if (!timeoutId) {
step();
startButton.disabled = true;
stopButton.disabled = false;
}
}
function stopGame() {
clearTimeout(timeoutId);
timeoutId = null;
startButton.disabled = false;
stopButton.disabled = true;
}
function resetGame() {
stopGame();
game.reset();
updateBoard();
}
startButton.addEventListener('click', startGame);
stopButton.addEventListener('click', stopGame);
resetButton.addEventListener('click', resetGame);
speedSlider.addEventListener('input', () => {
speedValue.textContent = `${speedSlider.value}x`;
});
updateBoard();
getWinCounts();
</script>
</body>
</html>