forked from chess-mazes/chess-mazes
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.js
279 lines (235 loc) · 9.01 KB
/
main.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
import puzzles from "./puzzles.js";
import isValidMove from "./moveValidator.js";
import pieceImages from "./assets.js";
const board = document.getElementById("board");
let curPuzzle = 0;
let solvedPuzzles = new Set();
let pieces = JSON.parse(JSON.stringify(puzzles[curPuzzle]));
let draggedPiece = null;
let startCol, startRow;
function setupButtonHandlers() {
document.getElementById("btnPrev").addEventListener("click", () => {
curPuzzle--;
if (curPuzzle < 0) {
curPuzzle = puzzles.length - 1;
}
document.location.hash = curPuzzle + 1;
pieces = JSON.parse(JSON.stringify(puzzles[curPuzzle]));
drawBoard();
});
document.getElementById("btnNext").addEventListener("click", () => {
curPuzzle++;
if (curPuzzle >= puzzles.length) {
curPuzzle = 0;
}
document.location.hash = curPuzzle + 1;
pieces = JSON.parse(JSON.stringify(puzzles[curPuzzle]));
drawBoard();
});
}
function drawBoard() {
let solvedText = solvedPuzzles.has(curPuzzle + 1) ? "✅" : "";
document.getElementById("page-title").innerText = `Chess Maze #${curPuzzle + 1} ${solvedText}`;
board.innerHTML = "";
for (let i = 0; i < 8; i++) {
for (let j = 0; j < 8; j++) {
const square = document.createElement("div");
square.classList.add("square");
square.classList.add((i + j) % 2 ? "black" : "white");
square.dataset.row = i;
square.dataset.col = j;
const piece = pieces[i * 8 + j];
if (piece !== "") {
const img = document.createElement("img");
img.src = pieceImages[piece];
img.style.position = 'absolute';
square.appendChild(img);
}
board.appendChild(square);
// Draw coordinates at the edge of the board, at the corner of the square
if (j === 0) {
const text = document.createElement("div");
text.classList.add("letter-coords");
text.innerHTML = 8 - i;
square.appendChild(text);
// align the element to the left and top of the square
}
if (i === 7) {
const text = document.createElement("div");
text.classList.add("number-coords");
text.innerHTML = String.fromCharCode(97 + j);
square.appendChild(text);
// align the element to the right and bottom of the square
text.style.marginLeft = "auto";
text.style.marginTop = "auto";
}
}
}
const squares = document.querySelectorAll(".square");
const pieceElements = document.querySelectorAll(".square img");
for (let pieceElement of pieceElements) {
pieceElement.draggable = true;
}
const [whiteCol, whiteRow] = locateWhitePiece(pieces);
for (let square of squares) {
square.addEventListener("dragstart", dragStart);
square.addEventListener("dragover", dragOver);
square.addEventListener("drop", dragDrop);
square.addEventListener("click", () => {
const col = parseInt(square.dataset.col);
const row = parseInt(square.dataset.row);
// Check if white piece can move to the square
const [startCol, startRow] = locateWhitePiece(pieces);
if (isValidMove(pieces, startCol, startRow, col, row)) {
moveWhitePieceTo(col, row);
drawBoard();
}
});
// if white piece can move to the square, highlight it
// if (isValidMove(pieces, whiteCol, whiteRow, parseInt(square.dataset.col), parseInt(square.dataset.row))) {
// square.classList.add("highlight");
// } else {
// square.classList.remove("highlight");
// }
}
}
function coordsToLocation(row, col) {
const letters = ["a", "b", "c", "d", "e", "f", "g", "h"];
return letters[col] + (8 - row);
}
function dragStart(event) {
draggedPiece = event.target;
draggedPiece.classList.add("dragged");
startCol = parseInt(event.target.parentElement.dataset.col);
startRow = parseInt(event.target.parentElement.dataset.row);
}
function dragOver(event) {
event.preventDefault();
}
function resetBoard() {
pieces = JSON.parse(JSON.stringify(puzzles[curPuzzle]));
drawBoard();
}
function moveWhitePieceTo(col, row) {
const [startCol, startRow] = locateWhitePiece(pieces);
let movedPiece = document.querySelector(`[data-row="${startRow}"][data-col="${startCol}"] img`);
let targetSquare = document.querySelector(`[data-row="${row}"][data-col="${col}"]`);
const piece = pieces[startRow * 8 + startCol];
pieces[startRow * 8 + startCol] = "";
pieces[row * 8 + col] = piece;
// remove only child img element from target square
[...targetSquare.children].forEach(
child => child.tagName.toLowerCase() === "img" && child.remove()
);
targetSquare.appendChild(movedPiece);
if (isThreatened(col, row)) {
Swal.fire({
title: 'Try again!',
text: 'You are threatened by a black piece.',
icon: 'error',
//timer: 2000,
timerProgressBar: true,
confirmButtonText: 'OK',
customClass: {
popup: 'my-swal'
}
}).then(() => {
resetBoard();
});
} else if (isThreatened(...locateBlackKing(pieces))) {
Swal.fire({
title: 'Good job!',
text: 'You have successfully checked the black king.',
icon: 'success',
timer: 2000,
timerProgressBar: true,
confirmButtonText: 'OK',
customClass: {
popup: 'my-swal'
}
}).then(() => {
solvedPuzzles.add(curPuzzle + 1);
localStorage.setItem("solvedPuzzles", JSON.stringify(Array.from(solvedPuzzles)));
document.getElementById("txtSolved").innerText = `Solved: [${Array.from(solvedPuzzles).sort().join(", ")}]`;
document.getElementById("btnNext").click();
});
};
}
function dragDrop(event) {
draggedPiece.classList.remove("dragged");
let target = event.target;
if (event.target.tagName.toLowerCase() === "img") {
console.log("dropped on image");
target = event.target.parentElement;
};
const endCol = parseInt(target.dataset.col);
const endRow = parseInt(target.dataset.row);
console.log(`dragEnd: {${startRow}, ${startCol}} -> {${endRow}, ${endCol}}`);
// Check if start and end are the same
if (startCol === endCol && startRow === endRow) {
return;
}
if (isValidMove(pieces, startCol, startRow, endCol, endRow, true)) {
moveWhitePieceTo(endCol, endRow);
drawBoard();
}
draggedPiece = null;
}
function isThreatened(col, row, debug = false) {
const isWhite = pieces[row * 8 + col].toLowerCase() !== pieces[row * 8 + col];
// Check if any piece can move to the square
for (let i = 0; i < 8; i++) {
for (let j = 0; j < 8; j++) {
if (pieces[i * 8 + j] === "") continue;
if (debug) console.log(`Checking if ${pieces[i * 8 + j]} at ${coordsToLocation(i, j)} can move to ${coordsToLocation(row, col)}`);
if (isValidMove(pieces, j, i, col, row, true, isWhite)) {
if (debug) console.log(`Threatened by ${pieces[i * 8 + j]} at ${coordsToLocation(i, j)}`);
return true;
}
}
}
return false;
}
function locateBlackKing(board) {
for (let i = 0; i < 8; i++) {
for (let j = 0; j < 8; j++) {
if (board[i * 8 + j] === "k") {
return [j, i];
}
}
}
}
function locateWhitePiece(board) {
for (let i = 0; i < 8; i++) {
for (let j = 0; j < 8; j++) {
let piece = board[i * 8 + j];
if (piece !== "" && piece.toLowerCase() !== piece) {
return [j, i];
}
}
}
}
function loadSolvedPuzzles() {
const solved = localStorage.getItem("solvedPuzzles");
if (solved) {
solvedPuzzles = new Set(JSON.parse(solved));
}
document.getElementById("txtSolved").innerText = `Solved: [${Array.from(solvedPuzzles).sort().join(", ")}]`;
}
function loadCurrentPuzzle() {
const hash = window.location.hash;
if (hash) {
const puzzle = parseInt(hash.substring(1));
if (puzzle >= 1 && puzzle <= puzzles.length) {
curPuzzle = puzzle - 1;
}
}
}
function main() {
loadCurrentPuzzle();
loadSolvedPuzzles();
setupButtonHandlers();
resetBoard();
}
// On document ready, call main
document.addEventListener("DOMContentLoaded", main);