New variant idea
[xogo.git] / utils / setupPieces.js
CommitLineData
f3824309
BA
1import {Random} from "/utils/alea.js";
2
0cef7bb4 3export const FenUtil = {
f3824309
BA
4
5 // arg o (constraints): "between" with p1 and p2.
6 // "flags", "diffCol": array of pieceType
0cef7bb4 7 setupRow: function(arr, o) {
7c038235 8 let res = JSON.parse(JSON.stringify(arr));
f3824309
BA
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 }
10c9010b
BA
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;
0adfbdb5 37 }
10c9010b
BA
38 });
39 }
40 if (o.between) {
52718c94
BA
41 o.between.forEach(b => {
42 // Locate p1. If appearing first, exchange with first p2.
43 // If appearing last, exchange with last p2.
44 const p1 = res.indexOf(b["p1"]);
45 const firstP2 = res.indexOf(b["p2"]),
46 lastP2 = res.lastIndexOf(b["p2"]);
47 if (p1 < firstP2 || p1 > lastP2) {
48 res[p1] = b["p2"];
49 if (p1 < firstP2)
50 res[firstP2] = b["p1"];
51 else //p1 > lastP2
52 res[lastP2] = b["p1"];
53 }
3ca47832 54 });
0adfbdb5 55 }
f3824309 56 }
f3824309 57 return {fen: res, flags: flags};
0cef7bb4 58 },
f3824309 59
0cef7bb4 60 setupPieces: function(arr, o) {
0adfbdb5
BA
61 const row1 = FenUtil.setupRow(arr, o);
62 const row2 = o.randomness == 2 ? FenUtil.setupRow(arr, o) : row1;
f3824309 63 return {
7c038235 64 w: row1.fen,
0adfbdb5
BA
65 b: row2.fen,
66 flags: row1.flags + row2.flags
67 };
f3824309 68 }
7c038235 69
f3824309 70};