Fix FenUtil
[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 }
0adfbdb5
BA
18 if (o.diffCol) {
19 o.diffCol.forEach(p => {
20 // Pieces of type p on different colors:
21 const firstP = res.indexOf(p),
22 lastP = res.lastIndexOf(p);
23 if ((firstP - lastP) % 2 != 0) {
24 const choice1 = Random.randBool() ? firstP : lastP;
25 let choice2;
26 do {
27 choice2 = Random.randInt(arr.length);
28 }
29 while (
30 choice2 == choice1 ||
31 o.diffCol.includes(choice2) ||
32 (choice2 - choice1) % 2 != 0
33 );
34 res[choice1] = res[choice2];
35 res[choice2] = p;
36 }
37 });
38 }
f3824309
BA
39 if (o.between) {
40 // Locate p1. If appearing first, exchange with first p2.
41 // If appearing last, exchange with last p2.
0adfbdb5
BA
42 const p1 = res.indexOf(o.between["p1"]);
43 const firstP2 = res.indexOf(o.between["p2"]),
44 lastP2 = res.lastIndexOf(o.between["p2"]);
45 if (p1 < firstP2 || p1 > lastP2) {
46 res[p1] = o.between["p2"];
47 if (p1 < firstP2)
48 res[firstP2] = o.between["p1"];
49 else //p1 > lastP2
50 res[lastP2] = o.between["p1"];
51 }
f3824309 52 }
f3824309 53 return {fen: res, flags: flags};
0cef7bb4 54 },
f3824309 55
0cef7bb4 56 setupPieces: function(arr, o) {
0adfbdb5
BA
57 const row1 = FenUtil.setupRow(arr, o);
58 const row2 = o.randomness == 2 ? FenUtil.setupRow(arr, o) : row1;
f3824309 59 return {
7c038235 60 w: row1.fen,
0adfbdb5
BA
61 b: row2.fen,
62 flags: row1.flags + row2.flags
63 };
f3824309 64 }
7c038235 65
f3824309 66};