Fix Convert, start Chaining
[xogo.git] / variants / Chaining / class.js
1 import ChessRules from "/base_rules.js";
2 import PiPo from "/utils/PiPo.js";
3 import Move from "/utils/Move.js";
4
5 export default class ChainingRules extends ChessRules {
6
7 static get Options() {
8 return {
9 select: C.Options.select,
10 input: C.Options.input,
11 styles: ["atomic", "capture", "crazyhouse", "cylinder", "dark", "zen"]
12 };
13 }
14
15 get hasSelfCaptures() {
16 return true;
17 }
18
19 canSelfTake() {
20 return true; //self captures induce chaining
21 }
22
23 setOtherVariables(fenParsed, pieceArray) {
24 super.setOtherVariables(fenParsed, pieceArray);
25 // Stack of "last move" only for intermediate chaining
26 this.lastMoveEnd = [];
27 }
28
29 getBasicMove([sx, sy], [ex, ey], tr) {
30 const L = this.lastMoveEnd.length;
31 const piece = (L >= 1 ? this.lastMoveEnd[L-1].p : null);
32 if (
33 this.board[ex][ey] == "" ||
34 this.getColor(ex, ey) == C.GetOppTurn(this.turn)
35 ) {
36 if (piece && !tr)
37 tr = {c: this.turn, p: piece};
38 let mv = super.getBasicMove([sx, sy], [ex, ey], tr);
39 if (piece)
40 mv.vanish.pop(); //end of a chain: initial piece remains
41 return mv;
42 }
43 // (Self)Capture: initial, or inside a chain
44 const initPiece = (piece || this.getPiece(sx, sy)),
45 destPiece = this.getPiece(ex, ey);
46 let mv = new Move({
47 start: {x: sx, y: sy},
48 end: {x: ex, y: ey},
49 appear: [
50 new PiPo({
51 x: ex,
52 y: ey,
53 c: this.turn,
54 p: (!!tr ? tr.p : initPiece)
55 })
56 ],
57 vanish: [
58 new PiPo({
59 x: ex,
60 y: ey,
61 c: this.turn,
62 p: destPiece
63 })
64 ]
65 });
66 if (!piece) {
67 // Initial capture
68 mv.vanish.unshift(
69 new PiPo({
70 x: sx,
71 y: sy,
72 c: this.turn,
73 p: initPiece
74 })
75 );
76 }
77 mv.chained = destPiece; //easier (no need to detect it)
78 return mv;
79 }
80
81 getPiece(x, y) {
82 const L = this.lastMoveEnd.length;
83 if (L >= 1 && this.lastMoveEnd[L-1].x == x && this.lastMoveEnd[L-1].y == y)
84 return this.lastMoveEnd[L-1].p;
85 return super.getPiece(x, y);
86 }
87
88 getPotentialMovesFrom([x, y], color) {
89 const L = this.lastMoveEnd.length;
90 if (
91 L >= 1 &&
92 (x != this.lastMoveEnd[L-1].x || y != this.lastMoveEnd[L-1].y)
93 ) {
94 // A self-capture was played: wrong square
95 return [];
96 }
97 return super.getPotentialMovesFrom([x, y], color);
98 }
99
100 isLastMove(move) {
101 return !move.chained;
102 }
103
104 postPlay(move) {
105 super.postPlay(move);
106 if (!!move.converted) {
107 this.lastMoveEnd.push({
108 x: move.end.x,
109 y: move.end.y,
110 p: move.chained
111 });
112 }
113 else
114 this.lastMoveEnd = [];
115 }
116
117 };