Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use colored::Colorize;
- use rand::seq::IndexedRandom;
- use std::{collections::HashMap, fmt::Display};
- #[derive(PartialEq, Eq, Clone, Copy, Debug)]
- enum LetterResult {
- Absent(char),
- Misplaced(char),
- Correct(char),
- }
- #[derive(PartialEq, Debug)]
- struct GuessResult(Vec<LetterResult>);
- impl GuessResult {
- fn is_win(&self) -> bool {
- self.0.iter().all(|res| matches!(res, LetterResult::Correct(_)))
- }
- }
- impl Display for GuessResult {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- for r in &self.0 {
- let x = match r {
- LetterResult::Correct(c) => c.to_string().green(),
- LetterResult::Misplaced(c) => c.to_string().yellow(),
- LetterResult::Absent(c) => c.to_string().red(),
- };
- write!(f, "{x}")?;
- }
- Ok(())
- }
- }
- struct Guess(String);
- impl Guess {
- // FIX: io in new() is unconventional
- fn from_input() -> Guess {
- let mut input = String::new();
- let input = loop {
- input.clear();
- std::io::stdin().read_line(&mut input).expect("FAILED TO READ LINE!");
- let trimmed = &input.trim();
- if !trimmed.chars().all(|x| x.is_ascii_alphabetic()) {
- println!("Please only use letters in the english alphabet!");
- continue;
- }
- if trimmed.len() != 5 {
- println!("Please only use words of length 5!");
- continue;
- }
- // to_owned over to_string is a personal preference
- break trimmed.to_uppercase();
- };
- Guess(input)
- }
- fn check(&self, correct: &str) -> GuessResult {
- let guess = &self.0;
- let mut char_counts_correct = char_counts(correct);
- guess.chars().zip(correct.chars()).filter(|(a, b)| a == b).for_each(|(a, _)| {
- *char_counts_correct.get_mut(&a).unwrap() -= 1;
- });
- GuessResult(
- guess
- .chars()
- .zip(correct.chars())
- .map(|(a, b)| {
- if a == b {
- return LetterResult::Correct(a);
- }
- if correct.contains(a)
- && char_counts_correct
- .get_mut(&a)
- .is_some_and(|x| { *x -= 1; *x >= 0 }) // x might dip below 0 which is fine
- {
- return LetterResult::Misplaced(a);
- }
- LetterResult::Absent(a)
- })
- .collect::<Vec<_>>(),
- )
- }
- }
- fn char_counts(word: &str) -> HashMap<char, i8> {
- word.chars().fold(HashMap::new(), |mut acc, x| {
- *acc.entry(x).or_default() += 1;
- acc
- })
- }
- fn main() {
- let words = ["HELLO"];
- let word = words.choose(&mut rand::rng()).unwrap();
- println!("----------WORDLE-----------");
- println!("-----Terminal Edition------");
- let win = (0..6).any(|_| {
- let guess = Guess::from_input();
- let result = guess.check(word);
- println!("{result}");
- result.is_win()
- });
- println!("---------GAME OVER---------");
- if win {
- println!("{}", "You Win!".bright_cyan());
- } else {
- println!("{}", "You Lose :(".red());
- println!("The Word Was: {}", word.yellow());
- }
- println!("---------------------------");
- }
Advertisement
Add Comment
Please, Sign In to add comment