Last active
January 25, 2022 23:20
-
-
Save ElectricCoffee/8f06fcbb1b07edae2cf617ff0d842c77 to your computer and use it in GitHub Desktop.
Fischer Random Chess setup generator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import _ from "lodash"; | |
// [0, 1, 2, 3, 4, 5, 6, 7] | |
// b, w, b, w, b, w, b, w | |
// gets all indices of `chr` in `str` | |
const getIndices = (chr) => (str) => | |
str | |
.split("") | |
.map((n, i) => [n, i]) | |
.filter(([n, _]) => n === chr) | |
.map(([_, i]) => i); | |
// replaces item at index in string | |
const replace = (index, item) => (string) => | |
string.substring(0, index) + item + string.substring(index + 1); | |
function blackBishop(board) { | |
const spot = _.sample([0, 2, 4, 6]); | |
return replace(spot, "b")(board); | |
} | |
function whiteBishop(board) { | |
const spot = _.sample([1, 3, 5, 7]); | |
return replace(spot, "b")(board); | |
} | |
function knight(board) { | |
const spot = _.flow([getIndices(" "), _.sample])(board); | |
return replace(spot, "n")(board); | |
} | |
function queen(board) { | |
const spot = _.flow([getIndices(" "), _.sample])(board); | |
return replace(spot, "q")(board); | |
} | |
function rooksAndKing(board) { | |
const [r1, k, r2] = getIndices(" ")(board); | |
return _.flow([replace(r1, "r"), replace(k, "k"), replace(r2, "r")])(board); | |
} | |
// start with 8 blank spaces | |
const board = _.repeat(" ", 8); | |
const result = _.flow([ | |
blackBishop, | |
whiteBishop, | |
knight, | |
knight, | |
queen, | |
rooksAndKing, | |
_.toUpper, | |
])(board); | |
console.log(result); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment