Add temporary patch for preset challenges
[vchess.git] / client / src / variants / Losers.js
1 import { ChessRules } from "@/base_rules";
2 import { ArrayFun } from "@/utils/array";
3 import { randInt } from "@/utils/alea";
4
5 export class LosersRules extends ChessRules {
6
7 // Trim all non-capturing moves
8 static KeepCaptures(moves) {
9 return moves.filter(m => m.vanish.length == 2 && m.appear.length == 1);
10 }
11
12 // Stop at the first capture found (if any)
13 atLeastOneCapture() {
14 const color = this.turn;
15 for (let i = 0; i < V.size.x; i++) {
16 for (let j = 0; j < V.size.y; j++) {
17 if (
18 this.board[i][j] != V.EMPTY &&
19 this.getColor(i, j) == color &&
20 this.getPotentialMovesFrom([i, j]).some(m => {
21 return (
22 // Warning: discard castle moves
23 m.vanish.length == 2 && m.appear.length == 1 &&
24 this.filterValid([m]).length == 1
25 );
26 })
27 ) {
28 return true;
29 }
30 }
31 }
32 return false;
33 }
34
35 getPossibleMovesFrom(sq) {
36 let moves = this.filterValid(this.getPotentialMovesFrom(sq));
37 const captureMoves = V.KeepCaptures(moves);
38 if (captureMoves.length > 0) return captureMoves;
39 if (this.atLeastOneCapture()) return [];
40 return moves;
41 }
42
43 getAllValidMoves() {
44 const moves = super.getAllValidMoves();
45 if (moves.some(m => m.vanish.length == 2 && m.appear.length == 1))
46 return V.KeepCaptures(moves);
47 return moves;
48 }
49
50 getCurrentScore() {
51 // If only my king remains, I win
52 const color = this.turn;
53 let onlyKing = true;
54 outerLoop: for (let i=0; i<V.size.x; i++) {
55 for (let j=0; j<V.size.y; j++) {
56 if (
57 this.board[i][j] != V.EMPTY &&
58 this.getColor(i,j) == color &&
59 this.getPiece(i,j) != V.KING
60 ) {
61 onlyKing = false;
62 break outerLoop;
63 }
64 }
65 }
66 if (onlyKing) return color == "w" ? "1-0" : "0-1";
67 if (this.atLeastOneMove()) return "*";
68 // No valid move: the side who cannot move (or is checkmated) wins
69 return this.turn == "w" ? "1-0" : "0-1";
70 }
71
72 evalPosition() {
73 // Less material is better (more subtle in fact but...)
74 return -super.evalPosition();
75 }
76
77 };