Add traces to understand what happens in MarseilleChess about turn/subturn
[vchess.git] / public / javascripts / variants / Marseille.js
CommitLineData
4f7723a1
BA
1class MarseilleRules extends ChessRules
2{
6e62b1c7
BA
3 static IsGoodEnpassant(enpassant)
4 {
5 if (enpassant != "-")
6 {
7 const squares = enpassant.split(",");
8 if (squares.length > 2)
9 return false;
10 for (let sq of squares)
11 {
12 const ep = V.SquareToCoords(sq);
13 if (isNaN(ep.x) || !V.OnBoard(ep))
14 return false;
15 }
16 }
17 return true;
18 }
19
20 getTurnFen()
21 {
22 if (this.startAtFirstMove && this.moves.length==0)
23 return "w";
24 return this.turn + this.subTurn;
25 }
26
27 // There may be 2 enPassant squares (if 2 pawns jump 2 squares in same turn)
28 getEnpassantFen()
29 {
30 const L = this.epSquares.length;
31 if (this.epSquares[L-1].every(epsq => epsq === undefined))
32 return "-"; //no en-passant
33 let res = "";
34 this.epSquares[L-1].forEach(epsq => {
35 if (!!epsq)
36 res += V.CoordsToSquare(epsq) + ",";
37 });
38 return res.slice(0,-1); //remove last comma
39 }
40
41 setOtherVariables(fen)
42 {
43 const parsedFen = V.ParseFen(fen);
44 this.setFlags(parsedFen.flags);
45 if (parsedFen.enpassant == "-")
46 this.epSquares = [ [undefined,undefined] ];
47 else
48 {
49 let res = [];
50 const squares = parsedFen.enpassant.split(",");
51 for (let sq of squares)
52 res.push(V.SquareToCoords(sq));
53 if (res.length == 1)
54 res.push(undefined); //always 2 slots in epSquares[i]
55 this.epSquares = [ res ];
56 }
57 this.scanKingsRooks(fen);
58 // Extract subTurn from turn indicator: "w" (first move), or
59 // "w1" or "w2" white subturn 1 or 2, and same for black
60 const fullTurn = V.ParseFen(fen).turn;
61 this.startAtFirstMove = (fullTurn == "w");
62 this.turn = fullTurn[0];
63 this.subTurn = (fullTurn[1] || 1);
64 }
65
66 getPotentialPawnMoves([x,y])
67 {
68 const color = this.turn;
69 let moves = [];
70 const [sizeX,sizeY] = [V.size.x,V.size.y];
71 const shiftX = (color == "w" ? -1 : 1);
72 const firstRank = (color == 'w' ? sizeX-1 : 0);
73 const startRank = (color == "w" ? sizeX-2 : 1);
74 const lastRank = (color == "w" ? 0 : sizeX-1);
75 const pawnColor = this.getColor(x,y); //can be different for checkered
69f3d801
BA
76 const finalPieces = x + shiftX == lastRank
77 ? [V.ROOK,V.KNIGHT,V.BISHOP,V.QUEEN]
78 : [V.PAWN];
6e62b1c7 79
69f3d801
BA
80 // One square forward
81 if (this.board[x+shiftX][y] == V.EMPTY)
6e62b1c7 82 {
69f3d801 83 for (let piece of finalPieces)
6e62b1c7 84 {
69f3d801
BA
85 moves.push(this.getBasicMove([x,y], [x+shiftX,y],
86 {c:pawnColor,p:piece}));
6e62b1c7 87 }
69f3d801
BA
88 // Next condition because pawns on 1st rank can generally jump
89 if ([startRank,firstRank].includes(x)
90 && this.board[x+2*shiftX][y] == V.EMPTY)
6e62b1c7 91 {
69f3d801
BA
92 // Two squares jump
93 moves.push(this.getBasicMove([x,y], [x+2*shiftX,y]));
94 }
95 }
96 // Captures
97 for (let shiftY of [-1,1])
98 {
99 if (y + shiftY >= 0 && y + shiftY < sizeY
100 && this.board[x+shiftX][y+shiftY] != V.EMPTY
101 && this.canTake([x,y], [x+shiftX,y+shiftY]))
102 {
103 for (let piece of finalPieces)
6e62b1c7 104 {
69f3d801
BA
105 moves.push(this.getBasicMove([x,y], [x+shiftX,y+shiftY],
106 {c:pawnColor,p:piece}));
6e62b1c7
BA
107 }
108 }
109 }
110
111 // En passant: always OK if subturn 1,
112 // OK on subturn 2 only if enPassant was played at subturn 1
113 // (and if there are two e.p. squares available).
114 const Lep = this.epSquares.length;
115 const epSquares = this.epSquares[Lep-1]; //always at least one element
116 let epSqs = [];
117 epSquares.forEach(sq => {
118 if (!!sq)
119 epSqs.push(sq);
120 });
121 if (epSqs.length == 0)
122 return moves;
123 for (let sq of epSqs)
124 {
125 if (this.subTurn == 1 || (epSqs.length == 2 &&
126 // Was this en-passant capture already played at subturn 1 ?
69f3d801 127 // (Or maybe the opponent filled the en-passant square with a piece)
6e62b1c7
BA
128 this.board[epSqs[0].x][epSqs[0].y] != V.EMPTY))
129 {
130 if (sq.x == x+shiftX && Math.abs(sq.y - y) == 1)
131 {
132 let epMove = this.getBasicMove([x,y], [sq.x,sq.y]);
133 epMove.vanish.push({
134 x: x,
135 y: sq.y,
136 p: 'p',
137 c: this.getColor(x,sq.y)
138 });
139 moves.push(epMove);
140 }
141 }
142 }
143
144 return moves;
145 }
146
147 play(move, ingame)
148 {
6e62b1c7 149 if (!!ingame)
1b61a94d 150 {
6e62b1c7 151 move.notation = [this.getNotation(move), this.getLongNotation(move)];
1b61a94d
BA
152 // In this special case, we also need the "move color":
153 move.color = this.turn;
154 }
6e62b1c7
BA
155 move.flags = JSON.stringify(this.aggregateFlags());
156 let lastEpsq = this.epSquares[this.epSquares.length-1];
157 const epSq = this.getEpSquare(move);
158 if (lastEpsq.length == 1)
159 lastEpsq.push(epSq);
160 else
161 {
162 // New turn
163 let newEpsqs = [epSq];
164 if (this.startAtFirstMove && this.moves.length == 0)
165 newEpsqs.push(undefined); //at first move, to force length==2 (TODO)
166 this.epSquares.push(newEpsqs);
167 }
168 V.PlayOnBoard(this.board, move);
169 if (this.startAtFirstMove && this.moves.length == 0)
170 this.turn = "b";
171 // Does this move give check on subturn 1? If yes, skip subturn 2
172 else if (this.subTurn==1 && this.underCheck(this.getOppCol(this.turn)))
173 {
174 this.epSquares[this.epSquares.length-1].push(undefined);
175 this.turn = this.getOppCol(this.turn);
176 move.checkOnSubturn1 = true;
177 }
178 else
179 {
180 if (this.subTurn == 2)
181 this.turn = this.getOppCol(this.turn);
182 this.subTurn = 3 - this.subTurn;
183 }
184 this.moves.push(move);
185 this.updateVariables(move);
186 if (!!ingame)
187 move.hash = hex_md5(this.getFen());
6e62b1c7
BA
188 }
189
190 undo(move)
191 {
192 this.disaggregateFlags(JSON.parse(move.flags));
193 let lastEpsq = this.epSquares[this.epSquares.length-1];
194 if (lastEpsq.length == 2)
195 {
196 if (!!move.checkOnSubturn1 ||
197 (this.startAtFirstMove && this.moves.length == 1))
198 {
199 this.epSquares.pop(); //remove real + artificial e.p. squares
200 }
201 else
202 lastEpsq.pop();
203 }
204 else
205 this.epSquares.pop();
206 V.UndoOnBoard(this.board, move);
207 if (this.startAtFirstMove && this.moves.length == 1)
208 this.turn = "w";
209 else if (move.checkOnSubturn1)
210 {
211 this.turn = this.getOppCol(this.turn);
212 this.subTurn = 1;
213 }
214 else
215 {
216 if (this.subTurn == 1)
217 this.turn = this.getOppCol(this.turn);
218 this.subTurn = 3 - this.subTurn;
219 }
220 this.moves.pop();
221 this.unupdateVariables(move);
6e62b1c7
BA
222 }
223
224 // NOTE: GenRandInitFen() is OK,
225 // since at first move turn indicator is just "w"
226
227 // No alpha-beta here, just adapted min-max at depth 2(+1)
228 getComputerMove()
229 {
78bab51e
BA
230 if (this.subTurn == 2)
231 return null; //TODO: imperfect interface setup
232
6e62b1c7
BA
233 const maxeval = V.INFINITY;
234 const color = this.turn;
235 const oppCol = this.getOppCol(this.turn);
3fa426b6
BA
236//if (this.moves.length == 25)
237// debugger;
238console.log("turn before " + this.turn + " " + this.subTurn);
6e62b1c7
BA
239 // Search best (half) move for opponent turn
240 const getBestMoveEval = () => {
241 let moves = this.getAllValidMoves();
242 if (moves.length == 0)
243 {
244 const score = this.checkGameEnd();
245 if (score == "1/2")
246 return 0;
247 return maxeval * (score == "1-0" ? 1 : -1);
248 }
249 let res = (oppCol == "w" ? -maxeval : maxeval);
250 for (let m of moves)
251 {
252 this.play(m);
253 this.turn = color; //very artificial...
254 if (!this.atLeastOneMove())
255 {
256 const score = this.checkGameEnd();
257 if (score == "1/2")
258 res = (oppCol == "w" ? Math.max(res, 0) : Math.min(res, 0));
259 else
260 {
261 // Found a mate
262 this.turn = oppCol;
263 this.undo(m);
264 return maxeval * (score == "1-0" ? 1 : -1);
265 }
266 }
267 const evalPos = this.evalPosition();
268 res = (oppCol == "w" ? Math.max(res, evalPos) : Math.min(res, evalPos));
269 this.turn = oppCol;
270 this.undo(m);
271 }
272 return res;
273 };
274
275 let moves11 = this.getAllValidMoves();
3fa426b6
BA
276console.log("turn after " + this.turn + " " + this.subTurn);
277
278if (this.moves.length == 25)
279 debugger;
280
281
6e62b1c7
BA
282 let doubleMoves = [];
283 // Rank moves using a min-max at depth 2
284 for (let i=0; i<moves11.length; i++)
285 {
6e62b1c7
BA
286 this.play(moves11[i]);
287 if (this.turn != color)
288 {
289 // We gave check with last move: search the best opponent move
290 doubleMoves.push({moves:[moves11[i]], eval:getBestMoveEval()});
291 }
292 else
293 {
294 let moves12 = this.getAllValidMoves();
295 for (let j=0; j<moves12.length; j++)
296 {
297 this.play(moves12[j]);
298 doubleMoves.push({
299 moves:[moves11[i],moves12[j]],
300 eval:getBestMoveEval()});
301 this.undo(moves12[j]);
3fa426b6 302 console.log("------ after undo of " + this.getNotation(moves12[j]) + " " + this.turn + " " + this.subTurn);
6e62b1c7
BA
303 }
304 }
305 this.undo(moves11[i]);
3fa426b6
BA
306
307 console.log("after undo of " + this.getNotation(moves11[i]) + " " + this.turn + " " + this.subTurn);
308
309 }
310console.log("turn interm " + this.turn + " " + this.subTurn);
311
312 for (let i=0; i<doubleMoves.length; i++)
313 {
314 if (doubleMoves[i].moves.length == 2)
315 {
316 if (this.moves.length == 1
317 && this.getNotation(doubleMoves[i].moves[0])=="a5"
318 && this.getNotation(doubleMoves[i].moves[1])=="h6")
319 {
320 return doubleMoves[i].moves;
321 }
322 if (this.moves.length == 5
323 && this.getNotation(doubleMoves[i].moves[0])=="c6"
324 && this.getNotation(doubleMoves[i].moves[1])=="Kc7")
325 {
326 return doubleMoves[i].moves;
327 }
328 if (this.moves.length == 9
329 && this.getNotation(doubleMoves[i].moves[0])=="d6"
330 && this.getNotation(doubleMoves[i].moves[1])=="dxe5")
331 {
332 return doubleMoves[i].moves;
333 }
334 if (this.moves.length == 13
335 && this.getNotation(doubleMoves[i].moves[0])=="fxe6"
336 && this.getNotation(doubleMoves[i].moves[1])=="Rxf1")
337 {
338 return doubleMoves[i].moves;
339 }
340 if (this.moves.length == 17
341 && this.getNotation(doubleMoves[i].moves[0])=="Nb6"
342 && this.getNotation(doubleMoves[i].moves[1])=="Bg6")
343 {
344 return doubleMoves[i].moves;
345 }
346 if (this.moves.length == 21
347 && this.getNotation(doubleMoves[i].moves[0])=="Bxe4"
348 && this.getNotation(doubleMoves[i].moves[1])=="Nxd3") //Bxd3
349 {
350 return doubleMoves[i].moves;
351 }
352 if (this.moves.length == 25
353 && this.getNotation(doubleMoves[i].moves[0])=="Na4"
354 && this.getNotation(doubleMoves[i].moves[1])=="xb6") //Nxb6
355 {
356 debugger;
357 return doubleMoves[i].moves;
358 }
359 }
6e62b1c7 360 }
3fa426b6 361console.log("turn intermBIS " + this.turn + " " + this.subTurn);
6e62b1c7
BA
362
363 doubleMoves.sort( (a,b) => {
364 return (color=="w" ? 1 : -1) * (b.eval - a.eval); });
365 let candidates = [0]; //indices of candidates moves
366 for (let i=1;
367 i<doubleMoves.length && doubleMoves[i].eval == doubleMoves[0].eval;
368 i++)
369 {
370 candidates.push(i);
371 }
3fa426b6 372console.log("turn END " + this.turn + " " + this.subTurn);
78bab51e 373
6e62b1c7
BA
374 const selected = doubleMoves[_.sample(candidates, 1)].moves;
375 if (selected.length == 1)
376 return selected[0];
377 return selected;
378 }
1b61a94d
BA
379
380 getPGN(mycolor, score, fenStart, mode)
381 {
382 let pgn = "";
383 pgn += '[Site "vchess.club"]<br>';
384 const opponent = mode=="human" ? "Anonymous" : "Computer";
385 pgn += '[Variant "' + variant + '"]<br>';
386 pgn += '[Date "' + getDate(new Date()) + '"]<br>';
387 pgn += '[White "' + (mycolor=='w'?'Myself':opponent) + '"]<br>';
388 pgn += '[Black "' + (mycolor=='b'?'Myself':opponent) + '"]<br>';
389 pgn += '[FenStart "' + fenStart + '"]<br>';
390 pgn += '[Fen "' + this.getFen() + '"]<br>';
391 pgn += '[Result "' + score + '"]<br><br>';
392
393 let counter = 1;
394 let i = 0;
395 while (i < this.moves.length)
396 {
397 pgn += (counter++) + ".";
398 for (let color of ["w","b"])
399 {
400 let move = "";
401 while (i < this.moves.length && this.moves[i].color == color)
402 move += this.moves[i++].notation[0] + ",";
403 move = move.slice(0,-1); //remove last comma
404 pgn += move + (i < this.moves.length-1 ? " " : "");
405 }
406 }
407 pgn += "<br><br>";
408
409 // "Complete moves" PGN (helping in ambiguous cases)
410 counter = 1;
411 i = 0;
412 while (i < this.moves.length)
413 {
414 pgn += (counter++) + ".";
415 for (let color of ["w","b"])
416 {
417 let move = "";
418 while (i < this.moves.length && this.moves[i].color == color)
419 move += this.moves[i++].notation[1] + ",";
420 move = move.slice(0,-1); //remove last comma
421 pgn += move + (i < this.moves.length-1 ? " " : "");
422 }
423 }
424
425 return pgn;
426 }
4f7723a1
BA
427}
428
429const VariantRules = MarseilleRules;