7bd5e5413273e31ccfcbb86ecea3a144c499ebdb
[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
39 console.log(this.atLeastOneCapture());
40
41 if (captureMoves.length > 0) return captureMoves;
42 if (this.atLeastOneCapture()) return [];
43 return moves;
44 }
45
46 getAllValidMoves() {
47 const moves = super.getAllValidMoves();
48 if (moves.some(m => m.vanish.length == 2 && m.appear.length == 1))
49 return V.KeepCaptures(moves);
50 return moves;
51 }
52
53 getCurrentScore() {
54 // If only my king remains, I win
55 const color = this.turn;
56 let onlyKing = true;
57 outerLoop: for (let i=0; i<V.size.x; i++) {
58 for (let j=0; j<V.size.y; j++) {
59 if (
60 this.board[i][j] != V.EMPTY &&
61 this.getColor(i,j) == color &&
62 this.getPiece(i,j) != V.KING
63 ) {
64 onlyKing = false;
65 break outerLoop;
66 }
67 }
68 }
69 if (onlyKing) return color == "w" ? "1-0" : "0-1";
70 if (this.atLeastOneMove()) return "*";
71 // No valid move: the side who cannot move (or is checkmated) wins
72 return this.turn == "w" ? "1-0" : "0-1";
73 }
74
75 evalPosition() {
76 // Less material is better (more subtle in fact but...)
77 return -super.evalPosition();
78 }
79
80 };