59e44b1ec9365956e1acca259820f235346d5eb1
[xogo.git] / variants / Chakart / class.js
1 import ChessRules from "/base_rules.js";
2 import GiveawayRules from "/variants/Giveaway/class.js";
3 import { ArrayFun } from "/utils/array.js";
4 import { Random } from "/utils/alea.js";
5 import PiPo from "/utils/PiPo.js";
6 import Move from "/utils/Move.js";
7
8 export default class ChakartRules extends ChessRules {
9
10 static get Options() {
11 return {
12 select: [
13 {
14 label: "Randomness",
15 variable: "randomness",
16 defaut: 2,
17 options: [
18 {label: "Deterministic", value: 0},
19 {label: "Symmetric random", value: 1},
20 {label: "Asymmetric random", value: 2}
21 ]
22 }
23 ],
24 styles: ["cylinder"]
25 };
26 }
27
28 get pawnPromotions() {
29 return ['q', 'r', 'n', 'b', 'k'];
30 }
31
32 get hasCastle() {
33 return false;
34 }
35 get hasEnpassant() {
36 return false;
37 }
38 get hasReserve() {
39 return true;
40 }
41 get hasReserveFen() {
42 return false;
43 }
44
45 static get IMMOBILIZE_CODE() {
46 return {
47 'p': 's',
48 'r': 'u',
49 'n': 'o',
50 'b': 'c',
51 'q': 't',
52 'k': 'l'
53 };
54 }
55
56 static get IMMOBILIZE_DECODE() {
57 return {
58 's': 'p',
59 'u': 'r',
60 'o': 'n',
61 'c': 'b',
62 't': 'q',
63 'l': 'k'
64 };
65 }
66
67 // Fictive color 'a', bomb banana mushroom egg
68 static get BOMB() {
69 return 'w'; //"Wario"
70 }
71 static get BANANA() {
72 return 'd'; //"Donkey"
73 }
74 static get EGG() {
75 return 'e';
76 }
77 static get MUSHROOM() {
78 return 'm';
79 }
80
81 static get EGG_SURPRISE() {
82 return [
83 "kingboo", "bowser", "daisy", "koopa",
84 "luigi", "waluigi", "toadette", "chomp"];
85 }
86
87 canIplay(x, y) {
88 if (
89 this.playerColor != this.turn ||
90 Object.keys(V.IMMOBILIZE_DECODE).includes(this.getPiece(x, y))
91 ) {
92 return false;
93 }
94 return this.egg == "kingboo" || this.getColor(x, y) == this.turn;
95 }
96
97 pieces(color, x, y) {
98 const specials = {
99 'i': {"class": "invisible"}, //queen
100 '?': {"class": "mystery"}, //...initial square
101 'e': {"class": "egg"},
102 'm': {"class": "mushroom"},
103 'd': {"class": "banana"},
104 'w': {"class": "bomb"},
105 'z': {"class": "remote-capture"}
106 };
107 const bowsered = {
108 's': {"class": ["immobilized", "pawn"]},
109 'u': {"class": ["immobilized", "rook"]},
110 'o': {"class": ["immobilized", "knight"]},
111 'c': {"class": ["immobilized", "bishop"]},
112 't': {"class": ["immobilized", "queen"]},
113 'l': {"class": ["immobilized", "king"]}
114 };
115 return Object.assign(
116 {
117 'y': {
118 // Virtual piece for "king remote shell captures"
119 moves: [],
120 attack: [
121 {
122 steps: [
123 [0, 1], [0, -1], [1, 0], [-1, 0],
124 [1, 1], [1, -1], [-1, 1], [-1, -1]
125 ]
126 }
127 ]
128 }
129 },
130 specials, bowsered, super.pieces(color, x, y));
131 }
132
133 genRandInitFen(seed) {
134 const options = Object.assign({mode: "suicide"}, this.options);
135 const gr = new GiveawayRules({options: options, genFenOnly: true});
136 const baseFen = gr.genRandInitFen(seed);
137 const fenParts = baseFen.split(" ");
138 let others = JSON.parse(fenParts[3]);
139 delete others["enpassant"];
140 others["flags"] = "1111"; //Peach + Mario flags
141 return fenParts.slice(0, 3).join(" ") + " " + JSON.stringify(others);
142 }
143
144 fen2board(f) {
145 return (
146 f.charCodeAt() <= 90
147 ? "w" + f.toLowerCase()
148 : (['w', 'd', 'e', 'm'].includes(f) ? "a" : "b") + f
149 );
150 }
151
152 setFlags(fenflags) {
153 // King can send shell? Queen can be invisible?
154 this.powerFlags = {
155 w: {k: false, q: false},
156 b: {k: false, q: false}
157 };
158 for (let c of ['w', 'b']) {
159 for (let p of ['k', 'q']) {
160 this.powerFlags[c][p] =
161 fenflags.charAt((c == "w" ? 0 : 2) + (p == 'k' ? 0 : 1)) == "1";
162 }
163 }
164 }
165
166 aggregateFlags() {
167 return this.powerFlags;
168 }
169
170 disaggregateFlags(flags) {
171 this.powerFlags = flags;
172 }
173
174 getFlagsFen() {
175 return ['w', 'b'].map(c => {
176 return ['k', 'q'].map(p => this.powerFlags[c][p] ? "1" : "0").join("");
177 }).join("");
178 }
179
180 setOtherVariables(fenParsed) {
181 super.setOtherVariables(fenParsed);
182 this.egg = null;
183 // Change seed (after FEN generation!!)
184 // so that further calls differ between players:
185 Random.setSeed(Math.floor(19840 * Math.random()));
186 }
187
188 initReserves() {
189 this.reserve = {}; //to be filled later
190 }
191
192 canStepOver(i, j) {
193 return (
194 this.board[i][j] == "" ||
195 ['i', V.EGG, V.MUSHROOM].includes(this.getPiece(i, j))
196 );
197 }
198
199 // For Toadette bonus
200 canDrop([c, p], [i, j]) {
201 return (
202 (
203 this.board[i][j] == "" ||
204 this.getColor(i, j) == 'a' ||
205 this.getPiece(i, j) == 'i'
206 )
207 &&
208 (p != "p" || (c == 'w' && i < this.size.x - 1) || (c == 'b' && i > 0))
209 );
210 }
211
212 getPotentialMovesFrom([x, y]) {
213 let moves = [];
214 const piece = this.getPiece(x, y);
215 if (this.egg == "toadette")
216 moves = this.getDropMovesFrom([x, y]);
217 else if (this.egg == "kingboo") {
218 const color = this.turn;
219 const oppCol = C.GetOppCol(color);
220 // Only allow to swap (non-immobilized!) pieces
221 for (let i=0; i<this.size.x; i++) {
222 for (let j=0; j<this.size.y; j++) {
223 const colIJ = this.getColor(i, j);
224 const pieceIJ = this.getPiece(i, j);
225 if (
226 (i != x || j != y) &&
227 ['w', 'b'].includes(colIJ) &&
228 !Object.keys(V.IMMOBILIZE_DECODE).includes(pieceIJ) &&
229 // Next conditions = no pawn on last rank
230 (
231 piece != 'p' ||
232 (
233 (color != 'w' || i != 0) &&
234 (color != 'b' || i != this.size.x - 1)
235 )
236 )
237 &&
238 (
239 pieceIJ != 'p' ||
240 (
241 (colIJ != 'w' || x != 0) &&
242 (colIJ != 'b' || x != this.size.x - 1)
243 )
244 )
245 ) {
246 let m = this.getBasicMove([x, y], [i, j]);
247 m.appear.push(new PiPo({x: x, y: y, p: pieceIJ, c: colIJ}));
248 m.kingboo = true; //avoid some side effects (bananas/bombs)
249 moves.push(m);
250 }
251 }
252 }
253 }
254 else {
255 // Normal case (including bonus daisy)
256 switch (piece) {
257 case 'p':
258 moves = this.getPawnMovesFrom([x, y]); //apply promotions
259 break;
260 case 'q':
261 moves = this.getQueenMovesFrom([x, y]);
262 break;
263 case 'k':
264 moves = this.getKingMovesFrom([x, y]);
265 break;
266 case 'n':
267 moves = this.getKnightMovesFrom([x, y]);
268 break;
269 case 'b':
270 case 'r':
271 // Explicitely listing types to avoid moving immobilized piece
272 moves = this.getPotentialMovesOf(piece, [x, y]);
273 break;
274 }
275 }
276 return moves;
277 }
278
279 getPawnMovesFrom([x, y]) {
280 const color = this.turn;
281 const oppCol = C.GetOppCol(color);
282 const shiftX = (color == 'w' ? -1 : 1);
283 const firstRank = (color == "w" ? this.size.x - 1 : 0);
284 let moves = [];
285 const frontPiece = this.getPiece(x + shiftX, y);
286 if (
287 this.board[x + shiftX][y] == "" ||
288 this.getColor(x + shiftX, y) == 'a' ||
289 frontPiece == 'i'
290 ) {
291 moves.push(this.getBasicMove([x, y], [x + shiftX, y]));
292 if (
293 [firstRank, firstRank + shiftX].includes(x) &&
294 ![V.BANANA, V.BOMB].includes(frontPiece) &&
295 (
296 this.board[x + 2 * shiftX][y] == "" ||
297 this.getColor(x + 2 * shiftX, y) == 'a' ||
298 this.getPiece(x + 2 * shiftX, y) == 'i'
299 )
300 ) {
301 moves.push(this.getBasicMove([x, y], [x + 2 * shiftX, y]));
302 }
303 }
304 for (let shiftY of [-1, 1]) {
305 const nextY = this.getY(y + shiftY);
306 if (
307 nextY >= 0 &&
308 nextY < this.size.y &&
309 this.board[x + shiftX][nextY] != "" &&
310 // Pawns cannot capture invisible queen this way!
311 this.getPiece(x + shiftX, nextY) != 'i' &&
312 ['a', oppCol].includes(this.getColor(x + shiftX, nextY))
313 ) {
314 moves.push(this.getBasicMove([x, y], [x + shiftX, nextY]));
315 }
316 }
317 this.pawnPostProcess(moves, color, oppCol);
318 // Add mushroom on before-last square (+ potential segments)
319 moves.forEach(m => {
320 let [mx, my] = [x, y];
321 if (Math.abs(m.end.x - m.start.x) == 2)
322 mx = (m.start.x + m.end.x) / 2;
323 m.appear.push(new PiPo({x: mx, y: my, c: 'a', p: 'm'}));
324 if (mx != x && this.board[mx][my] != "") {
325 m.vanish.push(new PiPo({
326 x: mx,
327 y: my,
328 c: this.getColor(mx, my),
329 p: this.getPiece(mx, my)
330 }));
331 }
332 if (Math.abs(m.end.y - m.start.y) > 1) {
333 m.segments = [
334 [[x, y], [x, y]],
335 [[m.end.x, m.end.y], [m.end.x, m.end.y]]
336 ];
337 }
338 });
339 return moves;
340 }
341
342 getKnightMovesFrom([x, y]) {
343 // Add egg on initial square:
344 return this.getPotentialMovesOf('n', [x, y]).map(m => {
345 m.appear.push(new PiPo({p: "e", c: "a", x: x, y: y}));
346 return m;
347 });
348 }
349
350 getQueenMovesFrom(sq) {
351 const normalMoves = this.getPotentialMovesOf('q', sq);
352 // If flag allows it, add 'invisible movements'
353 let invisibleMoves = [];
354 if (this.powerFlags[this.turn]['q']) {
355 normalMoves.forEach(m => {
356 if (
357 m.appear.length == 1 &&
358 m.vanish.length == 1 &&
359 // Only simple non-capturing moves:
360 m.vanish[0].c != 'a'
361 ) {
362 let im = JSON.parse(JSON.stringify(m));
363 im.appear[0].p = 'i';
364 im.noAnimate = true;
365 invisibleMoves.push(im);
366 }
367 });
368 }
369 return normalMoves.concat(invisibleMoves);
370 }
371
372 getKingMovesFrom([x, y]) {
373 let moves = this.getPotentialMovesOf('k', [x, y]);
374 // If flag allows it, add 'remote shell captures'
375 if (this.powerFlags[this.turn]['k']) {
376 let shellCaptures = this.getPotentialMovesOf('y', [x, y]);
377 shellCaptures.forEach(sc => {
378 sc.shell = true; //easier play()
379 sc.choice = 'z'; //to display in showChoices()
380 // Fix move (Rifle style):
381 sc.vanish.shift();
382 sc.appear.shift();
383 });
384 Array.prototype.push.apply(moves, shellCaptures);
385 }
386 return moves;
387 }
388
389 play(move) {
390 const color = this.turn;
391 const oppCol = C.GetOppCol(color);
392 if (
393 move.appear.length > 0 &&
394 move.appear[0].p == 'p' &&
395 (
396 (color == 'w' && move.end.x == 0) ||
397 (color == 'b' && move.end.x == this.size.x - 1)
398 )
399 ) {
400 // "Forgotten" promotion, which occurred after some effect
401 let moves = [move];
402 super.pawnPostProcess(moves, color, oppCol);
403 super.showChoices(moves);
404 return false;
405 }
406 this.postPlay(move, color, oppCol);
407 return true;
408 }
409
410 postPlay(move, color, oppCol) {
411 this.egg = move.egg;
412 if (move.egg == "toadette") {
413 this.reserve = { w: {}, b: {} };
414 // Randomly select a piece in pawnPromotions
415 if (!move.toadette)
416 move.toadette = Random.sample(this.pawnPromotions);
417 this.reserve[color][move.toadette] = 1;
418 this.re_drawReserve([color]);
419 }
420 else if (Object.keys(this.reserve).length > 0) {
421 this.reserve = {};
422 this.re_drawReserve([color]);
423 }
424 if (move.shell)
425 this.powerFlags[color]['k'] = false;
426 else if (move.appear.length > 0 && move.appear[0].p == 'i') {
427 this.powerFlags[move.appear[0].c]['q'] = false;
428 if (color == this.playerColor) {
429 move.appear.push(
430 new PiPo({x: move.start.x, y: move.start.y, c: color, p: '?'}));
431 }
432 }
433 if (color == this.playerColor) {
434 // Look for an immobilized piece of my color: it can now move
435 for (let i=0; i<8; i++) {
436 for (let j=0; j<8; j++) {
437 if ((i != move.end.x || j != move.end.y) && this.board[i][j] != "") {
438 const piece = this.getPiece(i, j);
439 if (
440 this.getColor(i, j) == color &&
441 Object.keys(V.IMMOBILIZE_DECODE).includes(piece)
442 ) {
443 move.vanish.push(new PiPo({
444 x: i, y: j, c: color, p: piece
445 }));
446 move.appear.push(new PiPo({
447 x: i, y: j, c: color, p: V.IMMOBILIZE_DECODE[piece]
448 }));
449 }
450 }
451 }
452 }
453 // Also make opponent invisible queen visible again, if any
454 for (let i=0; i<8; i++) {
455 for (let j=0; j<8; j++) {
456 if (
457 this.board[i][j] != "" &&
458 this.getColor(i, j) == oppCol
459 ) {
460 const pieceIJ = this.getPiece(i, j);
461 if (pieceIJ == 'i') {
462 move.vanish.push(new PiPo({x: i, y: j, c: oppCol, p: 'i'}));
463 move.appear.push(new PiPo({x: i, y: j, c: oppCol, p: 'q'}));
464 }
465 else if (pieceIJ == '?')
466 move.vanish.push(new PiPo({x: i, y: j, c: oppCol, p: '?'}));
467 }
468 }
469 }
470 }
471 this.playOnBoard(move);
472 super.postPlay(move);
473 }
474
475 playVisual(move, r) {
476 super.playVisual(move, r);
477 if (move.egg)
478 this.displayBonus(move);
479 }
480
481 computeNextMove(move) {
482 // Set potential random effects, so that play() is deterministic
483 // from opponent viewpoint:
484 const endPiece = this.getPiece(move.end.x, move.end.y);
485 switch (endPiece) {
486 case V.EGG:
487 move.egg = Random.sample(V.EGG_SURPRISE);
488 move.next = this.getEggEffect(move);
489 break;
490 case V.MUSHROOM:
491 move.next = this.getMushroomEffect(move);
492 break;
493 case V.BANANA:
494 case V.BOMB:
495 move.next = this.getBombBananaEffect(move, endPiece);
496 break;
497 }
498 // NOTE: Chakart has also some side-effects:
499 if (
500 !move.next && move.appear.length > 0 &&
501 !move.kingboo && !move.luigiEffect
502 ) {
503 const movingPiece = move.appear[0].p;
504 if (['b', 'r'].includes(movingPiece)) {
505 // Drop a banana or bomb:
506 const bs =
507 this.getRandomSquare([move.end.x, move.end.y],
508 movingPiece == 'r'
509 ? [[1, 1], [1, -1], [-1, 1], [-1, -1]]
510 : [[1, 0], [-1, 0], [0, 1], [0, -1]],
511 "freeSquare");
512 if (bs) {
513 move.appear.push(
514 new PiPo({
515 x: bs[0],
516 y: bs[1],
517 c: 'a',
518 p: movingPiece == 'r' ? 'd' : 'w'
519 })
520 );
521 if (this.board[bs[0]][bs[1]] != "") {
522 move.vanish.push(
523 new PiPo({
524 x: bs[0],
525 y: bs[1],
526 c: this.getColor(bs[0], bs[1]),
527 p: this.getPiece(bs[0], bs[1])
528 })
529 );
530 }
531 }
532 }
533 }
534 }
535
536 isLastMove(move) {
537 return !move.next && !["daisy", "toadette", "kingboo"].includes(move.egg);
538 }
539
540 // Helper to set and apply banana/bomb effect
541 getRandomSquare([x, y], steps, freeSquare) {
542 let validSteps = steps.filter(s => this.onBoard(x + s[0], y + s[1]));
543 if (freeSquare) {
544 // Square to put banana/bomb cannot be occupied by a piece
545 validSteps = validSteps.filter(s => {
546 return ["", 'a'].includes(this.getColor(x + s[0], y + s[1]))
547 });
548 }
549 if (validSteps.length == 0)
550 return null;
551 const step = validSteps[Random.randInt(validSteps.length)];
552 return [x + step[0], y + step[1]];
553 }
554
555 getEggEffect(move) {
556 const getRandomPiece = (c) => {
557 let bagOfPieces = [];
558 for (let i=0; i<this.size.x; i++) {
559 for (let j=0; j<this.size.y; j++) {
560 if (this.getColor(i, j) == c && this.getPiece(i, j) != 'k')
561 bagOfPieces.push([i, j]);
562 }
563 }
564 if (bagOfPieces.length >= 1)
565 return Random.sample(bagOfPieces);
566 return null;
567 };
568 const color = this.turn;
569 let em = null;
570 switch (move.egg) {
571 case "luigi":
572 case "waluigi":
573 // Change color of friendly or enemy piece, king excepted
574 const oldColor = (move.egg == "waluigi" ? color : C.GetOppCol(color));
575 const newColor = C.GetOppCol(oldColor);
576 const coords = getRandomPiece(oldColor);
577 if (coords) {
578 const piece = this.getPiece(coords[0], coords[1]);
579 em = new Move({
580 appear: [
581 new PiPo({x: coords[0], y: coords[1], c: newColor, p: piece})
582 ],
583 vanish: [
584 new PiPo({x: coords[0], y: coords[1], c: oldColor, p: piece})
585 ]
586 });
587 em.luigiEffect = true; //avoid dropping bomb/banana by mistake
588 }
589 break;
590 case "bowser":
591 em = new Move({
592 appear: [
593 new PiPo({
594 x: move.end.x,
595 y: move.end.y,
596 c: color,
597 p: V.IMMOBILIZE_CODE[move.appear[0].p]
598 })
599 ],
600 vanish: [
601 new PiPo({
602 x: move.end.x,
603 y: move.end.y,
604 c: color,
605 p: move.appear[0].p
606 })
607 ]
608 });
609 break;
610 case "koopa":
611 // Reverse move
612 em = new Move({
613 appear: [
614 new PiPo({
615 x: move.start.x, y: move.start.y, c: color, p: move.appear[0].p
616 })
617 ],
618 vanish: [
619 new PiPo({
620 x: move.end.x, y: move.end.y, c: color, p: move.appear[0].p
621 })
622 ]
623 });
624 if (this.board[move.start.x][move.start.y] != "") {
625 // Pawn or knight let something on init square
626 em.vanish.push(new PiPo({
627 x: move.start.x,
628 y: move.start.y,
629 c: 'a',
630 p: this.getPiece(move.start.x, move.start.y)
631 }));
632 }
633 break;
634 case "chomp":
635 // Eat piece
636 em = new Move({
637 appear: [],
638 vanish: [
639 new PiPo({
640 x: move.end.x, y: move.end.y, c: color, p: move.appear[0].p
641 })
642 ],
643 end: {x: move.end.x, y: move.end.y}
644 });
645 break;
646 }
647 if (em && move.egg != "koopa")
648 em.noAnimate = true; //static move
649 return em;
650 }
651
652 getMushroomEffect(move) {
653 if (
654 typeof move.start.x == "string" || //drop move (toadette)
655 ['b', 'r', 'q'].includes(move.vanish[0].p) //slider
656 ) {
657 return null;
658 }
659 let step = [move.end.x - move.start.x, move.end.y - move.start.y];
660 if (Math.abs(step[0]) == 2 && Math.abs(step[1]) == 0)
661 // Pawn initial 2-squares move: normalize step
662 step[0] /= 2;
663 const nextSquare = [move.end.x + step[0], move.end.y + step[1]];
664 let nextMove = null;
665 if (
666 this.onBoard(nextSquare[0], nextSquare[1]) &&
667 (
668 this.board[nextSquare[0]][nextSquare[1]] == "" ||
669 this.getColor(nextSquare[0], nextSquare[1]) == 'a'
670 )
671 ) {
672 this.playOnBoard(move); //HACK for getBasicMove()
673 nextMove = this.getBasicMove([move.end.x, move.end.y], nextSquare);
674 this.undoOnBoard(move);
675 }
676 return nextMove;
677 }
678
679 getBombBananaEffect(move, item) {
680 const steps = item == V.BANANA
681 ? [[1, 0], [-1, 0], [0, 1], [0, -1]]
682 : [[1, 1], [1, -1], [-1, 1], [-1, -1]];
683 const nextSquare = this.getRandomSquare([move.end.x, move.end.y], steps);
684 this.playOnBoard(move); //HACK for getBasicMove()
685 const res = this.getBasicMove([move.end.x, move.end.y], nextSquare);
686 this.undoOnBoard(move);
687 return res;
688 }
689
690 displayBonus(move) {
691 let divBonus = document.createElement("div");
692 divBonus.classList.add("bonus-text");
693 divBonus.innerHTML = move.egg;
694 let container = document.getElementById(this.containerId);
695 container.appendChild(divBonus);
696 setTimeout(() => container.removeChild(divBonus), 2000);
697 }
698
699 atLeastOneMove() {
700 return true;
701 }
702
703 filterValid(moves) {
704 return moves;
705 }
706
707 // Kingboo bonus can be animated better:
708 customAnimate(move, segments, cb) {
709 if (!move.kingboo)
710 return 0;
711 super.animateMoving(move.end, move.start, null,
712 segments.reverse().map(s => s.reverse()), cb);
713 return 1;
714 }
715
716 };