Fix FenUtil.setupPieces and Antiking variants
[xogo.git] / utils / setupPieces.js
1 import {Random} from "/utils/alea.js";
2
3 export const FenUtil = {
4
5 // arg o (constraints): "between" with p1 and p2.
6 // "flags", "diffCol": array of pieceType
7 setupRow: function(arr, o) {
8 let res = JSON.parse(JSON.stringify(arr));
9 if (o.randomness >= 1)
10 res = Random.shuffle(arr);
11 let flags = "";
12 if (o.flags) {
13 res.forEach((p, i) => {
14 if (o.flags.includes(p))
15 flags += i;
16 });
17 }
18 if (o.randomness >= 1) {
19 if (o.diffCol) {
20 o.diffCol.forEach(p => {
21 // Pieces of type p on different colors:
22 const firstP = res.indexOf(p),
23 lastP = res.lastIndexOf(p);
24 if ((firstP - lastP) % 2 != 0) {
25 const choice1 = Random.randBool() ? firstP : lastP;
26 let choice2;
27 do {
28 choice2 = Random.randInt(arr.length);
29 }
30 while (
31 choice2 == choice1 ||
32 o.diffCol.includes(choice2) ||
33 (choice2 - choice1) % 2 != 0
34 );
35 res[choice1] = res[choice2];
36 res[choice2] = p;
37 }
38 });
39 }
40 if (o.between) {
41 // Locate p1. If appearing first, exchange with first p2.
42 // If appearing last, exchange with last p2.
43 const p1 = res.indexOf(o.between["p1"]);
44 const firstP2 = res.indexOf(o.between["p2"]),
45 lastP2 = res.lastIndexOf(o.between["p2"]);
46 if (p1 < firstP2 || p1 > lastP2) {
47 res[p1] = o.between["p2"];
48 if (p1 < firstP2)
49 res[firstP2] = o.between["p1"];
50 else //p1 > lastP2
51 res[lastP2] = o.between["p1"];
52 }
53 }
54 }
55 return {fen: res, flags: flags};
56 },
57
58 setupPieces: function(arr, o) {
59 const row1 = FenUtil.setupRow(arr, o);
60 const row2 = o.randomness == 2 ? FenUtil.setupRow(arr, o) : row1;
61 return {
62 w: row1.fen,
63 b: row2.fen,
64 flags: row1.flags + row2.flags
65 };
66 }
67
68 };