b84fb5badab3ecd7822bf6000c5737c102668795
[vchess.git] / client / src / variants / Apocalypse.js
1 import { ChessRules } from "@/base_rules";
2 import { randInt } from "@/utils/alea";
3
4 export class ApocalypseRules extends ChessRules {
5 static get PawnSpecs() {
6 return Object.assign(
7 {},
8 ChessRules.PawnSpecs,
9 {
10 twoSquares: false,
11 promotions: [V.KNIGHT]
12 }
13 );
14 }
15
16 static get HasCastle() {
17 return false;
18 }
19
20 static get HasEnpassant() {
21 return false;
22 }
23
24 static get CanAnalyze() {
25 return true; //false;
26 }
27
28 static get ShowMoves() {
29 return "byrow";
30 }
31
32 getPPpath(m) {
33 // Show the piece taken, if any, and not multiple pawns:
34 if (m.vanish.length == 1) return "Apocalypse/empty";
35 return m.vanish[1].c + m.vanish[1].p;
36 }
37
38 static get PIECES() {
39 return [V.PAWN, V.KNIGHT];
40 }
41
42 static IsGoodPosition(position) {
43 if (position.length == 0) return false;
44 const rows = position.split("/");
45 if (rows.length != V.size.x) return false;
46 // At least one pawn per color
47 let pawns = { "p": 0, "P": 0 };
48 for (let row of rows) {
49 let sumElts = 0;
50 for (let i = 0; i < row.length; i++) {
51 if (['P','p'].includes(row[i])) pawns[row[i]]++;
52 if (V.PIECES.includes(row[i].toLowerCase())) sumElts++;
53 else {
54 const num = parseInt(row[i]);
55 if (isNaN(num)) return false;
56 sumElts += num;
57 }
58 }
59 if (sumElts != V.size.y) return false;
60 }
61 if (Object.values(pawns).some(v => v == 0))
62 return false;
63 return true;
64 }
65
66 static IsGoodFen(fen) {
67 if (!ChessRules.IsGoodFen(fen)) return false;
68 const fenParsed = V.ParseFen(fen);
69 // 4) Check whiteMove
70 if (
71 (
72 fenParsed.turn == "w" &&
73 // NOTE: do not check really JSON stringified move...
74 (!fenParsed.whiteMove || fenParsed.whiteMove == "-")
75 )
76 ||
77 (fenParsed.turn == "b" && fenParsed.whiteMove != "-")
78 ) {
79 return false;
80 }
81 return true;
82 }
83
84 static IsGoodFlags(flags) {
85 return !!flags.match(/^[0-2]{2,2}$/);
86 }
87
88 aggregateFlags() {
89 return this.penaltyFlags;
90 }
91
92 disaggregateFlags(flags) {
93 this.penaltyFlags = flags;
94 }
95
96 static ParseFen(fen) {
97 const fenParts = fen.split(" ");
98 return Object.assign(
99 ChessRules.ParseFen(fen),
100 { whiteMove: fenParts[4] }
101 );
102 }
103
104 static get size() {
105 return { x: 5, y: 5 };
106 }
107
108 static GenRandInitFen() {
109 return "npppn/p3p/5/P3P/NPPPN w 0 00 -";
110 }
111
112 getFen() {
113 return super.getFen() + " " + this.getWhitemoveFen();
114 }
115
116 getFenForRepeat() {
117 return super.getFenForRepeat() + "_" + this.getWhitemoveFen();
118 }
119
120 getFlagsFen() {
121 return (
122 this.penaltyFlags['w'].toString() + this.penaltyFlags['b'].toString()
123 );
124 }
125
126 setOtherVariables(fen) {
127 const parsedFen = V.ParseFen(fen);
128 this.setFlags(parsedFen.flags);
129 // Also init whiteMove
130 this.whiteMove =
131 parsedFen.whiteMove != "-"
132 ? JSON.parse(parsedFen.whiteMove)
133 : null;
134 }
135
136 setFlags(fenflags) {
137 this.penaltyFlags = {
138 'w': parseInt(fenflags[0]),
139 'b': parseInt(fenflags[1])
140 };
141 }
142
143 getWhitemoveFen() {
144 if (!this.whiteMove) return "-";
145 return JSON.stringify({
146 start: this.whiteMove.start,
147 end: this.whiteMove.end,
148 appear: this.whiteMove.appear,
149 vanish: this.whiteMove.vanish
150 });
151 }
152
153 getSpeculations(moves, sq) {
154 let moveSet = {};
155 moves.forEach(m => {
156 const mHash = "m" + m.start.x + m.start.y + m.end.x + m.end.y;
157 moveSet[mHash] = true;
158 });
159 const color = this.turn;
160 this.turn = V.GetOppCol(color);
161 const oppMoves = super.getAllValidMoves();
162 this.turn = color;
163 // For each opponent's move, generate valid moves [from sq if same color]
164 let speculations = [];
165 oppMoves.forEach(m => {
166 V.PlayOnBoard(this.board, m);
167 const newValidMoves =
168 !!sq
169 ? (
170 this.getColor(sq[0], sq[1]) == color
171 ? super.getPotentialMovesFrom(sq)
172 : []
173 )
174 : super.getAllValidMoves();
175 newValidMoves.forEach(vm => {
176 const mHash = "m" + vm.start.x + vm.start.y + vm.end.x + vm.end.y;
177 if (!moveSet[mHash]) {
178 moveSet[mHash] = true;
179 vm.illegal = true; //potentially illegal!
180 speculations.push(vm);
181 }
182 });
183 V.UndoOnBoard(this.board, m);
184 });
185 return speculations;
186 }
187
188 getPossibleMovesFrom([x, y]) {
189 const possibleMoves = super.getPotentialMovesFrom([x, y])
190 // Augment potential moves with opponent's moves speculation:
191 return possibleMoves.concat(this.getSpeculations(possibleMoves, [x, y]));
192 }
193
194 getAllValidMoves() {
195 // Return possible moves + potentially valid moves
196 const validMoves = super.getAllValidMoves();
197 return validMoves.concat(this.getSpeculations(validMoves));
198 }
199
200 addPawnMoves([x1, y1], [x2, y2], moves) {
201 let finalPieces = [V.PAWN];
202 const color = this.turn;
203 const lastRank = (color == "w" ? 0 : V.size.x - 1);
204 if (x2 == lastRank) {
205 // If 0 or 1 horsemen, promote in knight
206 let knightCounter = 0;
207 let emptySquares = [];
208 for (let i = 0; i < V.size.x; i++) {
209 for (let j = 0; j < V.size.y; j++) {
210 if (this.board[i][j] == V.EMPTY) emptySquares.push([i, j]);
211 else if (
212 this.getColor(i, j) == color &&
213 this.getPiece(i, j) == V.KNIGHT
214 ) {
215 knightCounter++;
216 }
217 }
218 }
219 if (knightCounter <= 1) finalPieces = [V.KNIGHT];
220 else {
221 // Generate all possible landings, maybe capturing something on the way
222 let capture = undefined;
223 if (this.board[x2][y2] != V.EMPTY) {
224 capture = JSON.parse(JSON.stringify({
225 x: x2,
226 y: y2,
227 c: this.getColor(x2, y2),
228 p: this.getPiece(x2, y2)
229 }));
230 }
231 emptySquares.forEach(sq => {
232 if (sq[0] != lastRank) {
233 let newMove = this.getBasicMove([x1, y1], [sq[0], sq[1]]);
234 if (!!capture) newMove.vanish.push(capture);
235 moves.push(newMove);
236 }
237 });
238 return;
239 }
240 }
241 let tr = null;
242 for (let piece of finalPieces) {
243 tr = (piece != V.PAWN ? { c: color, p: piece } : null);
244 moves.push(this.getBasicMove([x1, y1], [x2, y2], tr));
245 }
246 }
247
248 filterValid(moves) {
249 // No checks:
250 return moves;
251 }
252
253 atLeastOneMove(color) {
254 const curTurn = this.turn;
255 this.turn = color;
256 const res = super.atLeastOneMove();
257 this.turn = curTurn;
258 return res;
259 }
260
261 // White and black (partial) moves were played: merge
262 resolveSynchroneMove(move) {
263 let m1 = this.whiteMove;
264 let m2 = move;
265 const movingLikeCapture = (m) => {
266 const shift = (m.vanish[0].c == 'w' ? -1 : 1);
267 return (
268 m.start.x + shift == m.end.x &&
269 Math.abs(m.end.y - m.start.y) == 1
270 );
271 };
272 const isPossible = (m, other) => {
273 return (
274 (
275 m.vanish[0].p == V.KNIGHT &&
276 (m.vanish.length == 1 || m.vanish[1].c != m.vanish[0].c)
277 )
278 ||
279 (
280 // Promotion attempt
281 m.end.x == (m.vanish[0].c == "w" ? 0 : V.size.x - 1) &&
282 other.vanish.length == 2 &&
283 other.vanish[1].p == V.KNIGHT &&
284 other.vanish[1].c == m.vanish[0].c
285 )
286 ||
287 (
288 // Moving attempt
289 !movingLikeCapture(m) &&
290 other.start.x == m.end.x &&
291 other.start.y == m.end.y
292 )
293 ||
294 (
295 // Capture attempt
296 movingLikeCapture(m) &&
297 other.end.x == m.end.x &&
298 other.end.y == m.end.y
299 )
300 );
301 };
302 if (!!m1.illegal && !isPossible(m1, m2)) {
303 // Either an anticipated capture of something which didn't move
304 // (or not to the right square), or a push through blocus.
305 // ==> Just discard the move, and add a penalty point
306 this.penaltyFlags[m1.vanish[0].c]++;
307 m1.isNull = true;
308 }
309 if (!!m2.illegal && !isPossible(m2, m1)) {
310 this.penaltyFlags[m2.vanish[0].c]++;
311 m2.isNull = true;
312 }
313 if (!!m1.isNull) m1 = null;
314 if (!!m2.isNull) m2 = null;
315 // If one move is illegal, just execute the other
316 if (!m1 && !!m2) return m2;
317 if (!m2 && !!m1) return m1;
318 // For PlayOnBoard (no need for start / end, irrelevant)
319 let smove = {
320 appear: [],
321 vanish: []
322 };
323 if (!m1 && !m2) return smove;
324 // Both move are now legal:
325 smove.vanish.push(m1.vanish[0]);
326 smove.vanish.push(m2.vanish[0]);
327 if ((m1.end.x != m2.end.x) || (m1.end.y != m2.end.y)) {
328 // Easy case: two independant moves
329 smove.appear.push(m1.appear[0]);
330 smove.appear.push(m2.appear[0]);
331 // "Captured" pieces may have moved:
332 if (
333 m1.vanish.length == 2 &&
334 (
335 m1.vanish[1].x != m2.start.x ||
336 m1.vanish[1].y != m2.start.y
337 )
338 ) {
339 smove.vanish.push(m1.vanish[1]);
340 }
341 if (
342 m2.vanish.length == 2 &&
343 (
344 m2.vanish[1].x != m1.start.x ||
345 m2.vanish[1].y != m1.start.y
346 )
347 ) {
348 smove.vanish.push(m2.vanish[1]);
349 }
350 } else {
351 // Collision: priority to the anticipated capture, if any.
352 // If ex-aequo: knight wins (higher risk), or both disappears.
353 // Then, priority to the knight vs pawn: remains.
354 // Finally: both disappears.
355 let remain = null;
356 const p1 = m1.vanish[0].p;
357 const p2 = m2.vanish[0].p;
358 if (!!m1.illegal && !m2.illegal) remain = { c: 'w', p: p1 };
359 else if (!!m2.illegal && !m1.illegal) remain = { c: 'b', p: p2 };
360 if (!remain) {
361 // Either both are illegal or both are legal
362 if (p1 == V.KNIGHT && p2 == V.PAWN) remain = { c: 'w', p: p1 };
363 else if (p2 == V.KNIGHT && p1 == V.PAWN) remain = { c: 'b', p: p2 };
364 // If remain is still null: same type same risk, both disappear
365 }
366 if (!!remain) {
367 smove.appear.push({
368 x: m1.end.x,
369 y: m1.end.y,
370 p: remain.p,
371 c: remain.c
372 });
373 }
374 }
375 return smove;
376 }
377
378 play(move) {
379 if (!this.states) this.states = [];
380 const stateFen = this.getFen();
381 this.states.push(stateFen);
382
383 // Do not play on board (would reveal the move...)
384 move.flags = JSON.stringify(this.aggregateFlags());
385 this.turn = V.GetOppCol(this.turn);
386 this.movesCount++;
387 this.postPlay(move);
388 }
389
390 postPlay(move) {
391 if (this.turn == 'b') {
392 // NOTE: whiteMove is used read-only, so no need to copy
393 this.whiteMove = move;
394 return;
395 }
396 // A full turn just ended:
397 const smove = this.resolveSynchroneMove(move);
398 V.PlayOnBoard(this.board, smove);
399 move.whiteMove = this.whiteMove; //for undo
400 this.whiteMove = null;
401 move.smove = smove;
402 }
403
404 undo(move) {
405 this.disaggregateFlags(JSON.parse(move.flags));
406 if (this.turn == 'w')
407 // Back to the middle of the move
408 V.UndoOnBoard(this.board, move.smove);
409 this.turn = V.GetOppCol(this.turn);
410 this.movesCount--;
411 this.postUndo(move);
412
413 const stateFen = this.getFen();
414 if (stateFen != this.states[this.states.length-1]) debugger;
415 this.states.pop();
416 }
417
418 postUndo(move) {
419 if (this.turn == 'w') this.whiteMove = null;
420 else this.whiteMove = move.whiteMove;
421 }
422
423 getCheckSquares(color) {
424 return [];
425 }
426
427 getCurrentScore() {
428 if (this.turn == 'b')
429 // Turn (white + black) not over yet
430 return "*";
431 // Count footmen: if a side has none, it loses
432 let fmCount = { 'w': 0, 'b': 0 };
433 for (let i=0; i<5; i++) {
434 for (let j=0; j<5; j++) {
435 if (this.board[i][j] != V.EMPTY && this.getPiece(i, j) == V.PAWN)
436 fmCount[this.getColor(i, j)]++;
437 }
438 }
439 if (Object.values(fmCount).some(v => v == 0)) {
440 if (fmCount['w'] == 0 && fmCount['b'] == 0)
441 // Everyone died
442 return "1/2";
443 if (fmCount['w'] == 0) return "0-1";
444 return "1-0"; //fmCount['b'] == 0
445 }
446 // Check penaltyFlags: if a side has 2 or more, it loses
447 if (Object.values(this.penaltyFlags).every(v => v == 2)) return "1/2";
448 if (this.penaltyFlags['w'] == 2) return "0-1";
449 if (this.penaltyFlags['b'] == 2) return "1-0";
450 if (!this.atLeastOneMove('w') || !this.atLeastOneMove('b'))
451 // Stalemate (should be very rare)
452 return "1/2";
453 return "*";
454 }
455
456 getComputerMove() {
457 const maxeval = V.INFINITY;
458 const color = this.turn;
459 let moves = this.getAllValidMoves();
460 if (moves.length == 0)
461 // TODO: this situation should not happen
462 return null;
463
464 if (Math.random() < 0.5)
465 // Return a random move
466 return moves[randInt(moves.length)];
467
468 // Rank moves at depth 1:
469 // try to capture something (not re-capturing)
470 moves.forEach(m => {
471 V.PlayOnBoard(this.board, m);
472 m.eval = this.evalPosition();
473 V.UndoOnBoard(this.board, m);
474 });
475 moves.sort((a, b) => {
476 return (color == "w" ? 1 : -1) * (b.eval - a.eval);
477 });
478 let candidates = [0];
479 for (let i = 1; i < moves.length && moves[i].eval == moves[0].eval; i++)
480 candidates.push(i);
481 return moves[candidates[randInt(candidates.length)]];
482 }
483
484 getNotation(move) {
485 // Basic system: piece + init + dest square
486 return (
487 move.vanish[0].p.toUpperCase() +
488 V.CoordsToSquare(move.start) +
489 V.CoordsToSquare(move.end)
490 );
491 }
492 };