Add (real) Football chess
[vchess.git] / client / src / variants / Ball.js
1 import { ChessRules, Move, PiPo } from "@/base_rules";
2 import { ArrayFun } from "@/utils/array";
3 import { shuffle } from "@/utils/alea";
4
5 export class BallRules extends ChessRules {
6
7 static get Lines() {
8 return [
9 // White goal:
10 [[0, 3], [0, 6]],
11 [[0, 6], [1, 6]],
12 [[1, 6], [1, 3]],
13 [[1, 3], [0, 3]],
14 // Black goal:
15 [[9, 3], [9, 6]],
16 [[9, 6], [8, 6]],
17 [[8, 6], [8, 3]],
18 [[8, 3], [9, 3]]
19 ];
20 }
21
22 static get PawnSpecs() {
23 return Object.assign(
24 {},
25 ChessRules.PawnSpecs,
26 { promotions: ChessRules.PawnSpecs.promotions.concat([V.PHOENIX]) }
27 );
28 }
29
30 static get HasFlags() {
31 return false;
32 }
33
34 static get PHOENIX() {
35 return 'h';
36 }
37
38 static get BALL() {
39 // 'b' is already taken:
40 return "aa";
41 }
42
43 static get HAS_BALL_CODE() {
44 return {
45 'p': 's',
46 'r': 'u',
47 'n': 'o',
48 'b': 'c',
49 'q': 't',
50 'k': 'l',
51 'h': 'i'
52 };
53 }
54
55 static get HAS_BALL_DECODE() {
56 return {
57 's': 'p',
58 'u': 'r',
59 'o': 'n',
60 'c': 'b',
61 't': 'q',
62 'l': 'k',
63 'i': 'h'
64 };
65 }
66
67 static get PIECES() {
68 return ChessRules.PIECES
69 .concat([V.PHOENIX])
70 .concat(Object.keys(V.HAS_BALL_DECODE))
71 .concat(['a']);
72 }
73
74 static board2fen(b) {
75 if (b == V.BALL) return 'a';
76 return ChessRules.board2fen(b);
77 }
78
79 static fen2board(f) {
80 if (f == 'a') return V.BALL;
81 return ChessRules.fen2board(f);
82 }
83
84 static ParseFen(fen) {
85 return Object.assign(
86 ChessRules.ParseFen(fen),
87 { pmove: fen.split(" ")[4] }
88 );
89 }
90
91 // Check that exactly one ball is on the board
92 // + at least one piece per color.
93 static IsGoodPosition(position) {
94 if (position.length == 0) return false;
95 const rows = position.split("/");
96 if (rows.length != V.size.x) return false;
97 let pieces = { "w": 0, "b": 0 };
98 const withBall = Object.keys(V.HAS_BALL_DECODE).concat(['a']);
99 let ballCount = 0;
100 for (let row of rows) {
101 let sumElts = 0;
102 for (let i = 0; i < row.length; i++) {
103 const lowerRi = row[i].toLowerCase();
104 if (V.PIECES.includes(lowerRi)) {
105 if (lowerRi != 'a') pieces[row[i] == lowerRi ? "b" : "w"]++;
106 if (withBall.includes(lowerRi)) ballCount++;
107 sumElts++;
108 }
109 else {
110 const num = parseInt(row[i], 10);
111 if (isNaN(num)) return false;
112 sumElts += num;
113 }
114 }
115 if (sumElts != V.size.y) return false;
116 }
117 if (ballCount != 1 || Object.values(pieces).some(v => v == 0))
118 return false;
119 return true;
120 }
121
122 static IsGoodFen(fen) {
123 if (!ChessRules.IsGoodFen(fen)) return false;
124 const fenParts = fen.split(" ");
125 if (fenParts.length != 5) return false;
126 if (
127 fenParts[4] != "-" &&
128 !fenParts[4].match(/^([a-i][1-9]){2,2}$/)
129 ) {
130 return false;
131 }
132 return true;
133 }
134
135 getPpath(b) {
136 let prefix = "";
137 const withPrefix =
138 Object.keys(V.HAS_BALL_DECODE)
139 .concat([V.PHOENIX])
140 .concat(['a']);
141 if (withPrefix.includes(b[1])) prefix = "Ball/";
142 return prefix + b;
143 }
144
145 getPPpath(m) {
146 if (
147 m.vanish.length == 2 &&
148 m.appear.length == 2 &&
149 m.appear[0].c != m.appear[1].c
150 ) {
151 // Take ball in place (from opponent)
152 return "Ball/inplace";
153 }
154 return super.getPPpath(m);
155 }
156
157 canTake([x1, y1], [x2, y2]) {
158 if (this.getColor(x1, y1) !== this.getColor(x2, y2)) {
159 // The piece holding the ball cannot capture:
160 return (
161 !(Object.keys(V.HAS_BALL_DECODE)
162 .includes(this.board[x1][y1].charAt(1)))
163 );
164 }
165 // Pass: possible only if one of the friendly pieces has the ball
166 return (
167 Object.keys(V.HAS_BALL_DECODE).includes(this.board[x1][y1].charAt(1)) ||
168 Object.keys(V.HAS_BALL_DECODE).includes(this.board[x2][y2].charAt(1))
169 );
170 }
171
172 getFen() {
173 return super.getFen() + " " + this.getPmoveFen();
174 }
175
176 getFenForRepeat() {
177 return super.getFenForRepeat() + "_" + this.getPmoveFen();
178 }
179
180 getPmoveFen() {
181 const L = this.pmoves.length;
182 if (!this.pmoves[L-1]) return "-";
183 return (
184 V.CoordsToSquare(this.pmoves[L-1].start) +
185 V.CoordsToSquare(this.pmoves[L-1].end)
186 );
187 }
188
189 static GenRandInitFen(randomness) {
190 if (randomness == 0)
191 return "hbnrqrnhb/ppppppppp/9/9/4a4/9/9/PPPPPPPPP/HBNRQRNHB w 0 - -";
192
193 let pieces = { w: new Array(9), b: new Array(9) };
194 for (let c of ["w", "b"]) {
195 if (c == 'b' && randomness == 1) {
196 pieces['b'] = pieces['w'];
197 break;
198 }
199
200 // Get random squares for every piece, with bishops and phoenixes
201 // on different colors:
202 let positions = shuffle(ArrayFun.range(9));
203 const composition = ['b', 'b', 'h', 'h', 'n', 'n', 'r', 'r', 'q'];
204 let rem2 = positions[0] % 2;
205 if (rem2 == positions[1] % 2) {
206 // Fix bishops (on different colors)
207 for (let i=4; i<9; i++) {
208 if (positions[i] % 2 != rem2)
209 [positions[1], positions[i]] = [positions[i], positions[1]];
210 }
211 }
212 rem2 = positions[2] % 2;
213 if (rem2 == positions[3] % 2) {
214 // Fix phoenixes too:
215 for (let i=4; i<9; i++) {
216 if (positions[i] % 2 != rem2)
217 [positions[3], positions[i]] = [positions[i], positions[3]];
218 }
219 }
220 for (let i = 0; i < 9; i++) pieces[c][positions[i]] = composition[i];
221 }
222 return (
223 pieces["b"].join("") +
224 "/ppppppppp/9/9/4a4/9/9/PPPPPPPPP/" +
225 pieces["w"].join("").toUpperCase() +
226 " w 0 - -"
227 );
228 }
229
230 scanKings() {}
231
232 setOtherVariables(fen) {
233 super.setOtherVariables(fen);
234 const pmove = V.ParseFen(fen).pmove;
235 // Local stack of "pass moves" (no need for appear & vanish)
236 this.pmoves = [
237 pmove != "-"
238 ?
239 {
240 start: V.SquareToCoords(pmove.substr(0, 2)),
241 end: V.SquareToCoords(pmove.substr(2))
242 }
243 : null
244 ];
245 }
246
247 static get size() {
248 return { x: 9, y: 9 };
249 }
250
251 getPiece(i, j) {
252 const p = this.board[i][j].charAt(1);
253 if (Object.keys(V.HAS_BALL_DECODE).includes(p))
254 return V.HAS_BALL_DECODE[p];
255 return p;
256 }
257
258 static get steps() {
259 return Object.assign(
260 {},
261 ChessRules.steps,
262 // Add phoenix moves
263 {
264 h: [
265 [-2, -2],
266 [-2, 2],
267 [2, -2],
268 [2, 2],
269 [-1, 0],
270 [1, 0],
271 [0, -1],
272 [0, 1]
273 ]
274 }
275 );
276 }
277
278 // Because of the ball, getPiece() could be wrong:
279 // use board[x][y][1] instead (always valid).
280 getBasicMove([sx, sy], [ex, ey], tr) {
281 const initColor = this.getColor(sx, sy);
282 const initPiece = this.board[sx][sy].charAt(1);
283 let mv = new Move({
284 appear: [
285 new PiPo({
286 x: ex,
287 y: ey,
288 c: tr ? tr.c : initColor,
289 p: tr ? tr.p : initPiece
290 })
291 ],
292 vanish: [
293 new PiPo({
294 x: sx,
295 y: sy,
296 c: initColor,
297 p: initPiece
298 })
299 ]
300 });
301
302 // Fix "ball holding" indication in case of promotions:
303 if (!!tr && Object.keys(V.HAS_BALL_DECODE).includes(initPiece))
304 mv.appear[0].p = V.HAS_BALL_CODE[tr.p];
305
306 // The opponent piece disappears if we take it
307 if (this.board[ex][ey] != V.EMPTY) {
308 mv.vanish.push(
309 new PiPo({
310 x: ex,
311 y: ey,
312 c: this.getColor(ex, ey),
313 p: this.board[ex][ey].charAt(1)
314 })
315 );
316 }
317
318 // Post-processing: maybe the ball was taken, or a piece + ball,
319 // or maybe a pass (ball <--> piece)
320 if (mv.vanish.length == 2) {
321 if (
322 // Take the ball?
323 mv.vanish[1].c == 'a' ||
324 // Capture a ball-holding piece? If friendly one, then adjust
325 Object.keys(V.HAS_BALL_DECODE).includes(mv.vanish[1].p)
326 ) {
327 mv.appear[0].p = V.HAS_BALL_CODE[mv.appear[0].p];
328 if (mv.vanish[1].c == mv.vanish[0].c) {
329 // "Capturing" self => pass
330 mv.appear[0].x = mv.start.x;
331 mv.appear[0].y = mv.start.y;
332 mv.appear.push(
333 new PiPo({
334 x: mv.end.x,
335 y: mv.end.y,
336 p: V.HAS_BALL_DECODE[mv.vanish[1].p],
337 c: mv.vanish[0].c
338 })
339 );
340 }
341 }
342 else if (mv.vanish[1].c == mv.vanish[0].c) {
343 // Pass the ball: the passing unit does not disappear
344 mv.appear.push(JSON.parse(JSON.stringify(mv.vanish[0])));
345 mv.appear[0].p = V.HAS_BALL_CODE[mv.vanish[1].p];
346 mv.appear[1].p = V.HAS_BALL_DECODE[mv.appear[1].p];
347 }
348 // Else: standard capture
349 }
350
351 return mv;
352 }
353
354 // NOTE: if a pawn captures en-passant, he doesn't hold the ball
355 // So base implementation is fine.
356
357 getPotentialMovesFrom([x, y]) {
358 let moves = undefined;
359 const piece = this.getPiece(x, y);
360 if (piece == V.PHOENIX)
361 moves = this.getPotentialPhoenixMoves([x, y]);
362 else moves = super.getPotentialMovesFrom([x, y]);
363 // Add "taking ball in place" move (at most one in list)
364 for (let m of moves) {
365 if (
366 m.vanish.length == 2 &&
367 m.vanish[1].p != 'a' &&
368 m.vanish[0].c != m.vanish[1].c &&
369 Object.keys(V.HAS_BALL_DECODE).includes(m.appear[0].p)
370 ) {
371 const color = this.turn;
372 const oppCol = V.GetOppCol(color);
373 moves.push(
374 new Move({
375 appear: [
376 new PiPo({
377 x: x,
378 y: y,
379 c: color,
380 p: m.appear[0].p
381 }),
382 new PiPo({
383 x: m.vanish[1].x,
384 y: m.vanish[1].y,
385 c: oppCol,
386 p: V.HAS_BALL_DECODE[m.vanish[1].p]
387 })
388 ],
389 vanish: [
390 new PiPo({
391 x: x,
392 y: y,
393 c: color,
394 p: piece
395 }),
396 new PiPo({
397 x: m.vanish[1].x,
398 y: m.vanish[1].y,
399 c: oppCol,
400 p: m.vanish[1].p
401 })
402 ],
403 end: { x: m.end.x, y: m.end.y }
404 })
405 );
406 break;
407 }
408 }
409 return moves;
410 }
411
412 // "Sliders": at most 3 steps
413 getSlideNJumpMoves([x, y], steps, oneStep) {
414 let moves = [];
415 outerLoop: for (let step of steps) {
416 let i = x + step[0];
417 let j = y + step[1];
418 let stepCount = 1;
419 while (V.OnBoard(i, j) && this.board[i][j] == V.EMPTY) {
420 moves.push(this.getBasicMove([x, y], [i, j]));
421 if (oneStep || stepCount == 3) continue outerLoop;
422 i += step[0];
423 j += step[1];
424 stepCount++;
425 }
426 if (V.OnBoard(i, j) && this.canTake([x, y], [i, j]))
427 moves.push(this.getBasicMove([x, y], [i, j]));
428 }
429 return moves;
430 }
431
432 getPotentialPhoenixMoves(sq) {
433 return this.getSlideNJumpMoves(sq, V.steps[V.PHOENIX], "oneStep");
434 }
435
436 getPmove(move) {
437 if (
438 move.vanish.length == 2 &&
439 move.appear.length == 2 &&
440 move.appear[0].c != move.appear[1].c
441 ) {
442 // In-place pass:
443 return {
444 start: move.start,
445 end: move.end
446 };
447 }
448 return null;
449 }
450
451 oppositePasses(m1, m2) {
452 return (
453 m1.start.x == m2.end.x &&
454 m1.start.y == m2.end.y &&
455 m1.end.x == m2.start.x &&
456 m1.end.y == m2.start.y
457 );
458 }
459
460 filterValid(moves) {
461 const L = this.pmoves.length;
462 const lp = this.pmoves[L-1];
463 if (!lp) return moves;
464 return moves.filter(m => {
465 return (
466 m.vanish.length == 1 ||
467 m.appear.length == 1 ||
468 m.appear[0].c == m.appear[1].c ||
469 !this.oppositePasses(lp, m)
470 );
471 });
472 }
473
474 // isAttacked: unused here (no checks)
475
476 postPlay(move) {
477 this.pmoves.push(this.getPmove(move));
478 }
479
480 postUndo() {
481 this.pmoves.pop();
482 }
483
484 getCheckSquares() {
485 return [];
486 }
487
488 getCurrentScore() {
489 // Turn has changed:
490 const color = V.GetOppCol(this.turn);
491 const lastRank = (color == "w" ? 0 : 8);
492 if ([3,4,5].some(
493 i => {
494 return (
495 Object.keys(V.HAS_BALL_DECODE).includes(
496 this.board[lastRank][i].charAt(1)) &&
497 this.getColor(lastRank, i) == color
498 );
499 }
500 )) {
501 // Goal scored!
502 return color == "w" ? "1-0" : "0-1";
503 }
504 if (this.atLeastOneMove()) return "*";
505 // Stalemate (quite unlikely?)
506 return "1/2";
507 }
508
509 static get VALUES() {
510 return {
511 p: 1,
512 r: 3,
513 n: 3,
514 b: 2,
515 q: 5,
516 h: 3,
517 a: 0 //ball: neutral
518 };
519 }
520
521 static get SEARCH_DEPTH() {
522 return 2;
523 }
524
525 evalPosition() {
526 // Count material:
527 let evaluation = super.evalPosition();
528 if (this.board[4][4] == V.BALL)
529 // Ball not captured yet
530 return evaluation;
531 // Ponder depending on ball position
532 for (let i=0; i<9; i++) {
533 for (let j=0; j<9; j++) {
534 if (Object.keys(V.HAS_BALL_DECODE).includes(this.board[i][j][1]))
535 return evaluation/2 + (this.getColor(i, j) == "w" ? 8 - i : -i);
536 }
537 }
538 return 0; //never reached
539 }
540
541 getNotation(move) {
542 const finalSquare = V.CoordsToSquare(move.end);
543 if (move.appear.length == 2)
544 // A pass: special notation
545 return V.CoordsToSquare(move.start) + "P" + finalSquare;
546 const piece = this.getPiece(move.start.x, move.start.y);
547 if (piece == V.PAWN) {
548 // Pawn move
549 let notation = "";
550 if (move.vanish.length > move.appear.length) {
551 // Capture
552 const startColumn = V.CoordToColumn(move.start.y);
553 notation = startColumn + "x" + finalSquare;
554 }
555 else notation = finalSquare;
556 if (![V.PAWN, V.HAS_BALL_CODE[V.PAWN]].includes(move.appear[0].p)) {
557 // Promotion
558 const promotePiece =
559 V.HAS_BALL_DECODE[move.appear[0].p] || move.appear[0].p;
560 notation += "=" + promotePiece.toUpperCase();
561 }
562 return notation;
563 }
564 // Piece movement
565 return (
566 piece.toUpperCase() +
567 (move.vanish.length > move.appear.length ? "x" : "") +
568 finalSquare
569 );
570 }
571
572 };