I'd like to develop a bot that is able to win the 21 - counting game/NIM - game every time.
Rules: Here are the rules for the game:
- In a game players take it in turns to say up to 3 numbers (starting at 1 and working their way up).
- Who every say's the number 21 is eliminated.
Strategie: Winning the game ever time is possible if you know the right strategy How to win?
Continuing on, if you say 12 you win
if you say 9, you win,
- if you say 6, you win,
- if you say 3, you win
- So, if you go second, you can guarantee that you will say 3, and win every time.
My question: I'd like to create a bot using javascript that is able to beat the user.
let _ = function(call, int) {
setTimeout(call, int)
}
class game {
constructor() {
this.number = 1;
}
user(val) {
console.log(`Userinput: +${val}`)
for (let i=0; i<val; i++)
console.log(`number: ${this.number++}`)
this.checkWin("bot")
console.log("\n\n\n")
this.bot()
}
bot() {
let val = (this.number === 3) ? 3 : parseInt(Math.random()*2)+1
console.log(`Botinput: +${val}`)
for (let i=0; i<val; i++)
console.log(`number: ${this.number++}`)
this.checkWin("user")
console.log("\n\n\n")
}
checkWin(looser) {
if (this.number >= 21) {
console.log(`${looser} lost the game.`);
}
}
}
let instance = new game()
_(function() {
instance.user(3)
},0)
_(function() {
instance.user(2)
},100)
_(function() {
instance.user(3)
},200)
_(function() {
instance.user(3)
},300)
_(function() {
instance.user(1)
},400)
Note: I did not finished the development but obviously there are some issues. I would really appreciate if somebody is able to help me finding/fixing them.