Guest User

Untitled

a guest
Dec 27th, 2025
34
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 3.53 KB | None | 0 0
  1. use colored::Colorize;
  2. use rand::seq::IndexedRandom;
  3. use std::{collections::HashMap, fmt::Display};
  4.  
  5. #[derive(PartialEq, Eq, Clone, Copy, Debug)]
  6. enum LetterResult {
  7.     Absent(char),
  8.     Misplaced(char),
  9.     Correct(char),
  10. }
  11.  
  12. #[derive(PartialEq, Debug)]
  13. struct GuessResult(Vec<LetterResult>);
  14.  
  15. impl GuessResult {
  16.     fn is_win(&self) -> bool {
  17.         self.0.iter().all(|res| matches!(res, LetterResult::Correct(_)))
  18.     }
  19. }
  20.  
  21. impl Display for GuessResult {
  22.     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  23.        for r in &self.0 {
  24.            let x = match r {
  25.                LetterResult::Correct(c) => c.to_string().green(),
  26.                LetterResult::Misplaced(c) => c.to_string().yellow(),
  27.                LetterResult::Absent(c) => c.to_string().red(),
  28.            };
  29.            write!(f, "{x}")?;
  30.        }
  31.        Ok(())
  32.    }
  33. }
  34.  
  35. struct Guess(String);
  36.  
  37. impl Guess {
  38.    // FIX: io in new() is unconventional
  39.    fn from_input() -> Guess {
  40.        let mut input = String::new();
  41.  
  42.        let input = loop {
  43.            input.clear();
  44.  
  45.            std::io::stdin().read_line(&mut input).expect("FAILED TO READ LINE!");
  46.  
  47.            let trimmed = &input.trim();
  48.  
  49.            if !trimmed.chars().all(|x| x.is_ascii_alphabetic()) {
  50.                println!("Please only use letters in the english alphabet!");
  51.                continue;
  52.            }
  53.  
  54.            if trimmed.len() != 5 {
  55.                println!("Please only use words of length 5!");
  56.                continue;
  57.            }
  58.            // to_owned over to_string is a personal preference
  59.            break trimmed.to_uppercase();
  60.        };
  61.  
  62.        Guess(input)
  63.    }
  64.  
  65.    fn check(&self, correct: &str) -> GuessResult {
  66.        let guess = &self.0;
  67.  
  68.        let mut char_counts_correct = char_counts(correct);
  69.  
  70.        guess.chars().zip(correct.chars()).filter(|(a, b)| a == b).for_each(|(a, _)| {
  71.            *char_counts_correct.get_mut(&a).unwrap() -= 1;
  72.        });
  73.  
  74.        GuessResult(
  75.            guess
  76.                .chars()
  77.                .zip(correct.chars())
  78.                .map(|(a, b)| {
  79.                    if a == b {
  80.                        return LetterResult::Correct(a);
  81.                    }
  82.  
  83.                    if correct.contains(a)
  84.                        && char_counts_correct
  85.                            .get_mut(&a)
  86.                            .is_some_and(|x| { *x -= 1; *x >= 0 }) // x might dip below 0 which is fine
  87.                    {
  88.                        return LetterResult::Misplaced(a);
  89.                    }
  90.  
  91.                    LetterResult::Absent(a)
  92.                })
  93.                .collect::<Vec<_>>(),
  94.        )
  95.    }
  96. }
  97.  
  98. fn char_counts(word: &str) -> HashMap<char, i8> {
  99.    word.chars().fold(HashMap::new(), |mut acc, x| {
  100.        *acc.entry(x).or_default() += 1;
  101.        acc
  102.    })
  103. }
  104.  
  105. fn main() {
  106.    let words = ["HELLO"];
  107.  
  108.    let word = words.choose(&mut rand::rng()).unwrap();
  109.  
  110.    println!("----------WORDLE-----------");
  111.    println!("-----Terminal Edition------");
  112.  
  113.    let win = (0..6).any(|_| {
  114.        let guess = Guess::from_input();
  115.        let result = guess.check(word);
  116.        println!("{result}");
  117.  
  118.        result.is_win()
  119.    });
  120.  
  121.    println!("---------GAME OVER---------");
  122.  
  123.    if win {
  124.        println!("{}", "You Win!".bright_cyan());
  125.    } else {
  126.        println!("{}", "You Lose :(".red());
  127.        println!("The Word Was: {}", word.yellow());
  128.    }
  129.  
  130.    println!("---------------------------");
  131. }
Advertisement
Add Comment
Please, Sign In to add comment