2025-01-22 10:50:12 +00:00
|
|
|
export const GUESS_RESULT = {
|
|
|
|
MISS: 'm',
|
|
|
|
WIN: 'w',
|
|
|
|
FOUL: 'f'
|
|
|
|
};
|
|
|
|
|
2025-01-22 10:29:50 +00:00
|
|
|
export const MARKERS = {
|
|
|
|
MISS: 'm',
|
|
|
|
RIGHT_POS: 'g',
|
|
|
|
RIGHT_CHAR: 'y'
|
|
|
|
};
|
|
|
|
|
|
|
|
export class GameController {
|
2025-01-22 10:50:12 +00:00
|
|
|
constructor(wordSource) {
|
|
|
|
this._wordSource = wordSource;
|
|
|
|
this._currentWord = wordSource.getCurrentWord();
|
2025-01-22 10:29:50 +00:00
|
|
|
this._guesses = 5;
|
|
|
|
}
|
|
|
|
|
|
|
|
wordLength() {
|
|
|
|
return this._currentWord.length;
|
|
|
|
}
|
|
|
|
|
|
|
|
guesses() {
|
|
|
|
return this._guesses;
|
|
|
|
}
|
|
|
|
|
|
|
|
checkGuess(guess) {
|
|
|
|
if (guess.length != this._currentWord.length) {
|
|
|
|
throw Error(`Expected length to be ${this._currentWord.length} but was ${guess.length}`);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check correct placements
|
2025-01-22 10:50:12 +00:00
|
|
|
let guessResult;
|
2025-01-22 10:29:50 +00:00
|
|
|
let markers = new Array(guess.length);
|
|
|
|
let misses = {};
|
|
|
|
let hits = {};
|
|
|
|
|
2025-01-22 10:50:12 +00:00
|
|
|
if (!this._wordSource.isWord(guess)) {
|
|
|
|
return {
|
|
|
|
guessResult: GUESS_RESULT.FOUL,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2025-01-22 10:29:50 +00:00
|
|
|
for (let i = 0; i < guess.length; i++) {
|
|
|
|
if (guess[i] == this._currentWord[i]) {
|
|
|
|
markers[i] = MARKERS.RIGHT_POS;
|
|
|
|
hits[guess[i]] = MARKERS.RIGHT_POS;
|
|
|
|
} else {
|
|
|
|
if (this._currentWord[i] in misses) {
|
|
|
|
misses[this._currentWord[i]] += 1;
|
|
|
|
} else {
|
|
|
|
misses[this._currentWord[i]] = 1;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check words that are wrong placement but are in the word
|
|
|
|
// Distribute based on the words position
|
|
|
|
for (let i = 0; i < guess.length; i++) {
|
|
|
|
if (markers[i]) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (misses[guess[i]] && misses[guess[i]] > 0) {
|
|
|
|
misses[guess[i]] -= 1;
|
|
|
|
markers[i] = MARKERS.RIGHT_CHAR;
|
|
|
|
|
|
|
|
if (!hits[guess[i]]) {
|
|
|
|
hits[guess[i]] = MARKERS.RIGHT_CHAR;
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
if (!hits[guess[i]]) {
|
|
|
|
hits[guess[i]] = MARKERS.MISS;
|
|
|
|
}
|
|
|
|
markers[i] = MARKERS.MISS;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2025-01-22 10:50:12 +00:00
|
|
|
let isRight = markers.filter((x) => x == MARKERS.RIGHT_POS).length == this._currentWord.length;
|
|
|
|
if (isRight) {
|
|
|
|
guessResult = GUESS_RESULT.WIN;
|
|
|
|
} else {
|
|
|
|
guessResult = GUESS_RESULT.MISS;
|
|
|
|
}
|
|
|
|
|
2025-01-22 10:29:50 +00:00
|
|
|
return {
|
2025-01-22 10:50:12 +00:00
|
|
|
guessResult: guessResult,
|
2025-01-22 10:29:50 +00:00
|
|
|
hits: hits,
|
|
|
|
markers: markers
|
|
|
|
};
|
|
|
|
}
|
|
|
|
}
|