-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
412 lines (350 loc) · 13.1 KB
/
script.js
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
401
402
403
404
405
406
407
408
409
410
411
412
// https://github.com/jayasurian123/fen-validator
// js-chess-engine currently lacks a validator so use this
import validateFEN from './fen-validator/index.js';
// https://github.com/josefjadrny/js-chess-engine
// Option 1 - With in-memory (should allow us to deal with promotion)
import { Game } from './js-chess-engine/lib/js-chess-engine.mjs';
let game = new Game();
const fenPositions = ['a8', 'b8', 'c8', 'd8', 'e8', 'f8', 'g8', 'h8', 'a7', 'b7', 'c7', 'd7', 'e7', 'f7', 'g7', 'h7', 'a6', 'b6', 'c6', 'd6', 'e6', 'f6', 'g6', 'h6', 'a5', 'b5', 'c5', 'd5', 'e5', 'f5', 'g5', 'h5', 'a4', 'b4', 'c4', 'd4', 'e4', 'f4', 'g4', 'h4', 'a3', 'b3', 'c3', 'd3', 'e3', 'f3', 'g3', 'h3', 'a2', 'b2', 'c2', 'd2', 'e2', 'f2', 'g2', 'h2', 'a1', 'b1', 'c1', 'd1', 'e1', 'f1', 'g1', 'h1'];
const pieces = ['r', 'n', 'b', 'q', 'k', 'p', 'R', 'N', 'B', 'Q', 'K', 'P'];
const speed = 300;
const game_version = '0.0.2';
let puzzle_solved = false;
let puzzle_solved_clean = true;
let currentPuzzle = '';
let currentFEN = '';
let currentStatus = '';
let lastPuzzleMoveIndex = 0;
let puzzles = {};
let params = '';
let playerRating = 400;
window.addEventListener("DOMContentLoaded", (event) => {
setUpBoard();
setUpButtons();
params = getURLSearchParams();
// force set player rating if in params and is a number
if (params.get('rating') != null && !isNaN(params.get('rating'))) {
playerRating = params.get('rating');
storeLocalPlayerRating(playerRating);
} else {
playerRating = getLocalPlayerRating();
}
fetch('./puzzles/offline/puzzles.csv')
.then(response => response.text())
.then(csvString => {
puzzles = initPuzzles(csvString);
if (puzzles['param'] == null) {
loadRandomPuzzle();
} else {
loadPuzzle(puzzles['param']);
}
})
.catch(error => {
console.error('Error fetching puzzles:', error);
});
});
function setUpBoard() {
document.getElementById("no-js").remove();
const board = document.getElementById('board');
const squares = board.querySelectorAll('div');
squares.forEach(square => {
square.addEventListener('pointerdown', function () {
squareClicked(square)
});
});
const squareClicked = (square) => {
console.log(`${square} was clicked!`);
if (puzzle_solved) {
return;
}
// You may be temped to refactor, but why?
// unselectAll is catching **edge case** for multiple selected squares
// you still need to unselect the selected square, if user wants to undo selection
if (square.classList.contains('selected')) {
unselectAll();
} else if (square.classList.contains('circle')) {
const selected = document.querySelector('.selected');
unselectAll();
playerMove(selected.id, square.id);
} else {
unselectAll();
let containsPiece = false;
for (let i = 0; i < pieces.length; i++) {
if (square.classList.contains(pieces[i])) {
containsPiece = true;
break
}
}
// only add selected if piece exists
if (containsPiece) {
selectPiece(square);
}
}
}
}
function setUpButtons() {
const title = document.getElementById('title');
const menuButton = document.getElementById('menu-button');
const closeButtons = document.querySelectorAll('.close-button');
title.addEventListener('dblclick', function () {
let element = document.getElementById('debug');
element.style.display = element.style.display === 'none' ? 'block' : 'none';
});
menuButton.addEventListener('pointerdown', function () {
document.getElementById('info-modal').style.display = 'flex';
});
menuButton.addEventListener('pointerdown', function () {
document.getElementById('info-modal').style.display = 'flex';
});
closeButtons.forEach(closeButton => {
closeButton.addEventListener('pointerdown', function () {
this.parentNode.parentNode.style.display = 'none';
});
});
}
function unselectAll() {
const board = document.getElementById('board');
const squares = board.querySelectorAll('div');
squares.forEach(square => {
square.classList.remove('selected');
square.classList.remove('circle');
});
}
function clearBoard() {
const board = document.getElementById('board');
const squares = board.querySelectorAll('div');
squares.forEach(square => {
square.classList = '';
});
}
function loadBoard(fen) {
const fenArr = fen.split(' ');
const piecePlacement = fenArr[0];
clearBoard();
// replace numbers with spaces and remove forward slashes
let newPiecePlacement = piecePlacement.replace(/[0-8/]/g, (match) => {
if (match === '/') {
return ''; // remove forward slash
} else {
return " ".repeat(parseInt(match)); // repeat " " for the number of times matched
}
});
// add pieces to board
for (let i = 0; i < newPiecePlacement.length; i++) {
const square = document.getElementById(fenPositions[i]);
if (newPiecePlacement[i] !== ' ') {
square.classList.add(newPiecePlacement[i]);
}
}
}
function flipBoard(shouldFlip) {
const board = document.getElementById('board');
if (shouldFlip) {
board.classList.add('flip');
} else {
board.classList.remove('flip');
}
}
function selectPiece(element) {
const selectedPiece = currentStatus.pieces[element.id.toUpperCase()];
let canSelectPiece = false;
if(currentStatus.turn === 'white' && selectedPiece === selectedPiece.toUpperCase()) {
// white turn and white piece selected
canSelectPiece = true;
} else if(currentStatus.turn === 'black' && selectedPiece === selectedPiece.toLowerCase()) {
// black turn and black piece selected
canSelectPiece = true;
}
const selectedPieceValidMoves = currentStatus.moves[element.id.toUpperCase()];
if(canSelectPiece) {
element.classList.add('selected');
for (let i = 0; i < selectedPieceValidMoves?.length; i++) {
const square = document.getElementById(selectedPieceValidMoves[i].toLowerCase());
square.classList.add('circle');
}
}
}
function computerMove(from, to) {
// wait 1 second then move piece
setTimeout(() => {
movePiece(from, to);
}, speed);
}
function playerMove(from, to) {
let best_move = currentPuzzle.moves[lastPuzzleMoveIndex+1];
// check if move is solution - slice to avoid possible promotion char
if(best_move.slice(0,4) === `${from}${to}`) {
lastPuzzleMoveIndex++;
// if best_move is length 5, it has promotion
if (best_move.length === 5) {
// grab char for promotion
puzzleMoveGood(from, to, best_move.slice(4));
} else {
puzzleMoveGood(from, to);
}
} else {
puzzleMoveBad(from, to);
}
}
function puzzleMoveGood(from, to, promote = null) {
movePiece(from, to, promote);
lastPuzzleMoveIndex++;
if(currentStatus.isFinished || lastPuzzleMoveIndex >= currentPuzzle.moves.length) {
updateMessage('<p>Puzzle complete!</p><p class="show">Click for next puzzle.</p>', 'good');
puzzle_solved = true;
if(puzzle_solved_clean) {
calculateRatingChange(currentPuzzle.rating, true);
}
enableNextPuzzle();
} else {
updateMessage('<p>Good move, keep going.</p>');
setTimeout(() => {
computerMove(currentPuzzle.moves[lastPuzzleMoveIndex].substring(0, 2), currentPuzzle.moves[lastPuzzleMoveIndex].substring(2, 4));
}, speed);
}
}
function puzzleMoveBad(from, to) {
const backupStatus = currentFEN;
const backupPrevious = document.querySelectorAll('.previous');
movePiece(from, to);
updateMessage('There is a better move, try again.', 'bad');
puzzle_solved_clean = false;
calculateRatingChange(currentPuzzle.rating, false);
setTimeout(() => {
loadFen(backupStatus);
backupPrevious.forEach(element => {
element.classList.add('previous');
});
}, speed);
}
function movePiece(from, to, promote = null) {
game.move(from, to);
if (promote) {
if (currentStatus.turn === "white") {
game.setPiece(to,promote.toUpperCase());
} else {
game.setPiece(to,promote.toLowerCase());
}
}
currentStatus = game.exportJson();
currentFEN = game.exportFEN(currentStatus);
loadBoard(currentFEN);
document.getElementById(from).classList.add('previous');
document.getElementById(to).classList.add('previous');
}
const loadRandomPuzzle = () => {
const minRating = Math.max(0, getLocalPlayerRating() - 100);
const maxRating = getLocalPlayerRating() + 100;
const eligibleRatings = Object.keys(puzzles).filter(rating => rating >= minRating && rating <= maxRating);
if (eligibleRatings.length === 0) {
console.error('No puzzles found within the specified rating range.');
return;
}
const randomRating = eligibleRatings[Math.floor(Math.random() * eligibleRatings.length)];
const randomPuzzle = puzzles[randomRating][Math.floor(Math.random() * puzzles[randomRating].length)];
loadPuzzle(randomPuzzle);
puzzle_solved_clean = true;
disableNextPuzzle();
}
function updateMessage(text, type = '') {
const message = document.getElementById('message');
message.innerHTML = text;
message.classList = type;
}
function loadFen(fen) {
if (validateFEN(fen)) {
currentFEN = fen;
game = new Game(currentFEN);
currentStatus = game.exportJson();
loadBoard(currentFEN);
} else {
console.log('invalid FEN');
}
}
function loadPuzzle(puzzle) {
puzzle_solved = false;
currentPuzzle = puzzle;
loadFen(currentPuzzle.fen);
if(currentStatus.turn === 'white') {
updateMessage('<p>Find the best move for <u>black</u>.</p>');
flipBoard(true);
} else {
updateMessage('<p>Find the best move for <u>white</u>.</p>');
flipBoard(false);
}
computerMove(currentPuzzle.moves[0].substring(0, 2), currentPuzzle.moves[0].substring(2, 4));
lastPuzzleMoveIndex = 0;
updateGameInfo();
updateDebug();
}
function enableNextPuzzle() {
document.getElementById('message').addEventListener('click', loadRandomPuzzle);
document.getElementById('message').classList.add('clickable');
}
function disableNextPuzzle() {
document.getElementById('message').removeEventListener('click', loadRandomPuzzle);
}
function updateDebug() {
document.getElementById('debug').innerHTML = `
<strong>DEBUG INFO</strong>:
Puzzle ID: <a href="https://lichess.org/training/${currentPuzzle.puzzle_id}">${currentPuzzle.puzzle_id}</a> -
Puzzle Rating: ${currentPuzzle.rating} -
Player Rating: ${getLocalPlayerRating()}
`;
}
function updateGameInfo() {
document.getElementById('game-info').innerHTML = `
<em>Build v${game_version}</em><br>
Current Rating: <strong>${getLocalPlayerRating()}</strong><br>
`;
}
function initPuzzles(csvString) {
const lines = csvString.split('\n');
const puzzles = {};
lines.forEach(line => {
if (line.trim() !== '') {
const [puzzle_id, fen, moves, rating] = line.split(',');
const puzzle = { puzzle_id, fen, moves: moves.split(' '), rating };
if (!puzzles[rating]) {
puzzles[rating] = [];
}
puzzles[rating].push(puzzle);
// if a puzzle id was specified via URL
if (params.get('puzzle') === puzzle_id) {
puzzles['param'] = puzzle;
}
}
});
return puzzles;
}
function calculateRatingChange(puzzleRating, solved) {
const kFactor = 32; // K-factor determines the maximum rating change per game
const playerWinProbability = 1 / (1 + Math.pow(10, (puzzleRating - getLocalPlayerRating()) / 400));
const ratingChange = Math.round(kFactor * (solved ? 1 - playerWinProbability : 0 - playerWinProbability));
storeLocalPlayerRating(getLocalPlayerRating() + ratingChange);
}
// Store the player's rating in localStorage, if available
function storeLocalPlayerRating(rating) {
try {
localStorage.setItem("puzzleChessplayerRating", rating);
} catch (error) {
console.error("Error storing player rating:", error);
}
playerRating = rating;
}
// Retrieve the player's rating from localStorage, if available
function getLocalPlayerRating() {
try {
const rating = localStorage.getItem("puzzleChessplayerRating");
return rating ? parseInt(rating, 10) : 400;
} catch (error) {
console.error("Error retrieving player rating:", error);
return playerRating;
}
}
function getURLSearchParams() {
// Get the full URL (Example: https://puzzlechess.ca/?puzzle=123456)
const url = new URL(window.location.href);
// Access the URLSearchParams object
return new URLSearchParams(url.search);
}