Skip to content

Instantly share code, notes, and snippets.

@konstantint
Last active April 25, 2020 00:34
Show Gist options
  • Save konstantint/f2ea7baa86694e35ddc232686f8d1f23 to your computer and use it in GitHub Desktop.
Save konstantint/f2ea7baa86694e35ddc232686f8d1f23 to your computer and use it in GitHub Desktop.
// Greedy solver for https://leprosorium.ru/comments/2379244/
let modeMap = {"fa-ellipsis-v": ":",
"fa-ellipsis-h": "..",
"fa-arrows-alt-v": "|",
"fa-arrows-alt-h": "-",
"fa-plus": "+",
"fa-bomb": "[]",
"fa-trash": "X",
"fa-skull": "@"};
let modes = Object.keys(modeMap);
function Cell(cell) {
this.div = cell;
this.score = parseInt(cell.innerText);
if (isNaN(this.score)) this.score = 0;
this.mode = "";
modes.forEach(m => {
if (cell.innerHTML.indexOf(m) >= 0) this.mode = modeMap[m];
});
}
function Solver() {
let cols = [...document.querySelectorAll("div.col")]
let field = cols.map(col => [...col.children].map(cell => new Cell(cell)))
let ncols = field.length
let nrows = field[0].length
function traverse(c, r, traversed) {
if (traversed[""+[c,r]]) return 0;
if (c < 0 || c >= ncols) return 0;
if (r < 0 || r >= nrows) return 0;
traversed[""+[c,r]] = true;
let cell = field[c][r];
if (cell.mode == "@") {
if (!("@" in traversed)) traversed["@"] = 0;
traversed["@"]++;
return -100;
}
if (cell.mode == "X") {
traversed["X"] = true;
return 0;
}
let result = cell.score;
if ([":","+"].indexOf(cell.mode) >= 0) {
for (let i = -1; i <= 1; i+=1)
result += traverse(c, r+i, traversed);
}
if (["..", "+"].indexOf(cell.mode) >= 0) {
for (let i = -1; i <= 1; i+=1)
result += traverse(c+i, r, traversed);
}
if (cell.mode == "[]") {
for (let i = -1; i <= 1; i += 1)
for (let j = -1; j <= 1; j += 1)
result += traverse(c+i, r+j, traversed);
}
if (cell.mode == "-") {
for (let i = 0; i < ncols; i++)
result += traverse(i, r, traversed);
}
if (cell.mode == "|") {
for (let i = 0; i < nrows; i++)
result += traverse(c, i, traversed);
}
if (traversed["X"]) {
if (traversed["@"]) result = -100*traversed["@"];
else result = 0;
}
return result;
}
function bestMove() {
let best = [0, 0];
let bestScore = 0;
for (let r = 0; r < nrows; r++)
for (let c = 0; c < ncols; c++) {
if (field[c][r].score == 0) continue;
let newScore = traverse(c, r, {});
if (newScore > bestScore) {
bestScore = newScore;
best = [c, r];
}
}
return best;
}
this.field = field;
this.bestMove = bestMove;
this.traverse = traverse;
}
function makeBestMove() {
let s = new Solver();
let move = s.bestMove();
console.log("Best move score:", s.traverse(move[0],move[1],{}));
s.field[move[0]][move[1]].div.click();
}
solver = setInterval(makeBestMove, 5000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment