Skip to content

Instantly share code, notes, and snippets.

@danew
Created October 8, 2018 00:33
Show Gist options
  • Save danew/6a31122424060e1cdcfce908a81eb957 to your computer and use it in GitHub Desktop.
Save danew/6a31122424060e1cdcfce908a81eb957 to your computer and use it in GitHub Desktop.
Small sample for the Mastermind problem solving game
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