Created
October 8, 2018 00:33
-
-
Save danew/6a31122424060e1cdcfce908a81eb957 to your computer and use it in GitHub Desktop.
Small sample for the Mastermind problem solving game
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
class Mastermind { | |
constructor() { | |
this.answer = []; | |
this.blocks = [ | |
'green', | |
'red', | |
'blue', | |
'yellow', | |
]; | |
} | |
newAnswer() { | |
for (let i = 0; i < 4; i++) { | |
this.answer[i] = this.blocks[Math.floor(Math.random() * 4)]; | |
} | |
} | |
deduce(guess) { | |
let blackPegs = 0; | |
for (let i = 0; i < 4; i++) { | |
if (guess[i] == this.answer[i]) { | |
guess[i] = null; | |
blackPegs++; | |
} | |
} | |
const whitePegs = Array.from(new Set(guess)).filter(block => this.answer.includes(block)).length; | |
if (blackPegs == 4) return 'You win'; | |
return { | |
whitePegs, | |
blackPegs, | |
} | |
} | |
guess = (guess) => this.deduce(guess); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment