From 75ea76714c61b7d93690cff27b234dde74788cb7 Mon Sep 17 00:00:00 2001 From: Dragon Fire Date: Fri, 22 Jan 2021 21:50:38 -0500 Subject: [PATCH] Make ai actually win --- commands/games-mp/nim.js | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/commands/games-mp/nim.js b/commands/games-mp/nim.js index e393cc76..2b0f0c09 100644 --- a/commands/games-mp/nim.js +++ b/commands/games-mp/nim.js @@ -176,15 +176,24 @@ module.exports = class NimCommand extends Command { return value; } - sum(board) { - let value = 0; - for (let i = 0; i < board.length; i++) { - value += board[i]; - } - return value; - } - computerTurn(board) { + let nearEnd = false; + let countNon1 = 0; + for (const row of board) { + if (row > 1) countNon1++; + } + nearEnd = countNon1 <= 1; + if (nearEnd) { + let movesLeft = 0; + for (const row of board) { + if (row > 0) movesLeft++; + } + const isOdd = movesLeft % 2 === 1; + const largest = Math.max(...board); + const indexOfMax = board.indexOf(largest); + if (largest === 1 && isOdd) return [indexOfMax, 1]; + return [indexOfMax, largest - Number(isOdd)]; + } for (let i = 0; i < board.length; i++) { if (board[i] < 0) continue; for (let j = 1; j <= board[i]; j++) {