Skip to content

Instantly share code, notes, and snippets.

@vvgomes
Created February 25, 2022 16:08
Show Gist options
  • Select an option

  • Save vvgomes/fa10fc09df8bc766718a9d5a5b913d9c to your computer and use it in GitHub Desktop.

Select an option

Save vvgomes/fa10fc09df8bc766718a9d5a5b913d9c to your computer and use it in GitHub Desktop.
Wordle
const words = require("./words.json");
const readline = require("readline");
const EVALUATION = {
GOOD: "\x1b[32m■\x1b[0m",
CLOSE: "\x1b[33m■\x1b[0m",
BAD: "\x1b[31m■\x1b[0m"
};
const evaluateChar = (wordChars) =>
(char, index) => {
const pos = wordChars.indexOf(char);
if (pos === index) return EVALUATION.GOOD;
if (pos >= 0) return EVALUATION.CLOSE;
return EVALUATION.BAD;
};
const evaluateGuess = (word, guess) =>
guess.split("").map(evaluateChar(word.split("")));
const wordFound = (evaluations) =>
!evaluations.filter(e => e !== EVALUATION.GOOD).length;
const chooseWord = (words) =>
words[Math.floor(Math.random() * words.length)];
const interface = readline.createInterface({
input: process.stdin,
output: process.stdout
});
function runGame(word, rounds, interface) {
if (!rounds) {
interface.close();
console.log(word.toUpperCase());
return;
}
interface.question("", (guess) => {
const evaluations = evaluateGuess(word, guess);
console.log(evaluations.join(""));
if (wordFound(evaluations))
runGame(word, 0, interface);
else
runGame(word, rounds - 1, interface);
});
}
runGame(chooseWord(words), 6, interface);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment