Fix Koopa promotions after stunning pieces
[vchess.git] / client / src / variants / Koopa.js
1 import { ChessRules, PiPo } from "@/base_rules";
2
3 export class KoopaRules extends ChessRules {
4 static get HasEnpassant() {
5 return false;
6 }
7
8 static get STUNNED() {
9 return ['s', 'u', 'o', 'c', 't', 'l'];
10 }
11
12 static get PIECES() {
13 return ChessRules.PIECES.concat(V.STUNNED);
14 }
15
16 static ParseFen(fen) {
17 let res = ChessRules.ParseFen(fen);
18 const fenParts = fen.split(" ");
19 res.stunned = fenParts[4];
20 return res;
21 }
22
23 static IsGoodFen(fen) {
24 if (!ChessRules.IsGoodFen(fen)) return false;
25 const fenParsed = V.ParseFen(fen);
26 // 5) Check "stunned"
27 if (
28 !fenParsed.stunned ||
29 (
30 fenParsed.stunned != "-" &&
31 !fenParsed.stunned.match(/^([a-h][1-8][1-4],?)*$/)
32 )
33 ) {
34 return false;
35 }
36 return true;
37 }
38
39 getPpath(b) {
40 return (V.STUNNED.includes(b[1]) ? "Koopa/" : "") + b;
41 }
42
43 getFen() {
44 return super.getFen() + " " + this.getStunnedFen();
45 }
46
47 getFenForRepeat() {
48 return super.getFenForRepeat() + "_" + this.getStunnedFen();
49 }
50
51 getStunnedFen() {
52 const squares = Object.keys(this.stunned);
53 if (squares.length == 0) return "-";
54 return squares.map(square => square + this.stunned[square]).join(",");
55 }
56
57 // Base GenRandInitFen() is fine because en-passant indicator will
58 // stand for stunned indicator.
59
60 scanKings(fen) {
61 this.INIT_COL_KING = { w: -1, b: -1 };
62 // Squares of white and black king:
63 this.kingPos = { w: [-1, -1], b: [-1, -1] };
64 const fenRows = V.ParseFen(fen).position.split("/");
65 const startRow = { 'w': V.size.x - 1, 'b': 0 };
66 for (let i = 0; i < fenRows.length; i++) {
67 let k = 0; //column index on board
68 for (let j = 0; j < fenRows[i].length; j++) {
69 switch (fenRows[i].charAt(j)) {
70 case "k":
71 case "l":
72 this.kingPos["b"] = [i, k];
73 this.INIT_COL_KING["b"] = k;
74 break;
75 case "K":
76 case "L":
77 this.kingPos["w"] = [i, k];
78 this.INIT_COL_KING["w"] = k;
79 break;
80 default: {
81 const num = parseInt(fenRows[i].charAt(j), 10);
82 if (!isNaN(num)) k += num - 1;
83 }
84 }
85 k++;
86 }
87 }
88 }
89
90 setOtherVariables(fen) {
91 super.setOtherVariables(fen);
92 let stunnedArray = [];
93 const stunnedFen = V.ParseFen(fen).stunned;
94 if (stunnedFen != "-") {
95 stunnedArray =
96 stunnedFen
97 .split(",")
98 .map(s => {
99 return {
100 square: s.substr(0, 2),
101 state: parseInt(s[2], 10)
102 };
103 });
104 }
105 this.stunned = {};
106 stunnedArray.forEach(s => {
107 this.stunned[s.square] = s.state;
108 });
109 }
110
111 getNormalizedStep(step) {
112 const [deltaX, deltaY] = [Math.abs(step[0]), Math.abs(step[1])];
113 if (deltaX == 0 || deltaY == 0 || deltaX == deltaY)
114 return [step[0] / deltaX || 0, step[1] / deltaY || 0];
115 // Knight:
116 const divisor = Math.min(deltaX, deltaY)
117 return [step[0] / divisor, step[1] / divisor];
118 }
119
120 getPotentialMovesFrom([x, y]) {
121 let moves = super.getPotentialMovesFrom([x, y]);
122 // Complete moves: stuns & kicks
123 let promoteAfterStun = [];
124 const color = this.turn;
125 moves.forEach(m => {
126 if (m.vanish.length == 2 && m.appear.length == 1) {
127 const step =
128 this.getNormalizedStep([m.end.x - m.start.x, m.end.y - m.start.y]);
129 // "Capture" something: is target stunned?
130 if (V.STUNNED.includes(m.vanish[1].p)) {
131 // Kick it: continue movement in the same direction,
132 // destroying all on its path.
133 let [i, j] = [m.end.x + step[0], m.end.y + step[1]];
134 while (V.OnBoard(i, j)) {
135 if (this.board[i][j] != V.EMPTY) {
136 m.vanish.push(
137 new PiPo({
138 x: i,
139 y: j,
140 c: this.getColor(i, j),
141 p: this.getPiece(i, j)
142 })
143 );
144 }
145 i += step[0];
146 j += step[1];
147 }
148 }
149 else {
150 // The piece is now stunned
151 m.appear.push(JSON.parse(JSON.stringify(m.vanish[1])));
152 const pIdx = ChessRules.PIECES.findIndex(p => p == m.appear[1].p);
153 m.appear[1].p = V.STUNNED[pIdx];
154 // And the capturer continue in the same direction until an empty
155 // square or the edge of the board, maybe stunning other pieces.
156 let [i, j] = [m.end.x + step[0], m.end.y + step[1]];
157 while (V.OnBoard(i, j) && this.board[i][j] != V.EMPTY) {
158 const colIJ = this.getColor(i, j);
159 const pieceIJ = this.getPiece(i, j);
160 let pIdx = ChessRules.PIECES.findIndex(p => p == pieceIJ);
161 if (pIdx >= 0) {
162 // The piece isn't already stunned
163 m.vanish.push(
164 new PiPo({
165 x: i,
166 y: j,
167 c: colIJ,
168 p: pieceIJ
169 })
170 );
171 m.appear.push(
172 new PiPo({
173 x: i,
174 y: j,
175 c: colIJ,
176 p: V.STUNNED[pIdx]
177 })
178 );
179 }
180 i += step[0];
181 j += step[1];
182 }
183 if (V.OnBoard(i, j)) {
184 m.appear[0].x = i;
185 m.appear[0].y = j;
186 // Is it a pawn on last rank?
187 if (
188 m.appear[0].p == V.PAWN &&
189 ((color == 'w' && i == 0) || (color == 'b' && i == 7))
190 ) {
191 m.appear[0].p = V.ROOK;
192 for (let ppiece of [V.KNIGHT, V.BISHOP, V.QUEEN]) {
193 let mp = JSON.parse(JSON.stringify(m));
194 mp.appear[0].p = ppiece;
195 promoteAfterStun.push(mp);
196 }
197 }
198 }
199 else
200 // The piece is out
201 m.appear.shift();
202 }
203 }
204 });
205 return moves.concat(promoteAfterStun);
206 }
207
208 filterValid(moves) {
209 // Forbid kicking own king out
210 const color = this.turn;
211 return moves.filter(m => {
212 const kingAppear = m.appear.some(a => a.c == color && a.p == V.KING);
213 return m.vanish.every(v => {
214 return (
215 v.c != color ||
216 !["k", "l"].includes(v.p) ||
217 (v.p == "k" && kingAppear)
218 );
219 });
220 });
221 }
222
223 getCheckSquares() {
224 return [];
225 }
226
227 getCurrentScore() {
228 if (this.kingPos['w'][0] < 0) return "0-1";
229 if (this.kingPos['b'][0] < 0) return "1-0";
230 if (!this.atLeastOneMove()) return "1/2";
231 return "*";
232 }
233
234 postPlay(move) {
235 // Base method is fine because a stunned king (which won't be detected)
236 // can still castle after going back to normal.
237 super.postPlay(move);
238 const kIdx = move.vanish.findIndex(v => v.p == "l");
239 if (kIdx >= 0)
240 // A stunned king vanish (game over)
241 this.kingPos[move.vanish[kIdx].c] = [-1, -1];
242 move.stunned = JSON.stringify(this.stunned);
243 // Array of stunned stage 1 pieces (just back to normal then)
244 Object.keys(this.stunned).forEach(square => {
245 // All (formerly) stunned pieces progress by 1 level, if still on board
246 const coords = V.SquareToCoords(square);
247 const [x, y] = [coords.x, coords.y];
248 if (V.STUNNED.includes(this.board[x][y][1])) {
249 // Stunned piece still on board
250 this.stunned[square]--;
251 if (this.stunned[square] == 0) {
252 delete this.stunned[square];
253 const color = this.getColor(x, y);
254 const piece = this.getPiece(x, y);
255 const pIdx = V.STUNNED.findIndex(p => p == piece);
256 this.board[x][y] = color + ChessRules.PIECES[pIdx];
257 }
258 }
259 else delete this.stunned[square];
260 });
261 // Any new stunned pieces?
262 move.appear.forEach(a => {
263 if (V.STUNNED.includes(a.p))
264 // Set to maximum stun level:
265 this.stunned[V.CoordsToSquare({ x: a.x, y: a.y })] = 4;
266 });
267 }
268
269 postUndo(move) {
270 super.postUndo(move);
271 const kIdx = move.vanish.findIndex(v => v.p == "l");
272 if (kIdx >= 0) {
273 // A stunned king vanished
274 this.kingPos[move.vanish[kIdx].c] =
275 [move.vanish[kIdx].x, move.vanish[kIdx].y];
276 }
277 this.stunned = JSON.parse(move.stunned);
278 for (let i=0; i<8; i++) {
279 for (let j=0; j<8; j++) {
280 const square = V.CoordsToSquare({ x: i, y: j });
281 const pieceIJ = this.getPiece(i, j);
282 if (!this.stunned[square]) {
283 const pIdx = V.STUNNED.findIndex(p => p == pieceIJ);
284 if (pIdx >= 0)
285 this.board[i][j] = this.getColor(i, j) + ChessRules.PIECES[pIdx];
286 }
287 else {
288 const pIdx = ChessRules.PIECES.findIndex(p => p == pieceIJ);
289 if (pIdx >= 0)
290 this.board[i][j] = this.getColor(i, j) + V.STUNNED[pIdx];
291 }
292 }
293 }
294 }
295
296 static get VALUES() {
297 return Object.assign(
298 {
299 s: 1,
300 u: 5,
301 o: 3,
302 c: 3,
303 t: 9,
304 l: 1000
305 },
306 ChessRules.VALUES
307 );
308 }
309
310 static get SEARCH_DEPTH() {
311 return 2;
312 }
313
314 getNotation(move) {
315 if (
316 move.appear.length == 2 &&
317 move.vanish.length == 2 &&
318 move.appear.concat(move.vanish).every(
319 av => ChessRules.PIECES.includes(av.p)) &&
320 move.appear[0].p == V.KING
321 ) {
322 if (move.end.y < move.start.y) return "0-0-0";
323 return "0-0";
324 }
325 const finalSquare = V.CoordsToSquare(move.end);
326 const piece = this.getPiece(move.start.x, move.start.y);
327 const captureMark = move.vanish.length >= 2 ? "x" : "";
328 let pawnMark = "";
329 if (piece == 'p' && captureMark.length == 1)
330 pawnMark = V.CoordToColumn(move.start.y); //start column
331 // Piece or pawn movement
332 let notation =
333 (piece == V.PAWN ? pawnMark : piece.toUpperCase()) +
334 captureMark + finalSquare;
335 if (
336 piece == 'p' &&
337 move.appear[0].c == move.vanish[0].c &&
338 move.appear[0].p != 'p'
339 ) {
340 // Promotion
341 notation += "=" + move.appear[0].p.toUpperCase();
342 }
343 return notation;
344 }
345 };