1 import {Random
} from "/utils/alea.js";
3 export class Fenutil
= {
5 // arg o (constraints): "between" with p1 and p2.
6 // "flags", "diffCol": array of pieceType
10 res
= Random
.shuffle(arr
);
13 res
.forEach((p
, i
) => {
14 if (o
.flags
.includes(p
))
19 // Locate p1. If appearing first, exchange with first p2.
20 // If appearing last, exchange with last p2.
21 res
.findIndex(p
=> p
== o
.between
["p1"])
24 return {fen: res
, flags: flags
};
28 if (o
.randomness
== 0)
39 let fen
, flags
= "0707";
40 if (!this.options
.randomness
)
42 fen
= "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR";
46 let pieces
= {w: new Array(8), b: new Array(8)};
48 // Shuffle pieces on first (and last rank if randomness == 2)
49 for (let c
of ["w", "b"]) {
50 if (c
== 'b' && this.options
.randomness
== 1) {
51 pieces
['b'] = pieces
['w'];
55 let positions
= ArrayFun
.range(8);
56 // Get random squares for bishops
57 let randIndex
= 2 * Random
.randInt(4);
58 const bishop1Pos
= positions
[randIndex
];
59 // The second bishop must be on a square of different color
60 let randIndex_tmp
= 2 * Random
.randInt(4) + 1;
61 const bishop2Pos
= positions
[randIndex_tmp
];
62 // Remove chosen squares
63 positions
.splice(Math
.max(randIndex
, randIndex_tmp
), 1);
64 positions
.splice(Math
.min(randIndex
, randIndex_tmp
), 1);
65 // Get random squares for knights
66 randIndex
= Random
.randInt(6);
67 const knight1Pos
= positions
[randIndex
];
68 positions
.splice(randIndex
, 1);
69 randIndex
= Random
.randInt(5);
70 const knight2Pos
= positions
[randIndex
];
71 positions
.splice(randIndex
, 1);
72 // Get random square for queen
73 randIndex
= Random
.randInt(4);
74 const queenPos
= positions
[randIndex
];
75 positions
.splice(randIndex
, 1);
76 // Rooks and king positions are now fixed,
77 // because of the ordering rook-king-rook
78 const rook1Pos
= positions
[0];
79 const kingPos
= positions
[1];
80 const rook2Pos
= positions
[2];
81 // Finally put the shuffled pieces in the board array
82 pieces
[c
][rook1Pos
] = "r";
83 pieces
[c
][knight1Pos
] = "n";
84 pieces
[c
][bishop1Pos
] = "b";
85 pieces
[c
][queenPos
] = "q";
86 pieces
[c
][kingPos
] = "k";
87 pieces
[c
][bishop2Pos
] = "b";
88 pieces
[c
][knight2Pos
] = "n";
89 pieces
[c
][rook2Pos
] = "r";
90 flags
+= rook1Pos
.toString() + rook2Pos
.toString();
93 pieces
["b"].join("") +
94 "/pppppppp/8/8/8/8/PPPPPPPP/" +
95 pieces
["w"].join("").toUpperCase()
98 return { fen: fen
, o: {flags: flags
} };