Skip to content

Instantly share code, notes, and snippets.

@45deg
Created March 23, 2023 18:15
Show Gist options
  • Save 45deg/d50adf1f048ab762b0b1979fb49dafe8 to your computer and use it in GitHub Desktop.
Save 45deg/d50adf1f048ab762b0b1979fb49dafe8 to your computer and use it in GitHub Desktop.
Wordle for Rust by GPT-4
[package]
name = "wordle"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
rand = "0.8"
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::collections::HashSet;
use rand::seq::SliceRandom;
use rand::thread_rng;
fn main() {
let file = File::open("words.txt").expect("Unable to open words.txt");
let reader = BufReader::new(file);
let words: Vec<String> = reader.lines().map(|line| line.unwrap()).collect();
let secret_word = words.choose(&mut thread_rng()).unwrap();
let mut attempts = 6;
while attempts > 0 {
println!("You have {} attempts remaining. Please enter your guess:", attempts);
let mut guess = String::new();
std::io::stdin().read_line(&mut guess).expect("Error reading input");
let guess = guess.trim();
if guess.len() != 5 {
println!("Invalid input, please enter a five-letter word.");
continue;
}
let feedback = get_feedback(secret_word, guess);
println!("Feedback: {}", feedback);
if feedback == "🟩🟩🟩🟩🟩" {
println!("Congratulations! You've guessed the secret word: {}", secret_word);
break;
}
attempts -= 1;
}
if attempts == 0 {
println!("Sorry, you've run out of attempts. The secret word was: {}", secret_word);
}
}
fn get_feedback(secret_word: &str, guess: &str) -> String {
let mut feedback = vec!['⬛'; 5];
let mut secret_word_chars: Vec<char> = secret_word.chars().collect();
let mut guess_chars: Vec<char> = guess.chars().collect();
let mut yellow_positions = Vec::new();
// Check for correct position (green squares)
for i in 0..5 {
if secret_word_chars[i] == guess_chars[i] {
feedback[i] = '🟩';
secret_word_chars[i] = '-';
guess_chars[i] = '_';
}
}
// Check for correct letters in the wrong position (yellow squares)
for i in 0..5 {
if let Some(pos) = secret_word_chars.iter().position(|&c| c == guess_chars[i]) {
yellow_positions.push(i);
secret_word_chars[pos] = '-';
guess_chars[i] = '_';
}
}
for &i in yellow_positions.iter() {
feedback[i] = '🟨';
}
feedback.iter().collect()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment