Change castle flags. Eightpieces still not OK, but almost
[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.scanKings(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.postPlay(move);
162 }
163
164 postPlay(move) {
165 const c = move.turn.charAt(0);
166 const piece = move.vanish[0].p;
167 const firstRank = c == "w" ? V.size.x - 1 : 0;
168
169 if (piece == V.KING && move.appear.length > 0) {
170 this.kingPos[c][0] = move.appear[0].x;
171 this.kingPos[c][1] = move.appear[0].y;
172 if (V.HasCastle) this.castleFlags[c] = [V.size.y, V.size.y];
173 return;
174 }
175 const oppCol = V.GetOppCol(c);
176 const oppFirstRank = V.size.x - 1 - firstRank;
177 if (
178 move.start.x == firstRank && //our rook moves?
179 this.castleFlags[c].includes(move.start.y)
180 ) {
181 const flagIdx = (move.start.y == this.castleFlags[c][0] ? 0 : 1);
182 this.castleFlags[c][flagIdx] = V.size.y;
183 } else if (
184 move.end.x == oppFirstRank && //we took opponent rook?
185 this.castleFlags[oppCol].includes(move.end.y)
186 ) {
187 const flagIdx = (move.end.y == this.castleFlags[oppCol][0] ? 0 : 1);
188 this.castleFlags[oppCol][flagIdx] = V.size.y;
189 }
190 }
191
192 undo(move) {
193 this.disaggregateFlags(JSON.parse(move.flags));
194 V.UndoOnBoard(this.board, move);
195 if (this.movesCount == 1 || !!move.checkOnSubturn1 || this.subTurn == 2) {
196 // The move may not be full, but is fully undone:
197 this.epSquares.pop();
198 // Moves counter was just incremented:
199 this.movesCount--;
200 } else {
201 // Undo the second half of a move
202 let lastEpsq = this.epSquares[this.epSquares.length - 1];
203 lastEpsq.pop();
204 }
205 this.turn = move.turn[0];
206 this.subTurn = parseInt(move.turn[1]);
207 super.postUndo(move);
208 }
209
210 // NOTE: GenRandInitFen() is OK,
211 // since at first move turn indicator is just "w"
212
213 static get VALUES() {
214 return {
215 p: 1,
216 r: 5,
217 n: 3,
218 b: 3,
219 q: 7, //slightly less than in orthodox game
220 k: 1000
221 };
222 }
223
224 // No alpha-beta here, just adapted min-max at depth 2(+1)
225 getComputerMove() {
226 const maxeval = V.INFINITY;
227 const color = this.turn;
228 const oppCol = V.GetOppCol(this.turn);
229
230 // Search best (half) move for opponent turn
231 const getBestMoveEval = () => {
232 let score = this.getCurrentScore();
233 if (score != "*") {
234 if (score == "1/2") return 0;
235 return maxeval * (score == "1-0" ? 1 : -1);
236 }
237 let moves = this.getAllValidMoves();
238 let res = oppCol == "w" ? -maxeval : maxeval;
239 for (let m of moves) {
240 this.play(m);
241 score = this.getCurrentScore();
242 // Now turn is oppCol,2 if m doesn't give check
243 // Otherwise it's color,1. In both cases the next test makes sense
244 if (score != "*") {
245 if (score == "1/2")
246 res = oppCol == "w" ? Math.max(res, 0) : Math.min(res, 0);
247 else {
248 // Found a mate
249 this.undo(m);
250 return maxeval * (score == "1-0" ? 1 : -1);
251 }
252 }
253 const evalPos = this.evalPosition();
254 res = oppCol == "w" ? Math.max(res, evalPos) : Math.min(res, evalPos);
255 this.undo(m);
256 }
257 return res;
258 };
259
260 let moves11 = this.getAllValidMoves();
261 let doubleMoves = [];
262 // Rank moves using a min-max at depth 2
263 for (let i = 0; i < moves11.length; i++) {
264 this.play(moves11[i]);
265 if (this.turn != color) {
266 // We gave check with last move: search the best opponent move
267 doubleMoves.push({ moves: [moves11[i]], eval: getBestMoveEval() });
268 } else {
269 let moves12 = this.getAllValidMoves();
270 for (let j = 0; j < moves12.length; j++) {
271 this.play(moves12[j]);
272 doubleMoves.push({
273 moves: [moves11[i], moves12[j]],
274 eval: getBestMoveEval()
275 });
276 this.undo(moves12[j]);
277 }
278 }
279 this.undo(moves11[i]);
280 }
281
282 doubleMoves.sort((a, b) => {
283 return (color == "w" ? 1 : -1) * (b.eval - a.eval);
284 });
285 let candidates = [0]; //indices of candidates moves
286 for (
287 let i = 1;
288 i < doubleMoves.length && doubleMoves[i].eval == doubleMoves[0].eval;
289 i++
290 ) {
291 candidates.push(i);
292 }
293
294 const selected = doubleMoves[randInt(candidates.length)].moves;
295 if (selected.length == 1) return selected[0];
296 return selected;
297 }
298 };