108 lines
2.6 KiB
JavaScript
108 lines
2.6 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) {
|
|
let totalOk = 0
|
|
let totalToTry = 0
|
|
|
|
for (let i = 0; i < this.expectedWord.length; i++) {
|
|
if (this.expectedWord.charAt(i) === triedLetter) {
|
|
totalToTry++
|
|
|
|
if (this.expectedWord.charAt(i) === this.triedWords[u].charAt(i)) {
|
|
totalOk++
|
|
}
|
|
}
|
|
}
|
|
|
|
if (totalToTry === totalOk) {
|
|
result.push(1)
|
|
} else {
|
|
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(0)
|
|
}
|
|
}
|
|
}
|
|
} else {
|
|
for (var x = 0; x < this.expectedWord.length; x++) {
|
|
result.push(0)
|
|
}
|
|
}
|
|
|
|
results.push({word, result})
|
|
}
|
|
|
|
return results
|
|
}
|
|
}
|
|
|
|
export default Game
|