Debug movesCount for MarseilleChess, complete draft of Eightpieces variant
[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 // At move 1, the subTurn doesn't need to be specified:
43 this.subTurn = fullTurn[1] || 1;
44 }
45
46 getPotentialPawnMoves([x, y]) {
47 const color = this.turn;
48 let moves = [];
49 const [sizeX, sizeY] = [V.size.x, V.size.y];
50 const shiftX = color == "w" ? -1 : 1;
51 const firstRank = color == "w" ? sizeX - 1 : 0;
52 const startRank = color == "w" ? sizeX - 2 : 1;
53 const lastRank = color == "w" ? 0 : sizeX - 1;
54 const finalPieces =
55 x + shiftX == lastRank ? [V.ROOK, V.KNIGHT, V.BISHOP, V.QUEEN] : [V.PAWN];
56
57 // One square forward
58 if (this.board[x + shiftX][y] == V.EMPTY) {
59 for (let piece of finalPieces) {
60 moves.push(
61 this.getBasicMove([x, y], [x + shiftX, y], { c: color, p: piece })
62 );
63 }
64 // Next condition because pawns on 1st rank can generally jump
65 if (
66 [startRank, firstRank].includes(x) &&
67 this.board[x + 2 * shiftX][y] == V.EMPTY
68 ) {
69 // Two squares jump
70 moves.push(this.getBasicMove([x, y], [x + 2 * shiftX, y]));
71 }
72 }
73 // Captures
74 for (let shiftY of [-1, 1]) {
75 if (
76 y + shiftY >= 0 &&
77 y + shiftY < sizeY &&
78 this.board[x + shiftX][y + shiftY] != V.EMPTY &&
79 this.canTake([x, y], [x + shiftX, y + shiftY])
80 ) {
81 for (let piece of finalPieces) {
82 moves.push(
83 this.getBasicMove([x, y], [x + shiftX, y + shiftY], {
84 c: color,
85 p: piece
86 })
87 );
88 }
89 }
90 }
91
92 // En passant: always OK if subturn 1,
93 // OK on subturn 2 only if enPassant was played at subturn 1
94 // (and if there are two e.p. squares available).
95 const Lep = this.epSquares.length;
96 const epSquares = this.epSquares[Lep - 1]; //always at least one element
97 let epSqs = [];
98 epSquares.forEach(sq => {
99 if (sq) epSqs.push(sq);
100 });
101 if (epSqs.length == 0) return moves;
102 const oppCol = V.GetOppCol(color);
103 for (let sq of epSqs) {
104 if (
105 this.subTurn == 1 ||
106 (epSqs.length == 2 &&
107 // Was this en-passant capture already played at subturn 1 ?
108 // (Or maybe the opponent filled the en-passant square with a piece)
109 this.board[epSqs[0].x][epSqs[0].y] != V.EMPTY)
110 ) {
111 if (
112 sq.x == x + shiftX &&
113 Math.abs(sq.y - y) == 1 &&
114 // Add condition "enemy pawn must be present"
115 this.getPiece(x, sq.y) == V.PAWN &&
116 this.getColor(x, sq.y) == oppCol
117 ) {
118 let epMove = this.getBasicMove([x, y], [sq.x, sq.y]);
119 epMove.vanish.push({
120 x: x,
121 y: sq.y,
122 p: "p",
123 c: oppCol
124 });
125 moves.push(epMove);
126 }
127 }
128 }
129
130 return moves;
131 }
132
133 play(move) {
134 move.flags = JSON.stringify(this.aggregateFlags());
135 move.turn = this.turn + this.subTurn;
136 V.PlayOnBoard(this.board, move);
137 const epSq = this.getEpSquare(move);
138 if (this.movesCount == 0) {
139 // First move in game
140 this.turn = "b";
141 this.epSquares.push([epSq]);
142 this.movesCount = 1;
143 }
144 // Does this move give check on subturn 1? If yes, skip subturn 2
145 else if (this.subTurn == 1 && this.underCheck(V.GetOppCol(this.turn))) {
146 this.turn = V.GetOppCol(this.turn);
147 this.epSquares.push([epSq]);
148 move.checkOnSubturn1 = true;
149 this.movesCount++;
150 } else {
151 if (this.subTurn == 2) {
152 this.turn = V.GetOppCol(this.turn);
153 let lastEpsq = this.epSquares[this.epSquares.length - 1];
154 lastEpsq.push(epSq);
155 } else {
156 this.epSquares.push([epSq]);
157 this.movesCount++;
158 }
159 this.subTurn = 3 - this.subTurn;
160 }
161 this.updateVariables(move);
162 }
163
164 undo(move) {
165 this.disaggregateFlags(JSON.parse(move.flags));
166 V.UndoOnBoard(this.board, move);
167 if (this.movesCount == 1 || !!move.checkOnSubturn1 || this.subTurn == 2) {
168 // The move may not be full, but is fully undone:
169 this.epSquares.pop();
170 // Moves counter was just incremented:
171 this.movesCount--;
172 } else {
173 // Undo the second half of a move
174 let lastEpsq = this.epSquares[this.epSquares.length - 1];
175 lastEpsq.pop();
176 }
177 this.turn = move.turn[0];
178 this.subTurn = parseInt(move.turn[1]);
179 this.unupdateVariables(move);
180 }
181
182 // NOTE: GenRandInitFen() is OK,
183 // since at first move turn indicator is just "w"
184
185 static get VALUES() {
186 return {
187 p: 1,
188 r: 5,
189 n: 3,
190 b: 3,
191 q: 7, //slightly less than in orthodox game
192 k: 1000
193 };
194 }
195
196 // No alpha-beta here, just adapted min-max at depth 2(+1)
197 getComputerMove() {
198 const maxeval = V.INFINITY;
199 const color = this.turn;
200 const oppCol = V.GetOppCol(this.turn);
201
202 // Search best (half) move for opponent turn
203 const getBestMoveEval = () => {
204 let score = this.getCurrentScore();
205 if (score != "*") {
206 if (score == "1/2") return 0;
207 return maxeval * (score == "1-0" ? 1 : -1);
208 }
209 let moves = this.getAllValidMoves();
210 let res = oppCol == "w" ? -maxeval : maxeval;
211 for (let m of moves) {
212 this.play(m);
213 score = this.getCurrentScore();
214 // Now turn is oppCol,2 if m doesn't give check
215 // Otherwise it's color,1. In both cases the next test makes sense
216 if (score != "*") {
217 if (score == "1/2")
218 res = oppCol == "w" ? Math.max(res, 0) : Math.min(res, 0);
219 else {
220 // Found a mate
221 this.undo(m);
222 return maxeval * (score == "1-0" ? 1 : -1);
223 }
224 }
225 const evalPos = this.evalPosition();
226 res = oppCol == "w" ? Math.max(res, evalPos) : Math.min(res, evalPos);
227 this.undo(m);
228 }
229 return res;
230 };
231
232 let moves11 = this.getAllValidMoves();
233 let doubleMoves = [];
234 // Rank moves using a min-max at depth 2
235 for (let i = 0; i < moves11.length; i++) {
236 this.play(moves11[i]);
237 if (this.turn != color) {
238 // We gave check with last move: search the best opponent move
239 doubleMoves.push({ moves: [moves11[i]], eval: getBestMoveEval() });
240 } else {
241 let moves12 = this.getAllValidMoves();
242 for (let j = 0; j < moves12.length; j++) {
243 this.play(moves12[j]);
244 doubleMoves.push({
245 moves: [moves11[i], moves12[j]],
246 eval: getBestMoveEval()
247 });
248 this.undo(moves12[j]);
249 }
250 }
251 this.undo(moves11[i]);
252 }
253
254 doubleMoves.sort((a, b) => {
255 return (color == "w" ? 1 : -1) * (b.eval - a.eval);
256 });
257 let candidates = [0]; //indices of candidates moves
258 for (
259 let i = 1;
260 i < doubleMoves.length && doubleMoves[i].eval == doubleMoves[0].eval;
261 i++
262 ) {
263 candidates.push(i);
264 }
265
266 const selected = doubleMoves[randInt(candidates.length)].moves;
267 if (selected.length == 1) return selected[0];
268 return selected;
269 }
270 };