Update TODO, improve style for Crazyhouse variant, fix an introduced bug in example...
[vchess.git] / client / src / variants / Marseille.js
1 import { ChessRules } from "@/base_rules";
2 import { randInt } from "@/utils/alea";
3
4 export const VariantRules = class MarseilleRules extends ChessRules {
5 static IsGoodEnpassant(enpassant) {
6 const squares = enpassant.split(",");
7 if (squares.length > 2) return false;
8 for (let sq of squares) {
9 if (sq != "-") {
10 const ep = V.SquareToCoords(sq);
11 if (isNaN(ep.x) || !V.OnBoard(ep)) return false;
12 }
13 }
14 return true;
15 }
16
17 getTurnFen() {
18 return this.turn + this.subTurn;
19 }
20
21 // There may be 2 enPassant squares (if 2 pawns jump 2 squares in same turn)
22 getEnpassantFen() {
23 return this.epSquares[this.epSquares.length - 1].map(
24 epsq => epsq === undefined
25 ? "-" //no en-passant
26 : V.CoordsToSquare(epsq)
27 ).join(",");
28 }
29
30 setOtherVariables(fen) {
31 const parsedFen = V.ParseFen(fen);
32 this.setFlags(parsedFen.flags);
33 this.epSquares = [parsedFen.enpassant.split(",").map(sq => {
34 if (sq != "-") return V.SquareToCoords(sq);
35 return undefined;
36 })];
37 this.scanKingsRooks(fen);
38 // Extract subTurn from turn indicator: "w" (first move), or
39 // "w1" or "w2" white subturn 1 or 2, and same for black
40 const fullTurn = V.ParseFen(fen).turn;
41 this.turn = fullTurn[0];
42 this.subTurn = fullTurn[1] || 0; //"w0" = special code for first move in game
43 }
44
45 getPotentialPawnMoves([x, y]) {
46 const color = this.turn;
47 let moves = [];
48 const [sizeX, sizeY] = [V.size.x, V.size.y];
49 const shiftX = color == "w" ? -1 : 1;
50 const firstRank = color == "w" ? sizeX - 1 : 0;
51 const startRank = color == "w" ? sizeX - 2 : 1;
52 const lastRank = color == "w" ? 0 : sizeX - 1;
53 const finalPieces =
54 x + shiftX == lastRank ? [V.ROOK, V.KNIGHT, V.BISHOP, V.QUEEN] : [V.PAWN];
55
56 // One square forward
57 if (this.board[x + shiftX][y] == V.EMPTY) {
58 for (let piece of finalPieces) {
59 moves.push(
60 this.getBasicMove([x, y], [x + shiftX, y], { c: color, p: piece })
61 );
62 }
63 // Next condition because pawns on 1st rank can generally jump
64 if (
65 [startRank, firstRank].includes(x) &&
66 this.board[x + 2 * shiftX][y] == V.EMPTY
67 ) {
68 // Two squares jump
69 moves.push(this.getBasicMove([x, y], [x + 2 * shiftX, y]));
70 }
71 }
72 // Captures
73 for (let shiftY of [-1, 1]) {
74 if (
75 y + shiftY >= 0 &&
76 y + shiftY < sizeY &&
77 this.board[x + shiftX][y + shiftY] != V.EMPTY &&
78 this.canTake([x, y], [x + shiftX, y + shiftY])
79 ) {
80 for (let piece of finalPieces) {
81 moves.push(
82 this.getBasicMove([x, y], [x + shiftX, y + shiftY], {
83 c: color,
84 p: piece
85 })
86 );
87 }
88 }
89 }
90
91 // En passant: always OK if subturn 1,
92 // OK on subturn 2 only if enPassant was played at subturn 1
93 // (and if there are two e.p. squares available).
94 const Lep = this.epSquares.length;
95 const epSquares = this.epSquares[Lep - 1]; //always at least one element
96 let epSqs = [];
97 epSquares.forEach(sq => {
98 if (sq) epSqs.push(sq);
99 });
100 if (epSqs.length == 0) return moves;
101 const oppCol = V.GetOppCol(color);
102 for (let sq of epSqs) {
103 if (
104 this.subTurn == 1 ||
105 (epSqs.length == 2 &&
106 // Was this en-passant capture already played at subturn 1 ?
107 // (Or maybe the opponent filled the en-passant square with a piece)
108 this.board[epSqs[0].x][epSqs[0].y] != V.EMPTY)
109 ) {
110 if (
111 sq.x == x + shiftX &&
112 Math.abs(sq.y - y) == 1 &&
113 // Add condition "enemy pawn must be present"
114 this.getPiece(x, sq.y) == V.PAWN &&
115 this.getColor(x, sq.y) == oppCol
116 ) {
117 let epMove = this.getBasicMove([x, y], [sq.x, sq.y]);
118 epMove.vanish.push({
119 x: x,
120 y: sq.y,
121 p: "p",
122 c: oppCol
123 });
124 moves.push(epMove);
125 }
126 }
127 }
128
129 return moves;
130 }
131
132 play(move) {
133 move.flags = JSON.stringify(this.aggregateFlags());
134 move.turn = this.turn + this.subTurn;
135 V.PlayOnBoard(this.board, move);
136 const epSq = this.getEpSquare(move);
137 if (this.subTurn == 0) {
138 //first move in game
139 this.turn = "b";
140 this.subTurn = 1;
141 this.epSquares.push([epSq]);
142 }
143 // Does this move give check on subturn 1? If yes, skip subturn 2
144 else if (this.subTurn == 1 && this.underCheck(V.GetOppCol(this.turn))) {
145 this.turn = V.GetOppCol(this.turn);
146 this.epSquares.push([epSq]);
147 move.checkOnSubturn1 = true;
148 } else {
149 if (this.subTurn == 2) {
150 this.turn = V.GetOppCol(this.turn);
151 let lastEpsq = this.epSquares[this.epSquares.length - 1];
152 lastEpsq.push(epSq);
153 } else this.epSquares.push([epSq]);
154 this.subTurn = 3 - this.subTurn;
155 }
156 this.updateVariables(move);
157 }
158
159 undo(move) {
160 this.disaggregateFlags(JSON.parse(move.flags));
161 V.UndoOnBoard(this.board, move);
162 if (move.turn[1] == "0" || move.checkOnSubturn1 || this.subTurn == 2)
163 this.epSquares.pop();
164 else {
165 // this.subTurn == 1
166 let lastEpsq = this.epSquares[this.epSquares.length - 1];
167 lastEpsq.pop();
168 }
169 this.turn = move.turn[0];
170 this.subTurn = parseInt(move.turn[1]);
171 this.unupdateVariables(move);
172 }
173
174 // NOTE: GenRandInitFen() is OK,
175 // since at first move turn indicator is just "w"
176
177 static get VALUES() {
178 return {
179 p: 1,
180 r: 5,
181 n: 3,
182 b: 3,
183 q: 7, //slightly less than in orthodox game
184 k: 1000
185 };
186 }
187
188 // No alpha-beta here, just adapted min-max at depth 2(+1)
189 getComputerMove() {
190 const maxeval = V.INFINITY;
191 const color = this.turn;
192 const oppCol = V.GetOppCol(this.turn);
193
194 // Search best (half) move for opponent turn
195 const getBestMoveEval = () => {
196 let score = this.getCurrentScore();
197 if (score != "*") {
198 if (score == "1/2") return 0;
199 return maxeval * (score == "1-0" ? 1 : -1);
200 }
201 let moves = this.getAllValidMoves();
202 let res = oppCol == "w" ? -maxeval : maxeval;
203 for (let m of moves) {
204 this.play(m);
205 score = this.getCurrentScore();
206 // Now turn is oppCol,2 if m doesn't give check
207 // Otherwise it's color,1. In both cases the next test makes sense
208 if (score != "*") {
209 if (score == "1/2")
210 res = oppCol == "w" ? Math.max(res, 0) : Math.min(res, 0);
211 else {
212 // Found a mate
213 this.undo(m);
214 return maxeval * (score == "1-0" ? 1 : -1);
215 }
216 }
217 const evalPos = this.evalPosition();
218 res = oppCol == "w" ? Math.max(res, evalPos) : Math.min(res, evalPos);
219 this.undo(m);
220 }
221 return res;
222 };
223
224 let moves11 = this.getAllValidMoves();
225 let doubleMoves = [];
226 // Rank moves using a min-max at depth 2
227 for (let i = 0; i < moves11.length; i++) {
228 this.play(moves11[i]);
229 if (this.turn != color) {
230 // We gave check with last move: search the best opponent move
231 doubleMoves.push({ moves: [moves11[i]], eval: getBestMoveEval() });
232 } else {
233 let moves12 = this.getAllValidMoves();
234 for (let j = 0; j < moves12.length; j++) {
235 this.play(moves12[j]);
236 doubleMoves.push({
237 moves: [moves11[i], moves12[j]],
238 eval: getBestMoveEval()
239 });
240 this.undo(moves12[j]);
241 }
242 }
243 this.undo(moves11[i]);
244 }
245
246 doubleMoves.sort((a, b) => {
247 return (color == "w" ? 1 : -1) * (b.eval - a.eval);
248 });
249 let candidates = [0]; //indices of candidates moves
250 for (
251 let i = 1;
252 i < doubleMoves.length && doubleMoves[i].eval == doubleMoves[0].eval;
253 i++
254 ) {
255 candidates.push(i);
256 }
257
258 const selected = doubleMoves[randInt(candidates.length)].moves;
259 if (selected.length == 1) return selected[0];
260 return selected;
261 }
262 };