-
Notifications
You must be signed in to change notification settings - Fork 0
/
play.mjs
70 lines (66 loc) · 1.8 KB
/
play.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// 🟨🟨⬛⬛🟩
export class Game {
constructor(answer) {
this.answer = answer;
this.remainingGuesses = 6;
this.lost = false;
this.won = false;
this.guesses = [];
this.responses = [];
}
guess(word) {
if (this.lost || this.won) {
return;
}
this.guesses.push(word);
const response = getResponse(word, this.answer);
this.responses.push(response);
this.remainingGuesses--;
if (response.every((r) => r == "🟩")) {
this.won = true;
this.over = true;
} else if (!this.remainingGuesses) {
this.lost = true;
this.over = true;
}
return response;
}
print() {
const toLog = this.guesses.map((guess, i) => {
return { g: guess, r: this.responses[i].join("") };
});
console.table(toLog);
}
}
export function getResponse(test, answer) {
const response = [];
for (let i = 0; i < answer.length; i++) {
response.push("?");
}
const notFound = [];
for (let i = 0; i < answer.length; i++) {
if (test[i] === answer[i]) {
response[i] = "🟩";
} else if (!answer.includes(test[i])) {
notFound.push(answer[i]);
response[i] = "⬛";
} else {
notFound.push(answer[i]);
}
}
// Account for double letters. Wordle only does yellow for the count of any remaining unfound letters
// e.g. guess of Creed for the answer Smear will have a green e and then a black e. Likewise for single yellow
for (let i = 0; i < answer.length; i++) {
if (response[i] !== "?") {
continue;
}
const indexOfFound = notFound.indexOf(test[i]);
if (indexOfFound > -1) {
response[i] = "🟨";
notFound.splice(indexOfFound, 1);
} else {
response[i] = "⬛";
}
}
return response;
}