UNPKG

wordle-shell

Version:

A Wordle for the command line

99 lines (92 loc) 3.04 kB
import chalk from "chalk"; import inquirer from "inquirer"; import Wordle, { CharState } from "./Wordle"; import WordPicker, { Langs } from "./WordPicker"; class Game { private wordle: Wordle; private max_tries = 6; private current_try = 1; private guesses: { guess: string, states: CharState[]; }[]; constructor(lang: Langs) { this.guesses = Array(); const wordPicker = new WordPicker(lang); this.wordle = new Wordle( wordPicker ); } public run() { this.prompt(); } private prompt(msg?: string) { console.clear(); console.log("Current try number: ", this.current_try); this.promptGuesses(); if (msg) { console.log(msg); } inquirer.prompt([ { type: "input", name: "guess", message: "What is your guess?", validate: (input, _) => { return String(input).length === Wordle.get_word_size(); }, } ]).then((anwser: { guess: string; }) => { const guess = anwser.guess.toUpperCase(); try { const states = this.wordle.checkWord(guess); this.guesses.push({ guess, states }); if (Wordle.done(states)) { this.promptSuccess(); } else { if (this.current_try < this.max_tries) { this.current_try++; this.prompt(); } else { this.promptFailure(); } } } catch (error) { this.prompt((error as Error).message); } }); } private promptGuesses() { for (let prev_guess of this.guesses) { this.promptGuess(prev_guess.guess, prev_guess.states); } } private promptSuccess() { console.clear(); console.log(chalk.bgBlack.greenBright("Congratulations")); console.log(chalk.bgBlack.greenBright("You Won!")); } private promptFailure() { console.clear(); console.log("You Failed"); console.log("The Word was:", chalk.bgWhite.black(this.wordle.getWord())); } private pickColor(state: CharState) { switch (state) { case CharState.Correct: return chalk.bgGreen.white; case CharState.Misplaced: return chalk.bgYellow.white; case CharState.Wrong: return chalk.bgRed.white; default: return chalk.bgBlue.white; } } private promptGuess(guess: string, states: CharState[]) { let builder = ""; for (let index = 0; index < guess.length; index++) { const color = this.pickColor(states[index] ?? CharState.Unknow); builder += color(guess[index]); } console.log(builder); } } export default Game;