Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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'
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement