matrix-motus-bot/game.js
2022-01-31 13:50:48 +01:00

91 lines
2.5 KiB
JavaScript

class Game {
constructor(expectedWord, words) {
this.expectedWord = expectedWord.toUpperCase()
this.triedWord = null
this.triedWords = []
this.maxTries = 6
this.words = words
this.won = false
}
tryWord(word) {
word = word.toUpperCase()
if (!this.acceptableWord(word)) {
return false
}
if (!this.isFinish()) {
this.triedWord = word
this.triedWords.push(this.triedWord)
this.won = this.triedWord === this.expectedWord
return true
}
return false
}
acceptableWord(word) {
if (word.length !== this.expectedWord.length) {
return false
}
return this.words.indexOf(word) > -1;
}
isFinish() {
return this.triedWords.length === this.maxTries || this.isWon()
}
isWon() {
return this.won
}
matrix() {
let results = []
for (let u = 0; u < this.maxTries; u++) {
let result = []
let word
if (this.triedWords.hasOwnProperty(u)) {
word = this.triedWords[u]
for (var x = 0; x < this.expectedWord.length; x++) {
let expectedLetter = this.expectedWord.charAt(x)
let triedLetter = this.triedWords[u].charAt(x)
if (expectedLetter === triedLetter) {
result.push(3)
} else {
if (this.expectedWord.indexOf(triedLetter) > -1) {
const numberOfTriedLetterInExpectedWord = this.expectedWord.split(triedLetter).length - 1
const cuttedTriedWord = this.triedWords[u].substr(0, x + 1)
const numberOfTriedLetterInCuttedWord = cuttedTriedWord.split(triedLetter).length - 1
if (numberOfTriedLetterInCuttedWord > numberOfTriedLetterInExpectedWord) {
result.push(1)
} else {
result.push(2)
}
} else {
result.push(1)
}
}
}
} else {
for (var x = 0; x < this.expectedWord.length; x++) {
result.push(0)
}
}
results.push({word, result})
}
return results
}
}
export default Game