1db369199aee089aad9172e72f1fccb28f788a25
[vchess.git] / public / javascripts / variants / Ultima.js
1 class UltimaRules extends ChessRules
2 {
3 static getPpath(b)
4 {
5 if (b[1] == "m") //'m' for Immobilizer (I is too similar to 1)
6 return "Ultima/" + b;
7 return b; //usual piece
8 }
9
10 initVariables(fen)
11 {
12 this.kingPos = {'w':[-1,-1], 'b':[-1,-1]};
13 const fenParts = fen.split(" ");
14 const position = fenParts[0].split("/");
15 for (let i=0; i<position.length; i++)
16 {
17 let k = 0;
18 for (let j=0; j<position[i].length; j++)
19 {
20 switch (position[i].charAt(j))
21 {
22 case 'k':
23 this.kingPos['b'] = [i,k];
24 break;
25 case 'K':
26 this.kingPos['w'] = [i,k];
27 break;
28 default:
29 let num = parseInt(position[i].charAt(j));
30 if (!isNaN(num))
31 k += (num-1);
32 }
33 k++;
34 }
35 }
36 this.epSquares = []; //no en-passant here
37 }
38
39 setFlags(fen)
40 {
41 // TODO: for compatibility?
42 this.castleFlags = {"w":[false,false], "b":[false,false]};
43 }
44
45 static get IMMOBILIZER() { return 'm'; }
46 // Although other pieces keep their names here for coding simplicity,
47 // keep in mind that:
48 // - a "rook" is a coordinator, capturing by coordinating with the king
49 // - a "knight" is a long-leaper, capturing as in draughts
50 // - a "bishop" is a chameleon, capturing as its prey
51 // - a "queen" is a withdrawer, capturing by moving away from pieces
52
53 getPotentialMovesFrom([x,y])
54 {
55 // Pre-check: is thing on this square immobilized?
56 // In this case add potential suicide as a move "taking the immobilizer"
57 const piece = this.getPiece(x,y);
58 const color = this.getColor(x,y);
59 const oppCol = this.getOppCol(color);
60 const V = VariantRules;
61 const adjacentSteps = V.steps[V.ROOK].concat(V.steps[V.BISHOP]);
62 const [sizeX,sizeY] = V.size;
63 for (let step of adjacentSteps)
64 {
65 const [i,j] = [x+step[0],y+step[1]];
66 if (i>=0 && i<sizeX && j>=0 && j<sizeY && this.board[i][j] != V.EMPTY
67 && this.getColor(i,j) == oppCol)
68 {
69 const oppPiece = this.getPiece(i,j);
70 if (oppPiece == V.IMMOBILIZER
71 || (oppPiece == V.BISHOP && piece == V.IMMOBILIZER))
72 {
73 return [ new Move({
74 appear: [],
75 vanish: [new PiPo({x:x,y:y,p:piece,c:color})],
76 start: {x:x,y:y},
77 end: {x:i,y:j}
78 }) ];
79 }
80 }
81 }
82 switch (this.getPiece(x,y))
83 {
84 case VariantRules.IMMOBILIZER:
85 return this.getPotentialImmobilizerMoves([x,y]);
86 default:
87 return super.getPotentialMovesFrom([x,y]);
88 }
89 }
90
91 getSlideNJumpMoves([x,y], steps, oneStep)
92 {
93 const color = this.getColor(x,y);
94 const piece = this.getPiece(x,y);
95 let moves = [];
96 const [sizeX,sizeY] = VariantRules.size;
97 outerLoop:
98 for (let step of steps)
99 {
100 let i = x + step[0];
101 let j = y + step[1];
102 while (i>=0 && i<sizeX && j>=0 && j<sizeY
103 && this.board[i][j] == VariantRules.EMPTY)
104 {
105 moves.push(this.getBasicMove([x,y], [i,j]));
106 if (oneStep !== undefined)
107 continue outerLoop;
108 i += step[0];
109 j += step[1];
110 }
111 // Only king can take on occupied square:
112 if (piece==VariantRules.KING && i>=0 && i<sizeX && j>=0
113 && j<sizeY && this.canTake([x,y], [i,j]))
114 {
115 moves.push(this.getBasicMove([x,y], [i,j]));
116 }
117 }
118 return moves;
119 }
120
121 // Modify capturing moves among listed pawn moves
122 addPawnCaptures(moves, byChameleon)
123 {
124 const steps = VariantRules.steps[VariantRules.ROOK];
125 const [sizeX,sizeY] = VariantRules.size;
126 const color = this.turn;
127 const oppCol = this.getOppCol(color);
128 moves.forEach(m => {
129 if (!!byChameleon && m.start.x!=m.end.x && m.start.y!=m.end.y)
130 return; //chameleon not moving as pawn
131 // Try capturing in every direction
132 for (let step of steps)
133 {
134 const sq2 = [m.end.x+2*step[0],m.end.y+2*step[1]];
135 if (sq2[0]>=0 && sq2[0]<sizeX && sq2[1]>=0 && sq2[1]<sizeY
136 && this.board[sq2[0]][sq2[1]] != VariantRules.EMPTY
137 && this.getColor(sq2[0],sq2[1]) == color)
138 {
139 // Potential capture
140 const sq1 = [m.end.x+step[0],m.end.y+step[1]];
141 if (this.board[sq1[0]][sq1[1]] != VariantRules.EMPTY
142 && this.getColor(sq1[0],sq1[1]) == oppCol)
143 {
144 const piece1 = this.getPiece(sq1[0],sq1[1]);
145 if (!byChameleon || piece1 == VariantRules.PAWN)
146 {
147 m.vanish.push(new PiPo({
148 x:sq1[0],
149 y:sq1[1],
150 c:oppCol,
151 p:piece1
152 }));
153 }
154 }
155 }
156 }
157 });
158 }
159
160 // "Pincher"
161 getPotentialPawnMoves([x,y])
162 {
163 let moves = super.getPotentialRookMoves([x,y]);
164 this.addPawnCaptures(moves);
165 return moves;
166 }
167
168 addRookCaptures(moves, byChameleon)
169 {
170 const color = this.turn;
171 const oppCol = this.getOppCol(color);
172 const kp = this.kingPos[color];
173 moves.forEach(m => {
174 // Check piece-king rectangle (if any) corners for enemy pieces
175 if (m.end.x == kp[0] || m.end.y == kp[1])
176 return; //"flat rectangle"
177 const corner1 = [Math.max(m.end.x,kp[0]), Math.min(m.end.y,kp[1])];
178 const corner2 = [Math.min(m.end.x,kp[0]), Math.max(m.end.y,kp[1])];
179 for (let [i,j] of [corner1,corner2])
180 {
181 if (this.board[i][j] != VariantRules.EMPTY && this.getColor(i,j) == oppCol)
182 {
183 const piece = this.getPiece(i,j);
184 if (!byChameleon || piece == VariantRules.ROOK)
185 {
186 m.vanish.push( new PiPo({
187 x:i,
188 y:j,
189 p:piece,
190 c:oppCol
191 }) );
192 }
193 }
194 }
195 });
196 }
197
198 // Coordinator
199 getPotentialRookMoves(sq)
200 {
201 let moves = super.getPotentialQueenMoves(sq);
202 this.addRookCaptures(moves);
203 return moves;
204 }
205
206 // Long-leaper
207 getKnightCaptures(startSquare, byChameleon)
208 {
209 // Look in every direction for captures
210 const V = VariantRules;
211 const steps = V.steps[V.ROOK].concat(V.steps[V.BISHOP]);
212 const [sizeX,sizeY] = V.size;
213 const color = this.turn;
214 const oppCol = this.getOppCol(color);
215 let moves = [];
216 const [x,y] = [startSquare[0],startSquare[1]];
217 const piece = this.getPiece(x,y); //might be a chameleon!
218 outerLoop:
219 for (let step of steps)
220 {
221 let [i,j] = [x+step[0], y+step[1]];
222 while (i>=0 && i<sizeX && j>=0 && j<sizeY && this.board[i][j]==V.EMPTY)
223 {
224 i += step[0];
225 j += step[1];
226 }
227 if (i<0 || i>=sizeX || j<0 || j>=sizeY || this.getColor(i,j)==color
228 || (!!byChameleon && this.getPiece(i,j)!=V.KNIGHT))
229 {
230 continue;
231 }
232 // last(thing), cur(thing) : stop if "cur" is our color, or beyond board limits,
233 // or if "last" isn't empty and cur neither. Otherwise, if cur is empty then
234 // add move until cur square; if cur is occupied then stop if !!byChameleon and
235 // the square not occupied by a leaper.
236 let last = [i,j];
237 let cur = [i+step[0],j+step[1]];
238 let vanished = [ new PiPo({x:x,y:y,c:color,p:piece}) ];
239 while (cur[0]>=0 && cur[0]<sizeX && cur[1]>=0 && cur[1]<sizeY)
240 {
241 if (this.board[last[0]][last[1]] != V.EMPTY)
242 {
243 const oppPiece = this.getPiece(last[0],last[1]);
244 if (!!byChameleon && oppPiece != V.KNIGHT)
245 continue outerLoop;
246 // Something to eat:
247 vanished.push( new PiPo({x:last[0],y:last[1],c:oppCol,p:oppPiece}) );
248 }
249 if (this.board[cur[0]][cur[1]] != V.EMPTY)
250 {
251 if (this.getColor(cur[0],cur[1]) == color
252 || this.board[last[0]][last[1]] != V.EMPTY) //TODO: redundant test
253 {
254 continue outerLoop;
255 }
256 }
257 else
258 {
259 moves.push(new Move({
260 appear: [ new PiPo({x:cur[0],y:cur[1],c:color,p:piece}) ],
261 vanish: JSON.parse(JSON.stringify(vanished)), //TODO: required?
262 start: {x:x,y:y},
263 end: {x:cur[0],y:cur[1]}
264 }));
265 }
266 last = [last[0]+step[0],last[1]+step[1]];
267 cur = [cur[0]+step[0],cur[1]+step[1]];
268 }
269 }
270 return moves;
271 }
272
273 // Long-leaper
274 getPotentialKnightMoves(sq)
275 {
276 return super.getPotentialQueenMoves(sq).concat(this.getKnightCaptures(sq));
277 }
278
279 getPotentialBishopMoves([x,y])
280 {
281 let moves = super.getPotentialQueenMoves([x,y])
282 .concat(this.getKnightCaptures([x,y],"asChameleon"));
283 this.addPawnCaptures(moves, "asChameleon");
284 this.addRookCaptures(moves, "asChameleon");
285 this.addQueenCaptures(moves, "asChameleon");
286 // Add king capture if it's within range
287 const oppKp = this.kingPos[this.getOppCol(this.turn)];
288 if (Math.abs(x-oppKp[0]) <= 1 && Math.abs(y-oppKp[1]) <= 1)
289 moves.push(this.getBasicMove([x,y],oppKp));
290 // Post-processing: merge similar moves, concatenating vanish arrays
291 let mergedMoves = {};
292 const [sizeX,sizeY] = VariantRules.size;
293 moves.forEach(m => {
294 const key = m.end.x + sizeX * m.end.y;
295 if (!mergedMoves[key])
296 mergedMoves[key] = m;
297 else
298 {
299 for (let i=1; i<m.vanish.length; i++)
300 mergedMoves[key].vanish.push(m.vanish[i]);
301 }
302 });
303 // Finally return an array
304 moves = [];
305 Object.keys(mergedMoves).forEach(k => { moves.push(mergedMoves[k]); });
306 return moves;
307 }
308
309 // Withdrawer
310 addQueenCaptures(moves, byChameleon)
311 {
312 if (moves.length == 0)
313 return;
314 const [x,y] = [moves[0].start.x,moves[0].start.y];
315 const V = VariantRules;
316 const adjacentSteps = V.steps[V.ROOK].concat(V.steps[V.BISHOP]);
317 let capturingDirections = [];
318 const color = this.turn;
319 const oppCol = this.getOppCol(color);
320 const [sizeX,sizeY] = V.size;
321 adjacentSteps.forEach(step => {
322 const [i,j] = [x+step[0],y+step[1]];
323 if (i>=0 && i<sizeX && j>=0 && j<sizeY
324 && this.board[i][j] != V.EMPTY && this.getColor(i,j) == oppCol
325 && (!byChameleon || this.getPiece(i,j) == V.QUEEN))
326 {
327 capturingDirections.push(step);
328 }
329 });
330 moves.forEach(m => {
331 const step = [
332 m.end.x!=x ? (m.end.x-x)/Math.abs(m.end.x-x) : 0,
333 m.end.y!=y ? (m.end.y-y)/Math.abs(m.end.y-y) : 0
334 ];
335 // NOTE: includes() and even _.isEqual() functions fail...
336 // TODO: this test should be done only once per direction
337 if (capturingDirections.some(dir =>
338 { return (dir[0]==-step[0] && dir[1]==-step[1]); }))
339 {
340 const [i,j] = [x-step[0],y-step[1]];
341 m.vanish.push(new PiPo({
342 x:i,
343 y:j,
344 p:this.getPiece(i,j),
345 c:oppCol
346 }));
347 }
348 });
349 }
350
351 getPotentialQueenMoves(sq)
352 {
353 let moves = super.getPotentialQueenMoves(sq);
354 this.addQueenCaptures(moves);
355 return moves;
356 }
357
358 getPotentialImmobilizerMoves(sq)
359 {
360 // Immobilizer doesn't capture
361 return super.getPotentialQueenMoves(sq);
362 }
363
364 getPotentialKingMoves(sq)
365 {
366 const V = VariantRules;
367 return this.getSlideNJumpMoves(sq,
368 V.steps[V.ROOK].concat(V.steps[V.BISHOP]), "oneStep");
369 }
370
371 // TODO: verify this assertion
372 atLeastOneMove()
373 {
374 return true; //always at least one possible move
375 }
376
377 underCheck(move)
378 {
379 return false; //there is no check
380 }
381
382 getCheckSquares(move)
383 {
384 const c = this.getOppCol(this.turn); //opponent
385 const saveKingPos = this.kingPos[c]; //king might be taken
386 this.play(move);
387 // The only way to be "under check" is to have lost the king (thus game over)
388 let res = this.kingPos[c][0] < 0
389 ? [ JSON.parse(JSON.stringify(saveKingPos)) ]
390 : [ ];
391 this.undo(move);
392 return res;
393 }
394
395 updateVariables(move)
396 {
397 // Just update king(s) position(s)
398 const piece = this.getPiece(move.start.x,move.start.y);
399 const c = this.getColor(move.start.x,move.start.y);
400 if (piece == VariantRules.KING && move.appear.length > 0)
401 {
402 this.kingPos[c][0] = move.appear[0].x;
403 this.kingPos[c][1] = move.appear[0].y;
404 }
405 // Does this move takes opponent's king?
406 const oppCol = this.getOppCol(c);
407 for (let i=1; i<move.vanish.length; i++)
408 {
409 if (move.vanish[i].p == VariantRules.KING)
410 {
411 this.kingPos[oppCol] = [-1,-1];
412 break;
413 }
414 }
415 }
416
417 unupdateVariables(move)
418 {
419 super.unupdateVariables(move);
420 const c = this.getColor(move.start.x,move.start.y);
421 const oppCol = this.getOppCol(c);
422 if (this.kingPos[oppCol][0] < 0)
423 {
424 // Last move took opponent's king
425 for (let i=1; i<move.vanish.length; i++)
426 {
427 const psq = move.vanish[i];
428 if (psq.p == 'k')
429 {
430 this.kingPos[oppCol] = [psq.x, psq.y];
431 break;
432 }
433 }
434 }
435 }
436
437 checkGameOver()
438 {
439 if (this.checkRepetition())
440 return "1/2";
441
442 const color = this.turn;
443 // TODO: do we need "atLeastOneMove()"?
444 if (this.atLeastOneMove() && this.kingPos[color][0] >= 0)
445 return "*";
446
447 return this.checkGameEnd();
448 }
449
450 checkGameEnd()
451 {
452 // No valid move: our king disappeared
453 return this.turn == "w" ? "0-1" : "1-0";
454 }
455
456 static get VALUES() { //TODO: totally experimental!
457 return {
458 'p': 1,
459 'r': 2,
460 'n': 5,
461 'b': 3,
462 'q': 3,
463 'm': 5,
464 'k': 1000
465 };
466 }
467
468 static get SEARCH_DEPTH() { return 2; } //TODO?
469
470 static get THRESHOLD_MATE() {
471 return 500; //checkmates evals may be slightly below 1000
472 }
473
474 static GenRandInitFen()
475 {
476 let pieces = { "w": new Array(8), "b": new Array(8) };
477 // Shuffle pieces on first and last rank
478 for (let c of ["w","b"])
479 {
480 let positions = _.range(8);
481 // Get random squares for every piece, totally freely
482
483 let randIndex = _.random(7);
484 const bishop1Pos = positions[randIndex];
485 positions.splice(randIndex, 1);
486
487 randIndex = _.random(6);
488 const bishop2Pos = positions[randIndex];
489 positions.splice(randIndex, 1);
490
491 randIndex = _.random(5);
492 const knight1Pos = positions[randIndex];
493 positions.splice(randIndex, 1);
494
495 randIndex = _.random(4);
496 const knight2Pos = positions[randIndex];
497 positions.splice(randIndex, 1);
498
499 randIndex = _.random(3);
500 const queenPos = positions[randIndex];
501 positions.splice(randIndex, 1);
502
503 randIndex = _.random(2);
504 const kingPos = positions[randIndex];
505 positions.splice(randIndex, 1);
506
507 randIndex = _.random(1);
508 const rookPos = positions[randIndex];
509 positions.splice(randIndex, 1);
510 const immobilizerPos = positions[0];
511
512 pieces[c][bishop1Pos] = 'b';
513 pieces[c][bishop2Pos] = 'b';
514 pieces[c][knight1Pos] = 'n';
515 pieces[c][knight2Pos] = 'n';
516 pieces[c][queenPos] = 'q';
517 pieces[c][kingPos] = 'k';
518 pieces[c][rookPos] = 'r';
519 pieces[c][immobilizerPos] = 'm';
520 }
521 return pieces["b"].join("") +
522 "/pppppppp/8/8/8/8/PPPPPPPP/" +
523 pieces["w"].join("").toUpperCase() +
524 " 0000"; //TODO: flags?!
525 }
526
527 getFlagsFen()
528 {
529 return "0000"; //TODO: or "-" ?
530 }
531
532 getNotation(move)
533 {
534 if (move.appear.length == 0)
535 {
536 const startSquare =
537 String.fromCharCode(97 + move.start.y) + (VariantRules.size[0]-move.start.x);
538 return "^" + startSquare; //suicide
539 }
540 return super.getNotation(move);
541 }
542 }