Simplify Game logic a bit + some advances on Chakart
[vchess.git] / client / src / base_rules.js
1 // (Orthodox) Chess rules are defined in ChessRules class.
2 // Variants generally inherit from it, and modify some parts.
3
4 import { ArrayFun } from "@/utils/array";
5 import { randInt, shuffle } from "@/utils/alea";
6
7 // class "PiPo": Piece + Position
8 export const PiPo = class PiPo {
9 // o: {piece[p], color[c], posX[x], posY[y]}
10 constructor(o) {
11 this.p = o.p;
12 this.c = o.c;
13 this.x = o.x;
14 this.y = o.y;
15 }
16 };
17
18 export const Move = class Move {
19 // o: {appear, vanish, [start,] [end,]}
20 // appear,vanish = arrays of PiPo
21 // start,end = coordinates to apply to trigger move visually (think castle)
22 constructor(o) {
23 this.appear = o.appear;
24 this.vanish = o.vanish;
25 this.start = o.start ? o.start : { x: o.vanish[0].x, y: o.vanish[0].y };
26 this.end = o.end ? o.end : { x: o.appear[0].x, y: o.appear[0].y };
27 }
28 };
29
30 // NOTE: x coords = top to bottom; y = left to right
31 // (from white player perspective)
32 export const ChessRules = class ChessRules {
33 //////////////
34 // MISC UTILS
35
36 // Some variants don't have flags:
37 static get HasFlags() {
38 return true;
39 }
40
41 // Or castle
42 static get HasCastle() {
43 return V.HasFlags;
44 }
45
46 // Pawns specifications
47 static get PawnSpecs() {
48 return {
49 directions: { 'w': -1, 'b': 1 },
50 initShift: { w: 1, b: 1 },
51 twoSquares: true,
52 threeSquares: false,
53 promotions: [V.ROOK, V.KNIGHT, V.BISHOP, V.QUEEN],
54 canCapture: true,
55 captureBackward: false,
56 bidirectional: false
57 };
58 }
59
60 // En-passant captures need a stack of squares:
61 static get HasEnpassant() {
62 return true;
63 }
64
65 // Some variants cannot have analyse mode
66 static get CanAnalyze() {
67 return true;
68 }
69 // Patch: issues with javascript OOP, objects can't access static fields.
70 get canAnalyze() {
71 return V.CanAnalyze;
72 }
73
74 // Some variants show incomplete information,
75 // and thus show only a partial moves list or no list at all.
76 static get ShowMoves() {
77 return "all";
78 }
79 get showMoves() {
80 return V.ShowMoves;
81 }
82
83 // Generally true, unless the variant includes random effects
84 static get CorrConfirm() {
85 return true;
86 }
87
88 // Used for Monochrome variant (TODO: harmonize: !canFlip ==> showFirstTurn)
89 get showFirstTurn() {
90 return false;
91 }
92
93 // Some variants always show the same orientation
94 static get CanFlip() {
95 return true;
96 }
97 get canFlip() {
98 return V.CanFlip;
99 }
100
101 // For (generally old) variants without checkered board
102 static get Monochrome() {
103 return false;
104 }
105
106 // Some variants require lines drawing
107 static get Lines() {
108 if (V.Monochrome) {
109 let lines = [];
110 // Draw all inter-squares lines
111 for (let i = 0; i <= V.size.x; i++)
112 lines.push([[i, 0], [i, V.size.y]]);
113 for (let j = 0; j <= V.size.y; j++)
114 lines.push([[0, j], [V.size.x, j]]);
115 return lines;
116 }
117 return null;
118 }
119
120 // Some variants use click infos:
121 doClick() {
122 return null;
123 }
124
125 // Some variants may need to highlight squares on hover (Hamilton, Weiqi...)
126 hoverHighlight() {
127 return false;
128 }
129
130 static get IMAGE_EXTENSION() {
131 // All pieces should be in the SVG format
132 return ".svg";
133 }
134
135 // Turn "wb" into "B" (for FEN)
136 static board2fen(b) {
137 return b[0] == "w" ? b[1].toUpperCase() : b[1];
138 }
139
140 // Turn "p" into "bp" (for board)
141 static fen2board(f) {
142 return f.charCodeAt() <= 90 ? "w" + f.toLowerCase() : "b" + f;
143 }
144
145 // Check if FEN describes a board situation correctly
146 static IsGoodFen(fen) {
147 const fenParsed = V.ParseFen(fen);
148 // 1) Check position
149 if (!V.IsGoodPosition(fenParsed.position)) return false;
150 // 2) Check turn
151 if (!fenParsed.turn || !V.IsGoodTurn(fenParsed.turn)) return false;
152 // 3) Check moves count
153 if (!fenParsed.movesCount || !(parseInt(fenParsed.movesCount) >= 0))
154 return false;
155 // 4) Check flags
156 if (V.HasFlags && (!fenParsed.flags || !V.IsGoodFlags(fenParsed.flags)))
157 return false;
158 // 5) Check enpassant
159 if (
160 V.HasEnpassant &&
161 (!fenParsed.enpassant || !V.IsGoodEnpassant(fenParsed.enpassant))
162 ) {
163 return false;
164 }
165 return true;
166 }
167
168 // Is position part of the FEN a priori correct?
169 static IsGoodPosition(position) {
170 if (position.length == 0) return false;
171 const rows = position.split("/");
172 if (rows.length != V.size.x) return false;
173 let kings = { "k": 0, "K": 0 };
174 for (let row of rows) {
175 let sumElts = 0;
176 for (let i = 0; i < row.length; i++) {
177 if (['K','k'].includes(row[i])) kings[row[i]]++;
178 if (V.PIECES.includes(row[i].toLowerCase())) sumElts++;
179 else {
180 const num = parseInt(row[i]);
181 if (isNaN(num)) return false;
182 sumElts += num;
183 }
184 }
185 if (sumElts != V.size.y) return false;
186 }
187 // Both kings should be on board. Exactly one per color.
188 if (Object.values(kings).some(v => v != 1)) return false;
189 return true;
190 }
191
192 // For FEN checking
193 static IsGoodTurn(turn) {
194 return ["w", "b"].includes(turn);
195 }
196
197 // For FEN checking
198 static IsGoodFlags(flags) {
199 // NOTE: a little too permissive to work with more variants
200 return !!flags.match(/^[a-z]{4,4}$/);
201 }
202
203 // NOTE: not with regexp to adapt to different board sizes. (TODO?)
204 static IsGoodEnpassant(enpassant) {
205 if (enpassant != "-") {
206 const ep = V.SquareToCoords(enpassant);
207 if (isNaN(ep.x) || !V.OnBoard(ep)) return false;
208 }
209 return true;
210 }
211
212 // 3 --> d (column number to letter)
213 static CoordToColumn(colnum) {
214 return String.fromCharCode(97 + colnum);
215 }
216
217 // d --> 3 (column letter to number)
218 static ColumnToCoord(column) {
219 return column.charCodeAt(0) - 97;
220 }
221
222 // a4 --> {x:3,y:0}
223 static SquareToCoords(sq) {
224 return {
225 // NOTE: column is always one char => max 26 columns
226 // row is counted from black side => subtraction
227 x: V.size.x - parseInt(sq.substr(1)),
228 y: sq[0].charCodeAt() - 97
229 };
230 }
231
232 // {x:0,y:4} --> e8
233 static CoordsToSquare(coords) {
234 return V.CoordToColumn(coords.y) + (V.size.x - coords.x);
235 }
236
237 // Path to pieces (standard ones in pieces/ folder)
238 getPpath(b) {
239 return b;
240 }
241
242 // Path to promotion pieces (usually the same)
243 getPPpath(m) {
244 return this.getPpath(m.appear[0].c + m.appear[0].p);
245 }
246
247 // Aggregates flags into one object
248 aggregateFlags() {
249 return this.castleFlags;
250 }
251
252 // Reverse operation
253 disaggregateFlags(flags) {
254 this.castleFlags = flags;
255 }
256
257 // En-passant square, if any
258 getEpSquare(moveOrSquare) {
259 if (!moveOrSquare) return undefined;
260 if (typeof moveOrSquare === "string") {
261 const square = moveOrSquare;
262 if (square == "-") return undefined;
263 return V.SquareToCoords(square);
264 }
265 // Argument is a move:
266 const move = moveOrSquare;
267 const s = move.start,
268 e = move.end;
269 if (
270 s.y == e.y &&
271 Math.abs(s.x - e.x) == 2 &&
272 // Next conditions for variants like Atomic or Rifle, Recycle...
273 (move.appear.length > 0 && move.appear[0].p == V.PAWN) &&
274 (move.vanish.length > 0 && move.vanish[0].p == V.PAWN)
275 ) {
276 return {
277 x: (s.x + e.x) / 2,
278 y: s.y
279 };
280 }
281 return undefined; //default
282 }
283
284 // Can thing on square1 take thing on square2
285 canTake([x1, y1], [x2, y2]) {
286 return this.getColor(x1, y1) !== this.getColor(x2, y2);
287 }
288
289 // Is (x,y) on the chessboard?
290 static OnBoard(x, y) {
291 return x >= 0 && x < V.size.x && y >= 0 && y < V.size.y;
292 }
293
294 // Used in interface: 'side' arg == player color
295 canIplay(side, [x, y]) {
296 return this.turn == side && this.getColor(x, y) == side;
297 }
298
299 // On which squares is color under check ? (for interface)
300 getCheckSquares() {
301 const color = this.turn;
302 return (
303 this.underCheck(color)
304 // kingPos must be duplicated, because it may change:
305 ? [JSON.parse(JSON.stringify(this.kingPos[color]))]
306 : []
307 );
308 }
309
310 /////////////
311 // FEN UTILS
312
313 // Setup the initial random (asymmetric) position
314 static GenRandInitFen(randomness) {
315 if (randomness == 0)
316 // Deterministic:
317 return "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w 0 ahah -";
318
319 let pieces = { w: new Array(8), b: new Array(8) };
320 let flags = "";
321 // Shuffle pieces on first (and last rank if randomness == 2)
322 for (let c of ["w", "b"]) {
323 if (c == 'b' && randomness == 1) {
324 pieces['b'] = pieces['w'];
325 flags += flags;
326 break;
327 }
328
329 let positions = ArrayFun.range(8);
330
331 // Get random squares for bishops
332 let randIndex = 2 * randInt(4);
333 const bishop1Pos = positions[randIndex];
334 // The second bishop must be on a square of different color
335 let randIndex_tmp = 2 * randInt(4) + 1;
336 const bishop2Pos = positions[randIndex_tmp];
337 // Remove chosen squares
338 positions.splice(Math.max(randIndex, randIndex_tmp), 1);
339 positions.splice(Math.min(randIndex, randIndex_tmp), 1);
340
341 // Get random squares for knights
342 randIndex = randInt(6);
343 const knight1Pos = positions[randIndex];
344 positions.splice(randIndex, 1);
345 randIndex = randInt(5);
346 const knight2Pos = positions[randIndex];
347 positions.splice(randIndex, 1);
348
349 // Get random square for queen
350 randIndex = randInt(4);
351 const queenPos = positions[randIndex];
352 positions.splice(randIndex, 1);
353
354 // Rooks and king positions are now fixed,
355 // because of the ordering rook-king-rook
356 const rook1Pos = positions[0];
357 const kingPos = positions[1];
358 const rook2Pos = positions[2];
359
360 // Finally put the shuffled pieces in the board array
361 pieces[c][rook1Pos] = "r";
362 pieces[c][knight1Pos] = "n";
363 pieces[c][bishop1Pos] = "b";
364 pieces[c][queenPos] = "q";
365 pieces[c][kingPos] = "k";
366 pieces[c][bishop2Pos] = "b";
367 pieces[c][knight2Pos] = "n";
368 pieces[c][rook2Pos] = "r";
369 flags += V.CoordToColumn(rook1Pos) + V.CoordToColumn(rook2Pos);
370 }
371 // Add turn + flags + enpassant
372 return (
373 pieces["b"].join("") +
374 "/pppppppp/8/8/8/8/PPPPPPPP/" +
375 pieces["w"].join("").toUpperCase() +
376 " w 0 " + flags + " -"
377 );
378 }
379
380 // "Parse" FEN: just return untransformed string data
381 static ParseFen(fen) {
382 const fenParts = fen.split(" ");
383 let res = {
384 position: fenParts[0],
385 turn: fenParts[1],
386 movesCount: fenParts[2]
387 };
388 let nextIdx = 3;
389 if (V.HasFlags) Object.assign(res, { flags: fenParts[nextIdx++] });
390 if (V.HasEnpassant) Object.assign(res, { enpassant: fenParts[nextIdx] });
391 return res;
392 }
393
394 // Return current fen (game state)
395 getFen() {
396 return (
397 this.getBaseFen() + " " +
398 this.getTurnFen() + " " +
399 this.movesCount +
400 (V.HasFlags ? " " + this.getFlagsFen() : "") +
401 (V.HasEnpassant ? " " + this.getEnpassantFen() : "")
402 );
403 }
404
405 getFenForRepeat() {
406 // Omit movesCount, only variable allowed to differ
407 return (
408 this.getBaseFen() + "_" +
409 this.getTurnFen() +
410 (V.HasFlags ? "_" + this.getFlagsFen() : "") +
411 (V.HasEnpassant ? "_" + this.getEnpassantFen() : "")
412 );
413 }
414
415 // Position part of the FEN string
416 getBaseFen() {
417 const format = (count) => {
418 // if more than 9 consecutive free spaces, break the integer,
419 // otherwise FEN parsing will fail.
420 if (count <= 9) return count;
421 // Currently only boards of size up to 11 or 12:
422 return "9" + (count - 9);
423 };
424 let position = "";
425 for (let i = 0; i < V.size.x; i++) {
426 let emptyCount = 0;
427 for (let j = 0; j < V.size.y; j++) {
428 if (this.board[i][j] == V.EMPTY) emptyCount++;
429 else {
430 if (emptyCount > 0) {
431 // Add empty squares in-between
432 position += format(emptyCount);
433 emptyCount = 0;
434 }
435 position += V.board2fen(this.board[i][j]);
436 }
437 }
438 if (emptyCount > 0) {
439 // "Flush remainder"
440 position += format(emptyCount);
441 }
442 if (i < V.size.x - 1) position += "/"; //separate rows
443 }
444 return position;
445 }
446
447 getTurnFen() {
448 return this.turn;
449 }
450
451 // Flags part of the FEN string
452 getFlagsFen() {
453 let flags = "";
454 // Castling flags
455 for (let c of ["w", "b"])
456 flags += this.castleFlags[c].map(V.CoordToColumn).join("");
457 return flags;
458 }
459
460 // Enpassant part of the FEN string
461 getEnpassantFen() {
462 const L = this.epSquares.length;
463 if (!this.epSquares[L - 1]) return "-"; //no en-passant
464 return V.CoordsToSquare(this.epSquares[L - 1]);
465 }
466
467 // Turn position fen into double array ["wb","wp","bk",...]
468 static GetBoard(position) {
469 const rows = position.split("/");
470 let board = ArrayFun.init(V.size.x, V.size.y, "");
471 for (let i = 0; i < rows.length; i++) {
472 let j = 0;
473 for (let indexInRow = 0; indexInRow < rows[i].length; indexInRow++) {
474 const character = rows[i][indexInRow];
475 const num = parseInt(character);
476 // If num is a number, just shift j:
477 if (!isNaN(num)) j += num;
478 // Else: something at position i,j
479 else board[i][j++] = V.fen2board(character);
480 }
481 }
482 return board;
483 }
484
485 // Extract (relevant) flags from fen
486 setFlags(fenflags) {
487 // white a-castle, h-castle, black a-castle, h-castle
488 this.castleFlags = { w: [-1, -1], b: [-1, -1] };
489 for (let i = 0; i < 4; i++) {
490 this.castleFlags[i < 2 ? "w" : "b"][i % 2] =
491 V.ColumnToCoord(fenflags.charAt(i));
492 }
493 }
494
495 //////////////////
496 // INITIALIZATION
497
498 // Fen string fully describes the game state
499 constructor(fen) {
500 if (!fen)
501 // In printDiagram() fen isn't supply because only getPpath() is used
502 // TODO: find a better solution!
503 return;
504 const fenParsed = V.ParseFen(fen);
505 this.board = V.GetBoard(fenParsed.position);
506 this.turn = fenParsed.turn;
507 this.movesCount = parseInt(fenParsed.movesCount);
508 this.setOtherVariables(fen);
509 }
510
511 // Scan board for kings positions
512 scanKings(fen) {
513 this.INIT_COL_KING = { w: -1, b: -1 };
514 // Squares of white and black king:
515 this.kingPos = { w: [-1, -1], b: [-1, -1] };
516 const fenRows = V.ParseFen(fen).position.split("/");
517 const startRow = { 'w': V.size.x - 1, 'b': 0 };
518 for (let i = 0; i < fenRows.length; i++) {
519 let k = 0; //column index on board
520 for (let j = 0; j < fenRows[i].length; j++) {
521 switch (fenRows[i].charAt(j)) {
522 case "k":
523 this.kingPos["b"] = [i, k];
524 this.INIT_COL_KING["b"] = k;
525 break;
526 case "K":
527 this.kingPos["w"] = [i, k];
528 this.INIT_COL_KING["w"] = k;
529 break;
530 default: {
531 const num = parseInt(fenRows[i].charAt(j));
532 if (!isNaN(num)) k += num - 1;
533 }
534 }
535 k++;
536 }
537 }
538 }
539
540 // Some additional variables from FEN (variant dependant)
541 setOtherVariables(fen) {
542 // Set flags and enpassant:
543 const parsedFen = V.ParseFen(fen);
544 if (V.HasFlags) this.setFlags(parsedFen.flags);
545 if (V.HasEnpassant) {
546 const epSq =
547 parsedFen.enpassant != "-"
548 ? this.getEpSquare(parsedFen.enpassant)
549 : undefined;
550 this.epSquares = [epSq];
551 }
552 // Search for kings positions:
553 this.scanKings(fen);
554 }
555
556 /////////////////////
557 // GETTERS & SETTERS
558
559 static get size() {
560 return { x: 8, y: 8 };
561 }
562
563 // Color of thing on square (i,j). 'undefined' if square is empty
564 getColor(i, j) {
565 return this.board[i][j].charAt(0);
566 }
567
568 // Piece type on square (i,j). 'undefined' if square is empty
569 getPiece(i, j) {
570 return this.board[i][j].charAt(1);
571 }
572
573 // Get opponent color
574 static GetOppCol(color) {
575 return color == "w" ? "b" : "w";
576 }
577
578 // Pieces codes (for a clearer code)
579 static get PAWN() {
580 return "p";
581 }
582 static get ROOK() {
583 return "r";
584 }
585 static get KNIGHT() {
586 return "n";
587 }
588 static get BISHOP() {
589 return "b";
590 }
591 static get QUEEN() {
592 return "q";
593 }
594 static get KING() {
595 return "k";
596 }
597
598 // For FEN checking:
599 static get PIECES() {
600 return [V.PAWN, V.ROOK, V.KNIGHT, V.BISHOP, V.QUEEN, V.KING];
601 }
602
603 // Empty square
604 static get EMPTY() {
605 return "";
606 }
607
608 // Some pieces movements
609 static get steps() {
610 return {
611 r: [
612 [-1, 0],
613 [1, 0],
614 [0, -1],
615 [0, 1]
616 ],
617 n: [
618 [-1, -2],
619 [-1, 2],
620 [1, -2],
621 [1, 2],
622 [-2, -1],
623 [-2, 1],
624 [2, -1],
625 [2, 1]
626 ],
627 b: [
628 [-1, -1],
629 [-1, 1],
630 [1, -1],
631 [1, 1]
632 ]
633 };
634 }
635
636 ////////////////////
637 // MOVES GENERATION
638
639 // All possible moves from selected square
640 getPotentialMovesFrom([x, y]) {
641 switch (this.getPiece(x, y)) {
642 case V.PAWN:
643 return this.getPotentialPawnMoves([x, y]);
644 case V.ROOK:
645 return this.getPotentialRookMoves([x, y]);
646 case V.KNIGHT:
647 return this.getPotentialKnightMoves([x, y]);
648 case V.BISHOP:
649 return this.getPotentialBishopMoves([x, y]);
650 case V.QUEEN:
651 return this.getPotentialQueenMoves([x, y]);
652 case V.KING:
653 return this.getPotentialKingMoves([x, y]);
654 }
655 return []; //never reached
656 }
657
658 // Build a regular move from its initial and destination squares.
659 // tr: transformation
660 getBasicMove([sx, sy], [ex, ey], tr) {
661 const initColor = this.getColor(sx, sy);
662 const initPiece = this.getPiece(sx, sy);
663 let mv = new Move({
664 appear: [
665 new PiPo({
666 x: ex,
667 y: ey,
668 c: tr ? tr.c : initColor,
669 p: tr ? tr.p : initPiece
670 })
671 ],
672 vanish: [
673 new PiPo({
674 x: sx,
675 y: sy,
676 c: initColor,
677 p: initPiece
678 })
679 ]
680 });
681
682 // The opponent piece disappears if we take it
683 if (this.board[ex][ey] != V.EMPTY) {
684 mv.vanish.push(
685 new PiPo({
686 x: ex,
687 y: ey,
688 c: this.getColor(ex, ey),
689 p: this.getPiece(ex, ey)
690 })
691 );
692 }
693
694 return mv;
695 }
696
697 // Generic method to find possible moves of non-pawn pieces:
698 // "sliding or jumping"
699 getSlideNJumpMoves([x, y], steps, oneStep) {
700 let moves = [];
701 outerLoop: for (let step of steps) {
702 let i = x + step[0];
703 let j = y + step[1];
704 while (V.OnBoard(i, j) && this.board[i][j] == V.EMPTY) {
705 moves.push(this.getBasicMove([x, y], [i, j]));
706 if (oneStep) continue outerLoop;
707 i += step[0];
708 j += step[1];
709 }
710 if (V.OnBoard(i, j) && this.canTake([x, y], [i, j]))
711 moves.push(this.getBasicMove([x, y], [i, j]));
712 }
713 return moves;
714 }
715
716 // Special case of en-passant captures: treated separately
717 getEnpassantCaptures([x, y], shiftX) {
718 const Lep = this.epSquares.length;
719 const epSquare = this.epSquares[Lep - 1]; //always at least one element
720 let enpassantMove = null;
721 if (
722 !!epSquare &&
723 epSquare.x == x + shiftX &&
724 Math.abs(epSquare.y - y) == 1
725 ) {
726 enpassantMove = this.getBasicMove([x, y], [epSquare.x, epSquare.y]);
727 enpassantMove.vanish.push({
728 x: x,
729 y: epSquare.y,
730 // Captured piece is usually a pawn, but next line seems harmless
731 p: this.getPiece(x, epSquare.y),
732 c: this.getColor(x, epSquare.y)
733 });
734 }
735 return !!enpassantMove ? [enpassantMove] : [];
736 }
737
738 // Consider all potential promotions:
739 addPawnMoves([x1, y1], [x2, y2], moves, promotions) {
740 let finalPieces = [V.PAWN];
741 const color = this.turn; //this.getColor(x1, y1);
742 const lastRank = (color == "w" ? 0 : V.size.x - 1);
743 if (x2 == lastRank) {
744 // promotions arg: special override for Hiddenqueen variant
745 if (!!promotions) finalPieces = promotions;
746 else if (!!V.PawnSpecs.promotions)
747 finalPieces = V.PawnSpecs.promotions;
748 }
749 let tr = null;
750 for (let piece of finalPieces) {
751 tr = (piece != V.PAWN ? { c: color, p: piece } : null);
752 moves.push(this.getBasicMove([x1, y1], [x2, y2], tr));
753 }
754 }
755
756 // What are the pawn moves from square x,y ?
757 getPotentialPawnMoves([x, y], promotions) {
758 const color = this.turn; //this.getColor(x, y);
759 const [sizeX, sizeY] = [V.size.x, V.size.y];
760 const pawnShiftX = V.PawnSpecs.directions[color];
761 const firstRank = (color == "w" ? sizeX - 1 : 0);
762
763 // Pawn movements in shiftX direction:
764 const getPawnMoves = (shiftX) => {
765 let moves = [];
766 // NOTE: next condition is generally true (no pawn on last rank)
767 if (x + shiftX >= 0 && x + shiftX < sizeX) {
768 if (this.board[x + shiftX][y] == V.EMPTY) {
769 // One square forward
770 this.addPawnMoves([x, y], [x + shiftX, y], moves, promotions);
771 // Next condition because pawns on 1st rank can generally jump
772 if (
773 V.PawnSpecs.twoSquares &&
774 (
775 (color == 'w' && x >= V.size.x - 1 - V.PawnSpecs.initShift['w'])
776 ||
777 (color == 'b' && x <= V.PawnSpecs.initShift['b'])
778 )
779 ) {
780 if (this.board[x + 2 * shiftX][y] == V.EMPTY) {
781 // Two squares jump
782 moves.push(this.getBasicMove([x, y], [x + 2 * shiftX, y]));
783 if (
784 V.PawnSpecs.threeSquares &&
785 this.board[x + 3 * shiftX][y] == V.EMPTY
786 ) {
787 // Three squares jump
788 moves.push(this.getBasicMove([x, y], [x + 3 * shiftX, y]));
789 }
790 }
791 }
792 }
793 // Captures
794 if (V.PawnSpecs.canCapture) {
795 for (let shiftY of [-1, 1]) {
796 if (
797 y + shiftY >= 0 &&
798 y + shiftY < sizeY
799 ) {
800 if (
801 this.board[x + shiftX][y + shiftY] != V.EMPTY &&
802 this.canTake([x, y], [x + shiftX, y + shiftY])
803 ) {
804 this.addPawnMoves(
805 [x, y], [x + shiftX, y + shiftY],
806 moves, promotions
807 );
808 }
809 if (
810 V.PawnSpecs.captureBackward &&
811 x - shiftX >= 0 && x - shiftX < V.size.x &&
812 this.board[x - shiftX][y + shiftY] != V.EMPTY &&
813 this.canTake([x, y], [x - shiftX, y + shiftY])
814 ) {
815 this.addPawnMoves(
816 [x, y], [x + shiftX, y + shiftY],
817 moves, promotions
818 );
819 }
820 }
821 }
822 }
823 }
824 return moves;
825 }
826
827 let pMoves = getPawnMoves(pawnShiftX);
828 if (V.PawnSpecs.bidirectional)
829 pMoves = pMoves.concat(getPawnMoves(-pawnShiftX));
830
831 if (V.HasEnpassant) {
832 // NOTE: backward en-passant captures are not considered
833 // because no rules define them (for now).
834 Array.prototype.push.apply(
835 pMoves,
836 this.getEnpassantCaptures([x, y], pawnShiftX)
837 );
838 }
839
840 return pMoves;
841 }
842
843 // What are the rook moves from square x,y ?
844 getPotentialRookMoves(sq) {
845 return this.getSlideNJumpMoves(sq, V.steps[V.ROOK]);
846 }
847
848 // What are the knight moves from square x,y ?
849 getPotentialKnightMoves(sq) {
850 return this.getSlideNJumpMoves(sq, V.steps[V.KNIGHT], "oneStep");
851 }
852
853 // What are the bishop moves from square x,y ?
854 getPotentialBishopMoves(sq) {
855 return this.getSlideNJumpMoves(sq, V.steps[V.BISHOP]);
856 }
857
858 // What are the queen moves from square x,y ?
859 getPotentialQueenMoves(sq) {
860 return this.getSlideNJumpMoves(
861 sq,
862 V.steps[V.ROOK].concat(V.steps[V.BISHOP])
863 );
864 }
865
866 // What are the king moves from square x,y ?
867 getPotentialKingMoves(sq) {
868 // Initialize with normal moves
869 let moves = this.getSlideNJumpMoves(
870 sq,
871 V.steps[V.ROOK].concat(V.steps[V.BISHOP]),
872 "oneStep"
873 );
874 if (V.HasCastle) moves = moves.concat(this.getCastleMoves(sq));
875 return moves;
876 }
877
878 // "castleInCheck" arg to let some variants castle under check
879 getCastleMoves([x, y], castleInCheck) {
880 const c = this.getColor(x, y);
881 if (x != (c == "w" ? V.size.x - 1 : 0) || y != this.INIT_COL_KING[c])
882 return []; //x isn't first rank, or king has moved (shortcut)
883
884 // Castling ?
885 const oppCol = V.GetOppCol(c);
886 let moves = [];
887 let i = 0;
888 // King, then rook:
889 const finalSquares = [
890 [2, 3],
891 [V.size.y - 2, V.size.y - 3]
892 ];
893 castlingCheck: for (
894 let castleSide = 0;
895 castleSide < 2;
896 castleSide++ //large, then small
897 ) {
898 if (this.castleFlags[c][castleSide] >= V.size.y) continue;
899 // If this code is reached, rook and king are on initial position
900
901 // NOTE: in some variants this is not a rook
902 const rookPos = this.castleFlags[c][castleSide];
903 if (this.board[x][rookPos] == V.EMPTY || this.getColor(x, rookPos) != c)
904 // Rook is not here, or changed color (see Benedict)
905 continue;
906
907 // Nothing on the path of the king ? (and no checks)
908 const castlingPiece = this.getPiece(x, rookPos);
909 const finDist = finalSquares[castleSide][0] - y;
910 let step = finDist / Math.max(1, Math.abs(finDist));
911 i = y;
912 do {
913 if (
914 // NOTE: "castling" arg is used by some variants (Monster),
915 // where "isAttacked" is overloaded in an infinite-recursive way.
916 (!castleInCheck && this.isAttacked([x, i], oppCol, "castling")) ||
917 (this.board[x][i] != V.EMPTY &&
918 // NOTE: next check is enough, because of chessboard constraints
919 (this.getColor(x, i) != c ||
920 ![V.KING, castlingPiece].includes(this.getPiece(x, i))))
921 ) {
922 continue castlingCheck;
923 }
924 i += step;
925 } while (i != finalSquares[castleSide][0]);
926
927 // Nothing on the path to the rook?
928 step = castleSide == 0 ? -1 : 1;
929 for (i = y + step; i != rookPos; i += step) {
930 if (this.board[x][i] != V.EMPTY) continue castlingCheck;
931 }
932
933 // Nothing on final squares, except maybe king and castling rook?
934 for (i = 0; i < 2; i++) {
935 if (
936 finalSquares[castleSide][i] != rookPos &&
937 this.board[x][finalSquares[castleSide][i]] != V.EMPTY &&
938 (
939 this.getPiece(x, finalSquares[castleSide][i]) != V.KING ||
940 this.getColor(x, finalSquares[castleSide][i]) != c
941 )
942 ) {
943 continue castlingCheck;
944 }
945 }
946
947 // If this code is reached, castle is valid
948 moves.push(
949 new Move({
950 appear: [
951 new PiPo({
952 x: x,
953 y: finalSquares[castleSide][0],
954 p: V.KING,
955 c: c
956 }),
957 new PiPo({
958 x: x,
959 y: finalSquares[castleSide][1],
960 p: castlingPiece,
961 c: c
962 })
963 ],
964 vanish: [
965 new PiPo({ x: x, y: y, p: V.KING, c: c }),
966 new PiPo({ x: x, y: rookPos, p: castlingPiece, c: c })
967 ],
968 end:
969 Math.abs(y - rookPos) <= 2
970 ? { x: x, y: rookPos }
971 : { x: x, y: y + 2 * (castleSide == 0 ? -1 : 1) }
972 })
973 );
974 }
975
976 return moves;
977 }
978
979 ////////////////////
980 // MOVES VALIDATION
981
982 // For the interface: possible moves for the current turn from square sq
983 getPossibleMovesFrom(sq) {
984 return this.filterValid(this.getPotentialMovesFrom(sq));
985 }
986
987 // TODO: promotions (into R,B,N,Q) should be filtered only once
988 filterValid(moves) {
989 if (moves.length == 0) return [];
990 const color = this.turn;
991 return moves.filter(m => {
992 this.play(m);
993 const res = !this.underCheck(color);
994 this.undo(m);
995 return res;
996 });
997 }
998
999 getAllPotentialMoves() {
1000 const color = this.turn;
1001 let potentialMoves = [];
1002 for (let i = 0; i < V.size.x; i++) {
1003 for (let j = 0; j < V.size.y; j++) {
1004 if (this.board[i][j] != V.EMPTY && this.getColor(i, j) == color) {
1005 Array.prototype.push.apply(
1006 potentialMoves,
1007 this.getPotentialMovesFrom([i, j])
1008 );
1009 }
1010 }
1011 }
1012 return potentialMoves;
1013 }
1014
1015 // Search for all valid moves considering current turn
1016 // (for engine and game end)
1017 getAllValidMoves() {
1018 return this.filterValid(this.getAllPotentialMoves());
1019 }
1020
1021 // Stop at the first move found
1022 // TODO: not really, it explores all moves from a square (one is enough).
1023 atLeastOneMove() {
1024 const color = this.turn;
1025 for (let i = 0; i < V.size.x; i++) {
1026 for (let j = 0; j < V.size.y; j++) {
1027 if (this.board[i][j] != V.EMPTY && this.getColor(i, j) == color) {
1028 const moves = this.getPotentialMovesFrom([i, j]);
1029 if (moves.length > 0) {
1030 for (let k = 0; k < moves.length; k++)
1031 if (this.filterValid([moves[k]]).length > 0) return true;
1032 }
1033 }
1034 }
1035 }
1036 return false;
1037 }
1038
1039 // Check if pieces of given color are attacking (king) on square x,y
1040 isAttacked(sq, color) {
1041 return (
1042 this.isAttackedByPawn(sq, color) ||
1043 this.isAttackedByRook(sq, color) ||
1044 this.isAttackedByKnight(sq, color) ||
1045 this.isAttackedByBishop(sq, color) ||
1046 this.isAttackedByQueen(sq, color) ||
1047 this.isAttackedByKing(sq, color)
1048 );
1049 }
1050
1051 // Generic method for non-pawn pieces ("sliding or jumping"):
1052 // is x,y attacked by a piece of given color ?
1053 isAttackedBySlideNJump([x, y], color, piece, steps, oneStep) {
1054 for (let step of steps) {
1055 let rx = x + step[0],
1056 ry = y + step[1];
1057 while (V.OnBoard(rx, ry) && this.board[rx][ry] == V.EMPTY && !oneStep) {
1058 rx += step[0];
1059 ry += step[1];
1060 }
1061 if (
1062 V.OnBoard(rx, ry) &&
1063 this.getPiece(rx, ry) == piece &&
1064 this.getColor(rx, ry) == color
1065 ) {
1066 return true;
1067 }
1068 }
1069 return false;
1070 }
1071
1072 // Is square x,y attacked by 'color' pawns ?
1073 isAttackedByPawn(sq, color) {
1074 const pawnShift = (color == "w" ? 1 : -1);
1075 return this.isAttackedBySlideNJump(
1076 sq,
1077 color,
1078 V.PAWN,
1079 [[pawnShift, 1], [pawnShift, -1]],
1080 "oneStep"
1081 );
1082 }
1083
1084 // Is square x,y attacked by 'color' rooks ?
1085 isAttackedByRook(sq, color) {
1086 return this.isAttackedBySlideNJump(sq, color, V.ROOK, V.steps[V.ROOK]);
1087 }
1088
1089 // Is square x,y attacked by 'color' knights ?
1090 isAttackedByKnight(sq, color) {
1091 return this.isAttackedBySlideNJump(
1092 sq,
1093 color,
1094 V.KNIGHT,
1095 V.steps[V.KNIGHT],
1096 "oneStep"
1097 );
1098 }
1099
1100 // Is square x,y attacked by 'color' bishops ?
1101 isAttackedByBishop(sq, color) {
1102 return this.isAttackedBySlideNJump(sq, color, V.BISHOP, V.steps[V.BISHOP]);
1103 }
1104
1105 // Is square x,y attacked by 'color' queens ?
1106 isAttackedByQueen(sq, color) {
1107 return this.isAttackedBySlideNJump(
1108 sq,
1109 color,
1110 V.QUEEN,
1111 V.steps[V.ROOK].concat(V.steps[V.BISHOP])
1112 );
1113 }
1114
1115 // Is square x,y attacked by 'color' king(s) ?
1116 isAttackedByKing(sq, color) {
1117 return this.isAttackedBySlideNJump(
1118 sq,
1119 color,
1120 V.KING,
1121 V.steps[V.ROOK].concat(V.steps[V.BISHOP]),
1122 "oneStep"
1123 );
1124 }
1125
1126 // Is color under check after his move ?
1127 underCheck(color) {
1128 return this.isAttacked(this.kingPos[color], V.GetOppCol(color));
1129 }
1130
1131 /////////////////
1132 // MOVES PLAYING
1133
1134 // Apply a move on board
1135 static PlayOnBoard(board, move) {
1136 for (let psq of move.vanish) board[psq.x][psq.y] = V.EMPTY;
1137 for (let psq of move.appear) board[psq.x][psq.y] = psq.c + psq.p;
1138 }
1139 // Un-apply the played move
1140 static UndoOnBoard(board, move) {
1141 for (let psq of move.appear) board[psq.x][psq.y] = V.EMPTY;
1142 for (let psq of move.vanish) board[psq.x][psq.y] = psq.c + psq.p;
1143 }
1144
1145 prePlay() {}
1146
1147 play(move) {
1148 // DEBUG:
1149 // if (!this.states) this.states = [];
1150 // const stateFen = this.getFen() + JSON.stringify(this.kingPos);
1151 // this.states.push(stateFen);
1152
1153 this.prePlay(move);
1154 // Save flags (for undo)
1155 if (V.HasFlags) move.flags = JSON.stringify(this.aggregateFlags());
1156 if (V.HasEnpassant) this.epSquares.push(this.getEpSquare(move));
1157 V.PlayOnBoard(this.board, move);
1158 this.turn = V.GetOppCol(this.turn);
1159 this.movesCount++;
1160 this.postPlay(move);
1161 }
1162
1163 updateCastleFlags(move, piece) {
1164 const c = V.GetOppCol(this.turn);
1165 const firstRank = (c == "w" ? V.size.x - 1 : 0);
1166 // Update castling flags if rooks are moved
1167 const oppCol = this.turn;
1168 const oppFirstRank = V.size.x - 1 - firstRank;
1169 if (piece == V.KING && move.appear.length > 0)
1170 this.castleFlags[c] = [V.size.y, V.size.y];
1171 else if (
1172 move.start.x == firstRank && //our rook moves?
1173 this.castleFlags[c].includes(move.start.y)
1174 ) {
1175 const flagIdx = (move.start.y == this.castleFlags[c][0] ? 0 : 1);
1176 this.castleFlags[c][flagIdx] = V.size.y;
1177 }
1178 // NOTE: not "else if" because a rook could take an opposing rook
1179 if (
1180 move.end.x == oppFirstRank && //we took opponent rook?
1181 this.castleFlags[oppCol].includes(move.end.y)
1182 ) {
1183 const flagIdx = (move.end.y == this.castleFlags[oppCol][0] ? 0 : 1);
1184 this.castleFlags[oppCol][flagIdx] = V.size.y;
1185 }
1186 }
1187
1188 // After move is played, update variables + flags
1189 postPlay(move) {
1190 const c = V.GetOppCol(this.turn);
1191 let piece = undefined;
1192 if (move.vanish.length >= 1)
1193 // Usual case, something is moved
1194 piece = move.vanish[0].p;
1195 else
1196 // Crazyhouse-like variants
1197 piece = move.appear[0].p;
1198
1199 // Update king position + flags
1200 if (piece == V.KING && move.appear.length > 0) {
1201 this.kingPos[c][0] = move.appear[0].x;
1202 this.kingPos[c][1] = move.appear[0].y;
1203 }
1204 if (V.HasCastle) this.updateCastleFlags(move, piece);
1205 }
1206
1207 preUndo() {}
1208
1209 undo(move) {
1210 this.preUndo(move);
1211 if (V.HasEnpassant) this.epSquares.pop();
1212 if (V.HasFlags) this.disaggregateFlags(JSON.parse(move.flags));
1213 V.UndoOnBoard(this.board, move);
1214 this.turn = V.GetOppCol(this.turn);
1215 this.movesCount--;
1216 this.postUndo(move);
1217
1218 // DEBUG:
1219 // const stateFen = this.getFen() + JSON.stringify(this.kingPos);
1220 // if (stateFen != this.states[this.states.length-1]) debugger;
1221 // this.states.pop();
1222 }
1223
1224 // After move is undo-ed *and flags resetted*, un-update other variables
1225 // TODO: more symmetry, by storing flags increment in move (?!)
1226 postUndo(move) {
1227 // (Potentially) Reset king position
1228 const c = this.getColor(move.start.x, move.start.y);
1229 if (this.getPiece(move.start.x, move.start.y) == V.KING)
1230 this.kingPos[c] = [move.start.x, move.start.y];
1231 }
1232
1233 ///////////////
1234 // END OF GAME
1235
1236 // What is the score ? (Interesting if game is over)
1237 getCurrentScore() {
1238 if (this.atLeastOneMove()) return "*";
1239 // Game over
1240 const color = this.turn;
1241 // No valid move: stalemate or checkmate?
1242 if (!this.underCheck(color)) return "1/2";
1243 // OK, checkmate
1244 return (color == "w" ? "0-1" : "1-0");
1245 }
1246
1247 ///////////////
1248 // ENGINE PLAY
1249
1250 // Pieces values
1251 static get VALUES() {
1252 return {
1253 p: 1,
1254 r: 5,
1255 n: 3,
1256 b: 3,
1257 q: 9,
1258 k: 1000
1259 };
1260 }
1261
1262 // "Checkmate" (unreachable eval)
1263 static get INFINITY() {
1264 return 9999;
1265 }
1266
1267 // At this value or above, the game is over
1268 static get THRESHOLD_MATE() {
1269 return V.INFINITY;
1270 }
1271
1272 // Search depth: 1,2 for e.g. higher branching factor, 4 for smaller
1273 static get SEARCH_DEPTH() {
1274 return 3;
1275 }
1276
1277 // 'movesList' arg for some variants to provide a custom list
1278 getComputerMove(movesList) {
1279 const maxeval = V.INFINITY;
1280 const color = this.turn;
1281 let moves1 = movesList || this.getAllValidMoves();
1282
1283 if (moves1.length == 0)
1284 // TODO: this situation should not happen
1285 return null;
1286
1287 // Rank moves using a min-max at depth 2 (if search_depth >= 2!)
1288 for (let i = 0; i < moves1.length; i++) {
1289 this.play(moves1[i]);
1290 const score1 = this.getCurrentScore();
1291 if (score1 != "*") {
1292 moves1[i].eval =
1293 score1 == "1/2"
1294 ? 0
1295 : (score1 == "1-0" ? 1 : -1) * maxeval;
1296 }
1297 if (V.SEARCH_DEPTH == 1 || score1 != "*") {
1298 if (!moves1[i].eval) moves1[i].eval = this.evalPosition();
1299 this.undo(moves1[i]);
1300 continue;
1301 }
1302 // Initial self evaluation is very low: "I'm checkmated"
1303 moves1[i].eval = (color == "w" ? -1 : 1) * maxeval;
1304 // Initial enemy evaluation is very low too, for him
1305 let eval2 = (color == "w" ? 1 : -1) * maxeval;
1306 // Second half-move:
1307 let moves2 = this.getAllValidMoves();
1308 for (let j = 0; j < moves2.length; j++) {
1309 this.play(moves2[j]);
1310 const score2 = this.getCurrentScore();
1311 let evalPos = 0; //1/2 value
1312 switch (score2) {
1313 case "*":
1314 evalPos = this.evalPosition();
1315 break;
1316 case "1-0":
1317 evalPos = maxeval;
1318 break;
1319 case "0-1":
1320 evalPos = -maxeval;
1321 break;
1322 }
1323 if (
1324 (color == "w" && evalPos < eval2) ||
1325 (color == "b" && evalPos > eval2)
1326 ) {
1327 eval2 = evalPos;
1328 }
1329 this.undo(moves2[j]);
1330 }
1331 if (
1332 (color == "w" && eval2 > moves1[i].eval) ||
1333 (color == "b" && eval2 < moves1[i].eval)
1334 ) {
1335 moves1[i].eval = eval2;
1336 }
1337 this.undo(moves1[i]);
1338 }
1339 moves1.sort((a, b) => {
1340 return (color == "w" ? 1 : -1) * (b.eval - a.eval);
1341 });
1342 // console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
1343
1344 // Skip depth 3+ if we found a checkmate (or if we are checkmated in 1...)
1345 if (V.SEARCH_DEPTH >= 3 && Math.abs(moves1[0].eval) < V.THRESHOLD_MATE) {
1346 for (let i = 0; i < moves1.length; i++) {
1347 this.play(moves1[i]);
1348 // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
1349 moves1[i].eval =
1350 0.1 * moves1[i].eval +
1351 this.alphabeta(V.SEARCH_DEPTH - 1, -maxeval, maxeval);
1352 this.undo(moves1[i]);
1353 }
1354 moves1.sort((a, b) => {
1355 return (color == "w" ? 1 : -1) * (b.eval - a.eval);
1356 });
1357 }
1358
1359 let candidates = [0];
1360 for (let i = 1; i < moves1.length && moves1[i].eval == moves1[0].eval; i++)
1361 candidates.push(i);
1362 return moves1[candidates[randInt(candidates.length)]];
1363 }
1364
1365 alphabeta(depth, alpha, beta) {
1366 const maxeval = V.INFINITY;
1367 const color = this.turn;
1368 const score = this.getCurrentScore();
1369 if (score != "*")
1370 return score == "1/2" ? 0 : (score == "1-0" ? 1 : -1) * maxeval;
1371 if (depth == 0) return this.evalPosition();
1372 const moves = this.getAllValidMoves();
1373 let v = color == "w" ? -maxeval : maxeval;
1374 if (color == "w") {
1375 for (let i = 0; i < moves.length; i++) {
1376 this.play(moves[i]);
1377 v = Math.max(v, this.alphabeta(depth - 1, alpha, beta));
1378 this.undo(moves[i]);
1379 alpha = Math.max(alpha, v);
1380 if (alpha >= beta) break; //beta cutoff
1381 }
1382 }
1383 else {
1384 // color=="b"
1385 for (let i = 0; i < moves.length; i++) {
1386 this.play(moves[i]);
1387 v = Math.min(v, this.alphabeta(depth - 1, alpha, beta));
1388 this.undo(moves[i]);
1389 beta = Math.min(beta, v);
1390 if (alpha >= beta) break; //alpha cutoff
1391 }
1392 }
1393 return v;
1394 }
1395
1396 evalPosition() {
1397 let evaluation = 0;
1398 // Just count material for now
1399 for (let i = 0; i < V.size.x; i++) {
1400 for (let j = 0; j < V.size.y; j++) {
1401 if (this.board[i][j] != V.EMPTY) {
1402 const sign = this.getColor(i, j) == "w" ? 1 : -1;
1403 evaluation += sign * V.VALUES[this.getPiece(i, j)];
1404 }
1405 }
1406 }
1407 return evaluation;
1408 }
1409
1410 /////////////////////////
1411 // MOVES + GAME NOTATION
1412 /////////////////////////
1413
1414 // Context: just before move is played, turn hasn't changed
1415 // TODO: un-ambiguous notation (switch on piece type, check directions...)
1416 getNotation(move) {
1417 if (move.appear.length == 2 && move.appear[0].p == V.KING)
1418 // Castle
1419 return move.end.y < move.start.y ? "0-0-0" : "0-0";
1420
1421 // Translate final square
1422 const finalSquare = V.CoordsToSquare(move.end);
1423
1424 const piece = this.getPiece(move.start.x, move.start.y);
1425 if (piece == V.PAWN) {
1426 // Pawn move
1427 let notation = "";
1428 if (move.vanish.length > move.appear.length) {
1429 // Capture
1430 const startColumn = V.CoordToColumn(move.start.y);
1431 notation = startColumn + "x" + finalSquare;
1432 }
1433 else notation = finalSquare;
1434 if (move.appear.length > 0 && move.appear[0].p != V.PAWN)
1435 // Promotion
1436 notation += "=" + move.appear[0].p.toUpperCase();
1437 return notation;
1438 }
1439 // Piece movement
1440 return (
1441 piece.toUpperCase() +
1442 (move.vanish.length > move.appear.length ? "x" : "") +
1443 finalSquare
1444 );
1445 }
1446
1447 static GetUnambiguousNotation(move) {
1448 // Machine-readable format with all the informations about the move
1449 return (
1450 (!!move.start && V.OnBoard(move.start.x, move.start.y)
1451 ? V.CoordsToSquare(move.start)
1452 : "-"
1453 ) + "." +
1454 (!!move.end && V.OnBoard(move.end.x, move.end.y)
1455 ? V.CoordsToSquare(move.end)
1456 : "-"
1457 ) + " " +
1458 (!!move.appear && move.appear.length > 0
1459 ? move.appear.map(a =>
1460 a.c + a.p + V.CoordsToSquare({ x: a.x, y: a.y })).join(".")
1461 : "-"
1462 ) + "/" +
1463 (!!move.vanish && move.vanish.length > 0
1464 ? move.vanish.map(a =>
1465 a.c + a.p + V.CoordsToSquare({ x: a.x, y: a.y })).join(".")
1466 : "-"
1467 )
1468 );
1469 }
1470 };