A few fixes
[vchess.git] / client / src / variants / Football.js
CommitLineData
107dc1bd 1import { ChessRules } from "@/base_rules";
5c50b18e
BA
2import { randInt, shuffle } from "@/utils/alea";
3import { ArrayFun } from "@/utils/array";
107dc1bd
BA
4
5export class FootballRules extends ChessRules {
7e8a7ea1 6
4f3a0823
BA
7 static get HasEnpassant() {
8 return false;
9 }
10
107dc1bd
BA
11 static get HasFlags() {
12 return false;
13 }
14
4f3a0823
BA
15 static get size() {
16 return { x: 9, y: 9 };
107dc1bd
BA
17 }
18
19 static get Lines() {
20 return [
21 // White goal:
4f3a0823 22 [[0, 4], [0, 5]],
107dc1bd 23 [[0, 5], [1, 5]],
4f3a0823 24 [[1, 4], [0, 4]],
107dc1bd 25 // Black goal:
4f3a0823
BA
26 [[9, 4], [9, 5]],
27 [[9, 5], [8, 5]],
28 [[8, 4], [9, 4]]
107dc1bd
BA
29 ];
30 }
31
4f3a0823
BA
32 static get BALL() {
33 // 'b' is already taken:
34 return "aa";
35 }
36
37 // Check that exactly one ball is on the board
38 // + at least one piece per color.
107dc1bd
BA
39 static IsGoodPosition(position) {
40 if (position.length == 0) return false;
41 const rows = position.split("/");
42 if (rows.length != V.size.x) return false;
107dc1bd 43 let pieces = { "w": 0, "b": 0 };
4f3a0823 44 let ballCount = 0;
107dc1bd
BA
45 for (let row of rows) {
46 let sumElts = 0;
47 for (let i = 0; i < row.length; i++) {
48 const lowerRi = row[i].toLowerCase();
4f3a0823
BA
49 if (!!lowerRi.match(/^[a-z]$/)) {
50 if (V.PIECES.includes(lowerRi))
51 pieces[row[i] == lowerRi ? "b" : "w"]++;
52 else if (lowerRi == 'a') ballCount++;
53 else return false;
107dc1bd 54 sumElts++;
0f7762c1
BA
55 }
56 else {
e50a8025 57 const num = parseInt(row[i], 10);
107dc1bd
BA
58 if (isNaN(num)) return false;
59 sumElts += num;
60 }
61 }
62 if (sumElts != V.size.y) return false;
63 }
4f3a0823
BA
64 if (ballCount != 1 || Object.values(pieces).some(v => v == 0))
65 return false;
107dc1bd
BA
66 return true;
67 }
68
4f3a0823
BA
69 static board2fen(b) {
70 if (b == V.BALL) return 'a';
71 return ChessRules.board2fen(b);
72 }
107dc1bd 73
4f3a0823
BA
74 static fen2board(f) {
75 if (f == 'a') return V.BALL;
76 return ChessRules.fen2board(f);
77 }
78
79 getPpath(b) {
80 if (b == V.BALL) return "Football/ball";
81 return b;
82 }
83
84 canIplay(side, [x, y]) {
85 return (
86 side == this.turn &&
87 (this.board[x][y] == V.BALL || this.getColor(x, y) == side)
88 );
89 }
90
91 // No checks or king tracking etc. But, track ball
92 setOtherVariables() {
93 // Stack of "kicked by" coordinates, to avoid infinite loops
94 this.kickedBy = [ {} ];
95 this.subTurn = 1;
96 this.ballPos = [-1, -1];
97 for (let i=0; i < V.size.x; i++) {
98 for (let j=0; j< V.size.y; j++) {
99 if (this.board[i][j] == V.BALL) {
100 this.ballPos = [i, j];
101 return;
102 }
103 }
104 }
105 }
106
107 static GenRandInitFen(randomness) {
108 if (randomness == 0)
109 return "rnbq1knbr/9/9/9/4a4/9/9/9/RNBQ1KNBR w 0";
110
4f3a0823
BA
111 let pieces = { w: new Array(8), b: new Array(8) };
112 for (let c of ["w", "b"]) {
113 if (c == 'b' && randomness == 1) {
114 pieces['b'] = pieces['w'];
115 break;
116 }
117
118 // Get random squares for every piece, totally freely
119 let positions = shuffle(ArrayFun.range(8));
120 const composition = ['b', 'b', 'r', 'r', 'n', 'n', 'k', 'q'];
5d74fcea
BA
121 // Fix bishops (on different colors)
122 const realOddity =
123 (pos) => { return (pos <= 3 ? pos % 2 : (pos + 1) % 2); };
124 const rem2 = realOddity(positions[0]);
125 if (rem2 == realOddity(positions[1])) {
4f3a0823 126 for (let i=2; i<8; i++) {
5d74fcea 127 if (realOddity(positions[i]) != rem2) {
4f3a0823 128 [positions[1], positions[i]] = [positions[i], positions[1]];
5d74fcea
BA
129 break;
130 }
4f3a0823
BA
131 }
132 }
133 for (let i = 0; i < 8; i++) pieces[c][positions[i]] = composition[i];
134 }
135 const piecesB = pieces["b"].join("") ;
136 const piecesW = pieces["w"].join("").toUpperCase();
137 return (
138 piecesB.substr(0, 4) + "1" + piecesB.substr(4) +
139 "/9/9/9/4a4/9/9/9/" +
140 piecesW.substr(0, 4) + "1" + piecesW.substr(4) +
141 " w 0"
142 );
143 }
144
145 tryKickFrom([x, y]) {
146 const bp = this.ballPos;
147 const emptySquare = (i, j) => {
148 return V.OnBoard(i, j) && this.board[i][j] == V.EMPTY;
149 };
150 // Kick the (adjacent) ball from x, y with current turn:
151 const step = [bp[0] - x, bp[1] - y];
152 const piece = this.getPiece(x, y);
153 let moves = [];
154 if (piece == V.KNIGHT) {
155 // The knight case is particular
156 V.steps[V.KNIGHT].forEach(s => {
157 const [i, j] = [bp[0] + s[0], bp[1] + s[1]];
158 if (
159 V.OnBoard(i, j) &&
160 this.board[i][j] == V.EMPTY &&
161 (
162 // In a corner? The, allow all ball moves
163 ([0, 8].includes(bp[0]) && [0, 8].includes(bp[1])) ||
164 // Do not end near the knight
165 (Math.abs(i - x) >= 2 || Math.abs(j - y) >= 2)
166 )
167 ) {
168 moves.push(super.getBasicMove(bp, [i, j]));
169 }
170 });
171 }
172 else {
173 let compatible = false,
174 oneStep = false;
175 switch (piece) {
176 case V.ROOK:
177 compatible = (step[0] == 0 || step[1] == 0);
178 break;
179 case V.BISHOP:
180 compatible = (step[0] != 0 && step[1] != 0);
181 break;
182 case V.QUEEN:
183 compatible = true;
184 break;
185 case V.KING:
186 compatible = true;
187 oneStep = true;
188 break;
189 }
190 if (!compatible) return [];
191 let [i, j] = [bp[0] + step[0], bp[1] + step[1]];
192 const horizontalStepOnGoalRow =
193 ([0, 8].includes(bp[0]) && step.some(s => s == 0));
194 if (emptySquare(i, j) && (!horizontalStepOnGoalRow || j != 4)) {
195 moves.push(super.getBasicMove(bp, [i, j]));
196 if (!oneStep) {
197 do {
198 i += step[0];
199 j += step[1];
200 if (!emptySquare(i, j)) break;
201 if (!horizontalStepOnGoalRow || j != 4)
202 moves.push(super.getBasicMove(bp, [i, j]));
203 } while (true);
204 }
205 }
206 }
207 const kickedFrom = x + "-" + y;
208 moves.forEach(m => m.by = kickedFrom)
107dc1bd
BA
209 return moves;
210 }
211
4f3a0823
BA
212 getPotentialMovesFrom([x, y], computer) {
213 if (V.PIECES.includes(this.getPiece(x, y))) {
214 if (this.subTurn > 1) return [];
215 return (
216 super.getPotentialMovesFrom([x, y])
217 .filter(m => m.end.y != 4 || ![0, 8].includes(m.end.x))
218 );
219 }
220 // Kicking the ball: look for adjacent pieces.
221 const steps = V.steps[V.ROOK].concat(V.steps[V.BISHOP]);
222 const c = this.turn;
223 let moves = [];
224 for (let s of steps) {
225 const [i, j] = [x + s[0], y + s[1]];
226 if (
227 V.OnBoard(i, j) &&
228 this.board[i][j] != V.EMPTY &&
229 this.getColor(i, j) == c
230 ) {
231 Array.prototype.push.apply(moves, this.tryKickFrom([i, j]));
232 }
233 }
234 // And, always add the "end" move. For computer, keep only one
235 outerLoop: for (let i=0; i < V.size.x; i++) {
236 for (let j=0; j < V.size.y; j++) {
237 if (this.board[i][j] != V.EMPTY && this.getColor(i, j) == c) {
238 moves.push(super.getBasicMove([x, y], [i, j]));
239 if (!!computer) break outerLoop;
240 }
241 }
242 }
243 return moves;
244 }
245
246 // No captures:
247 getSlideNJumpMoves([x, y], steps, oneStep) {
248 let moves = [];
249 outerLoop: for (let step of steps) {
250 let i = x + step[0];
251 let j = y + step[1];
252 let stepCount = 1;
253 while (V.OnBoard(i, j) && this.board[i][j] == V.EMPTY) {
254 moves.push(this.getBasicMove([x, y], [i, j]));
255 if (!!oneStep) continue outerLoop;
256 i += step[0];
257 j += step[1];
258 stepCount++;
259 }
260 }
261 return moves;
262 }
263
264 // Extra arg "computer" to avoid trimming all redundant pass moves:
265 getAllPotentialMoves(computer) {
266 const color = this.turn;
267 let potentialMoves = [];
268 for (let i = 0; i < V.size.x; i++) {
269 for (let j = 0; j < V.size.y; j++) {
270 if (this.board[i][j] != V.EMPTY && this.getColor(i, j) == color) {
271 Array.prototype.push.apply(
272 potentialMoves,
273 this.getPotentialMovesFrom([i, j], computer)
274 );
275 }
276 }
277 }
278 return potentialMoves;
279 }
280
281 getAllValidMoves() {
282 return this.filterValid(this.getAllPotentialMoves("computer"));
283 }
284
285 filterValid(moves) {
286 const L = this.kickedBy.length;
287 const kb = this.kickedBy[L-1];
288 return moves.filter(m => !m.by || !kb[m.by]);
289 }
290
107dc1bd
BA
291 getCheckSquares() {
292 return [];
293 }
294
4f3a0823
BA
295 allowAnotherPass(color) {
296 // Two cases: a piece moved, or the ball moved.
297 // In both cases, check our pieces and ball proximity,
298 // so the move played doesn't matter (if ball position updated)
299 const bp = this.ballPos;
300 const steps = V.steps[V.ROOK].concat(V.steps[V.BISHOP]);
301 for (let s of steps) {
302 const [i, j] = [this.ballPos[0] + s[0], this.ballPos[1] + s[1]];
303 if (
304 V.OnBoard(i, j) &&
305 this.board[i][j] != V.EMPTY &&
306 this.getColor(i, j) == color
307 ) {
308 return true; //potentially...
309 }
310 }
311 return false;
312 }
313
314 prePlay(move) {
315 if (move.appear[0].p == 'a')
316 this.ballPos = [move.appear[0].x, move.appear[0].y];
317 }
318
319 play(move) {
320 // Special message saying "passes are over"
321 const passesOver = (move.vanish.length == 2);
322 if (!passesOver) {
323 this.prePlay(move);
324 V.PlayOnBoard(this.board, move);
325 }
326 move.turn = [this.turn, this.subTurn]; //easier undo
327 if (passesOver || !this.allowAnotherPass(this.turn)) {
328 this.turn = V.GetOppCol(this.turn);
329 this.subTurn = 1;
330 this.movesCount++;
331 this.kickedBy.push( {} );
332 }
333 else {
334 this.subTurn++;
335 if (!!move.by) {
336 const L = this.kickedBy.length;
337 this.kickedBy[L-1][move.by] = true;
338 }
339 }
340 }
341
342 undo(move) {
343 const passesOver = (move.vanish.length == 2);
344 if (move.turn[0] != this.turn) {
345 [this.turn, this.subTurn] = move.turn;
346 this.movesCount--;
347 this.kickedBy.pop();
348 }
349 else {
350 this.subTurn--;
351 if (!!move.by) {
352 const L = this.kickedBy.length;
353 delete this.kickedBy[L-1][move.by];
354 }
355 }
356 if (!passesOver) {
357 V.UndoOnBoard(this.board, move);
358 this.postUndo(move);
359 }
360 }
361
362 postUndo(move) {
363 if (move.vanish[0].p == 'a')
364 this.ballPos = [move.vanish[0].x, move.vanish[0].y];
365 }
107dc1bd
BA
366
367 getCurrentScore() {
4f3a0823
BA
368 if (this.board[0][4] == V.BALL) return "1-0";
369 if (this.board[8][4] == V.BALL) return "0-1";
370 return "*";
107dc1bd 371 }
b9ce3d0f 372
4f3a0823
BA
373 getComputerMove() {
374 let initMoves = this.getAllValidMoves();
375 if (initMoves.length == 0) return null;
376 let moves = JSON.parse(JSON.stringify(initMoves));
377 let mvArray = [];
378 let mv = null;
379 // Just play random moves (for now at least. TODO?)
380 const c = this.turn;
381 while (moves.length > 0) {
382 mv = moves[randInt(moves.length)];
383 mvArray.push(mv);
384 this.play(mv);
385 if (mv.vanish.length == 1 && this.allowAnotherPass(c))
386 // Potential kick
387 moves = this.getPotentialMovesFrom(this.ballPos);
388 else break;
389 }
390 for (let i = mvArray.length - 1; i >= 0; i--) this.undo(mvArray[i]);
391 return (mvArray.length > 1 ? mvArray : mvArray[0]);
392 }
393
394 // NOTE: evalPosition() is wrong, but unused since bot plays at random
395
396 getNotation(move) {
397 if (move.vanish.length == 2) return "pass";
398 if (move.vanish[0].p != 'a') return super.getNotation(move);
399 // Kick: simple notation (TODO?)
400 return V.CoordsToSquare(move.end);
b9ce3d0f 401 }
7e8a7ea1 402
107dc1bd 403};