1 import { ChessRules
} from "@/base_rules";
2 import { randInt
} from "@/utils/alea";
4 export class ApocalypseRules
extends ChessRules
{
5 static get PawnSpecs() {
11 promotions: [V
.KNIGHT
]
16 static get HasCastle() {
20 static get HasEnpassant() {
24 static get CanAnalyze() {
28 static get ShowMoves() {
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
;
39 return [V
.PAWN
, V
.KNIGHT
];
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
) {
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
++;
54 const num
= parseInt(row
[i
]);
55 if (isNaN(num
)) return false;
59 if (sumElts
!= V
.size
.y
) return false;
61 if (Object
.values(pawns
).some(v
=> v
== 0))
66 static IsGoodFen(fen
) {
67 if (!ChessRules
.IsGoodFen(fen
)) return false;
68 const fenParsed
= V
.ParseFen(fen
);
72 fenParsed
.turn
== "b" &&
73 // NOTE: do not check really JSON stringified move...
74 (!fenParsed
.whiteMove
|| fenParsed
.whiteMove
== "-")
77 (fenParsed
.turn
== "w" && fenParsed
.whiteMove
!= "-")
84 static IsGoodFlags(flags
) {
85 return !!flags
.match(/^[0-2]{2,2}$/);
89 return this.penaltyFlags
;
92 disaggregateFlags(flags
) {
93 this.penaltyFlags
= flags
;
96 static ParseFen(fen
) {
97 const fenParts
= fen
.split(" ");
99 ChessRules
.ParseFen(fen
),
100 { whiteMove: fenParts
[4] }
105 return { x: 5, y: 5 };
108 static GenRandInitFen() {
109 return "npppn/p3p/5/P3P/NPPPN w 0 00 -";
113 return super.getFen() + " " + this.getWhitemoveFen();
117 return super.getFenForRepeat() + "_" + this.getWhitemoveFen();
122 this.penaltyFlags
['w'].toString() + this.penaltyFlags
['b'].toString()
126 setOtherVariables(fen
) {
127 const parsedFen
= V
.ParseFen(fen
);
128 this.setFlags(parsedFen
.flags
);
129 // Also init whiteMove
131 parsedFen
.whiteMove
!= "-"
132 ? JSON
.parse(parsedFen
.whiteMove
)
137 this.penaltyFlags
= {
138 'w': parseInt(fenflags
[0]),
139 'b': parseInt(fenflags
[1])
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 illegal: this.whiteMove
.illegal
154 getSpeculations(moves
, sq
) {
157 const mHash
= "m" + m
.start
.x
+ m
.start
.y
+ m
.end
.x
+ m
.end
.y
;
158 moveSet
[mHash
] = true;
160 const color
= this.turn
;
161 this.turn
= V
.GetOppCol(color
);
162 const oppMoves
= super.getAllValidMoves();
164 // For each opponent's move, generate valid moves [from sq if same color]
165 let speculations
= [];
166 oppMoves
.forEach(m
=> {
167 V
.PlayOnBoard(this.board
, m
);
168 const newValidMoves
=
171 this.getColor(sq
[0], sq
[1]) == color
172 ? super.getPotentialMovesFrom(sq
)
175 : super.getAllValidMoves();
176 newValidMoves
.forEach(vm
=> {
177 const mHash
= "m" + vm
.start
.x
+ vm
.start
.y
+ vm
.end
.x
+ vm
.end
.y
;
178 if (!moveSet
[mHash
]) {
179 moveSet
[mHash
] = true;
180 vm
.illegal
= true; //potentially illegal!
181 speculations
.push(vm
);
184 V
.UndoOnBoard(this.board
, m
);
189 getPossibleMovesFrom([x
, y
]) {
190 const possibleMoves
= super.getPotentialMovesFrom([x
, y
])
191 // Augment potential moves with opponent's moves speculation:
192 return possibleMoves
.concat(this.getSpeculations(possibleMoves
, [x
, y
]));
196 // Return possible moves + potentially valid moves
197 const validMoves
= super.getAllValidMoves();
198 return validMoves
.concat(this.getSpeculations(validMoves
));
201 addPawnMoves([x1
, y1
], [x2
, y2
], moves
) {
202 let finalPieces
= [V
.PAWN
];
203 const color
= this.turn
;
204 const lastRank
= (color
== "w" ? 0 : V
.size
.x
- 1);
205 if (x2
== lastRank
) {
206 // If 0 or 1 horsemen, promote in knight
207 let knightCounter
= 0;
208 let emptySquares
= [];
209 for (let i
= 0; i
< V
.size
.x
; i
++) {
210 for (let j
= 0; j
< V
.size
.y
; j
++) {
211 if (this.board
[i
][j
] == V
.EMPTY
) emptySquares
.push([i
, j
]);
213 this.getColor(i
, j
) == color
&&
214 this.getPiece(i
, j
) == V
.KNIGHT
220 if (knightCounter
<= 1) finalPieces
= [V
.KNIGHT
];
222 // Generate all possible landings, maybe capturing something on the way
223 let capture
= undefined;
224 if (this.board
[x2
][y2
] != V
.EMPTY
) {
225 capture
= JSON
.parse(JSON
.stringify({
228 c: this.getColor(x2
, y2
),
229 p: this.getPiece(x2
, y2
)
232 emptySquares
.forEach(sq
=> {
233 if (sq
[0] != lastRank
) {
234 let newMove
= this.getBasicMove([x1
, y1
], [sq
[0], sq
[1]]);
235 if (!!capture
) newMove
.vanish
.push(capture
);
243 for (let piece
of finalPieces
) {
244 tr
= (piece
!= V
.PAWN
? { c: color
, p: piece
} : null);
245 moves
.push(this.getBasicMove([x1
, y1
], [x2
, y2
], tr
));
254 atLeastOneMove(color
) {
255 const curTurn
= this.turn
;
257 const res
= super.atLeastOneMove();
262 // White and black (partial) moves were played: merge
263 resolveSynchroneMove(move) {
264 let m1
= this.whiteMove
;
266 const movingLikeCapture
= (m
) => {
267 const shift
= (m
.vanish
[0].c
== 'w' ? -1 : 1);
269 m
.start
.x
+ shift
== m
.end
.x
&&
270 Math
.abs(m
.end
.y
- m
.start
.y
) == 1
273 const isPossible
= (m
, other
) => {
276 m
.vanish
[0].p
== V
.KNIGHT
&&
278 m
.vanish
.length
== 1 ||
279 m
.vanish
[1].c
!= m
.vanish
[0].c
||
280 // Self-capture attempt
283 other
.end
.x
== m
.end
.x
&&
284 other
.end
.y
== m
.end
.y
290 m
.vanish
[0].p
== V
.PAWN
&&
295 m
.end
.x
== (m
.vanish
[0].c
== "w" ? 0 : V
.size
.x
- 1) &&
296 other
.vanish
.length
== 2 &&
297 other
.vanish
[1].p
== V
.KNIGHT
&&
298 other
.vanish
[1].c
== m
.vanish
[0].c
303 !movingLikeCapture(m
) &&
304 other
.start
.x
== m
.end
.x
&&
305 other
.start
.y
== m
.end
.y
310 movingLikeCapture(m
) &&
311 other
.end
.x
== m
.end
.x
&&
312 other
.end
.y
== m
.end
.y
318 if (!!m1
.illegal
&& !isPossible(m1
, m2
)) {
319 // Either an anticipated capture of something which didn't move
320 // (or not to the right square), or a push through blocus.
321 // ==> Just discard the move, and add a penalty point
322 this.penaltyFlags
[m1
.vanish
[0].c
]++;
325 if (!!m2
.illegal
&& !isPossible(m2
, m1
)) {
326 this.penaltyFlags
[m2
.vanish
[0].c
]++;
329 if (!!m1
.isNull
) m1
= null;
330 if (!!m2
.isNull
) m2
= null;
331 // If one move is illegal, just execute the other
332 if (!m1
&& !!m2
) return m2
;
333 if (!m2
&& !!m1
) return m1
;
334 // For PlayOnBoard (no need for start / end, irrelevant)
339 if (!m1
&& !m2
) return smove
;
340 // Both moves are now legal or at least possible:
341 smove
.vanish
.push(m1
.vanish
[0]);
342 smove
.vanish
.push(m2
.vanish
[0]);
343 if ((m1
.end
.x
!= m2
.end
.x
) || (m1
.end
.y
!= m2
.end
.y
)) {
344 // Easy case: two independant moves
345 smove
.appear
.push(m1
.appear
[0]);
346 smove
.appear
.push(m2
.appear
[0]);
347 // "Captured" pieces may have moved:
349 m1
.vanish
.length
== 2 &&
351 m1
.vanish
[1].x
!= m2
.start
.x
||
352 m1
.vanish
[1].y
!= m2
.start
.y
355 smove
.vanish
.push(m1
.vanish
[1]);
358 m2
.vanish
.length
== 2 &&
360 m2
.vanish
[1].x
!= m1
.start
.x
||
361 m2
.vanish
[1].y
!= m1
.start
.y
364 smove
.vanish
.push(m2
.vanish
[1]);
367 // Collision: priority to the anticipated capture, if any.
368 // If ex-aequo: knight wins (higher risk), or both disappears.
369 // Then, priority to the knight vs pawn: remains.
370 // Finally: both disappears.
372 const p1
= m1
.vanish
[0].p
;
373 const p2
= m2
.vanish
[0].p
;
374 if (!!m1
.illegal
&& !m2
.illegal
) remain
= { c: 'w', p: p1
};
375 else if (!!m2
.illegal
&& !m1
.illegal
) remain
= { c: 'b', p: p2
};
377 // Either both are illegal or both are legal
378 if (p1
== V
.KNIGHT
&& p2
== V
.PAWN
) remain
= { c: 'w', p: p1
};
379 else if (p2
== V
.KNIGHT
&& p1
== V
.PAWN
) remain
= { c: 'b', p: p2
};
380 // If remain is still null: same type same risk, both disappear
395 // Do not play on board (would reveal the move...)
396 move.flags
= JSON
.stringify(this.aggregateFlags());
397 this.turn
= V
.GetOppCol(this.turn
);
403 if (this.turn
== 'b') {
404 // NOTE: whiteMove is used read-only, so no need to copy
405 this.whiteMove
= move;
408 // A full turn just ended:
409 const smove
= this.resolveSynchroneMove(move);
410 V
.PlayOnBoard(this.board
, smove
);
411 move.whiteMove
= this.whiteMove
; //for undo
412 this.whiteMove
= null;
417 this.disaggregateFlags(JSON
.parse(move.flags
));
418 if (this.turn
== 'w')
419 // Back to the middle of the move
420 V
.UndoOnBoard(this.board
, move.smove
);
421 this.turn
= V
.GetOppCol(this.turn
);
427 if (this.turn
== 'w') this.whiteMove
= null;
428 else this.whiteMove
= move.whiteMove
;
431 getCheckSquares(color
) {
436 if (this.turn
== 'b')
437 // Turn (white + black) not over yet
439 // Count footmen: if a side has none, it loses
440 let fmCount
= { 'w': 0, 'b': 0 };
441 for (let i
=0; i
<5; i
++) {
442 for (let j
=0; j
<5; j
++) {
443 if (this.board
[i
][j
] != V
.EMPTY
&& this.getPiece(i
, j
) == V
.PAWN
)
444 fmCount
[this.getColor(i
, j
)]++;
447 if (Object
.values(fmCount
).some(v
=> v
== 0)) {
448 if (fmCount
['w'] == 0 && fmCount
['b'] == 0)
451 if (fmCount
['w'] == 0) return "0-1";
452 return "1-0"; //fmCount['b'] == 0
454 // Check penaltyFlags: if a side has 2 or more, it loses
455 if (Object
.values(this.penaltyFlags
).every(v
=> v
== 2)) return "1/2";
456 if (this.penaltyFlags
['w'] == 2) return "0-1";
457 if (this.penaltyFlags
['b'] == 2) return "1-0";
458 if (!this.atLeastOneMove('w') || !this.atLeastOneMove('b'))
459 // Stalemate (should be very rare)
465 const maxeval
= V
.INFINITY
;
466 const color
= this.turn
;
467 let moves
= this.getAllValidMoves();
468 if (moves
.length
== 0)
469 // TODO: this situation should not happen
472 // Rank moves at depth 1:
474 let illegalMoves
= [];
476 // Warning: m might be illegal!
478 V
.PlayOnBoard(this.board
, m
);
479 m
.eval
= this.evalPosition();
480 V
.UndoOnBoard(this.board
, m
);
482 } else illegalMoves
.push(m
);
485 const illegalRatio
= illegalMoves
.length
/ moves
.length
;
486 if (Math
.random() < illegalRatio
)
487 // Return a random illegal move
488 return illegalMoves
[randInt(illegalMoves
.length
)];
490 validMoves
.sort((a
, b
) => {
491 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
493 let candidates
= [0];
496 i
< validMoves
.length
&& validMoves
[i
].eval
== moves
[0].eval
;
501 return validMoves
[candidates
[randInt(candidates
.length
)]];
505 // Basic system: piece + init + dest square
507 (move.vanish
[0].p
== V
.KNIGHT
? "N" : "") +
508 V
.CoordsToSquare(move.start
) +
509 V
.CoordsToSquare(move.end
)