Skip to content

Instantly share code, notes, and snippets.

@jda0
Created January 23, 2017 00:15
Show Gist options
  • Save jda0/aaa4da3815000a33ab97a557e78d8410 to your computer and use it in GitHub Desktop.
Save jda0/aaa4da3815000a33ab97a557e78d8410 to your computer and use it in GitHub Desktop.
Easy version of the board game mastermind
class Mastermind {
constructor() {
this.length = 4
this.chars = ['0', '1', '2', '3', '4', '5']
}
generate() {
this.key = []
for (var i = 0; i < this.length; i++)
this.key.push(this.chars[(Math.random() * this.chars.length) | 0])
}
guess(attempt) {
if (attempt.length != this.length)
return 'INVALID ATTEMPT'
let correct = 0, almost = 0, key2 = this.key.slice(0), idx
for (var i = 0; i < this.length; i++) {
if (key2[i] === attempt[i])
++correct
else if ((idx = key2.indexOf(attempt[i])) !== -1
&& key2[idx] !== attempt[idx]) {
key2[idx] = ' '
++almost
}
}
if (correct === this.length)
return 'CORRECT'
return correct + ' CORRECT, ' + almost + ' ALMOST'
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment