LoginSignup
3
2

More than 1 year has passed since last update.

RustでWordleクローンを作る

Last updated at Posted at 2022-01-16

最近流行りのWordleは、英単語推測ゲームです。これをCLI上で遊べるよう、Rustで作ってみました。プログラミング言語の習作の題材として面白いと思います。以下に仕様とRustプログラムをそのまま載せますので、参考にしてください。

wordle.gif

Wordle基本ルール

  • 6回の挑戦以内に正解の英単語を当てる
  • 正解の単語は必ず5文字
  • 単語を入力しエンターボタンを押すと、その単語が正解単語とどれだけ近いか、各文字の色が変わることで教えてくれる

仕様

  • ループ中にユーザからの入力を取る
  • 入力文字列を正解の文字列と比較し正誤判定
  • 結果表示
    • 文字位置が一致している場合、その文字色を緑で表示
    • 文字が別の位置に含まれる場合、その文字色を黄色で表示
    • 文字が正解単語に含まれない場合、普通に表示
  • 6回の挑戦以内に正答したら終了
  • 6回目の挑戦で不正解だったら正答を表示して終了
  • [発展] 正解の単語をランダムにする
  • [発展] 5文字しか入力できないようにする

下の自分の実装例では、発展とした仕様は未実装ですが、完全なWordleクローンを目指すならぜひ。

Rustでの実装例

まだRustを書き始めたばかりなのでよろしくお願いします。

main.rs
use colored::*;
use proconio::input;
use proconio::marker::Chars;
use ansi_escapes::{EraseLines};

#[derive(Debug)]
struct Word(Vec<char>);

impl Word {
    fn print_diff(&self, other: &Word) {
        for (i, char) in self.0.iter().enumerate() {
            let maybe_correct_char = other.0.get(i);
            match maybe_correct_char {
                Some(correct_char) => {
                    if char == correct_char {
                        print!("{}", char.to_string().green());
                    } else if other.0.contains(char) {
                        print!("{}", char.to_string().yellow());
                    } else {
                        print!("{}", char);
                    }
                }
                None => {}
            }
        }
        println!();
    }

    fn eq(&self, other: &Word) -> bool {
        self.0 == other.0
    }
}

fn main() {
    let correct_answer = Word(['w', 'o', 'r', 'l', 'd'].to_vec());

    let mut correct = false;

    for _i in 0..6 {
        input! {
            chars: Chars
        }

        let input = Word(chars);

        print!("{}", EraseLines(2));
        input.print_diff(&correct_answer);
        if input.eq(&correct_answer) {
            println!("Genius");
            correct = true;
            break;
        }
    }

    if !correct {
        println!("{}", correct_answer.0.into_iter().collect::<String>());
    }
}
Cargo.toml
[package]
name = "wordle-rs"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
ansi-escapes = "0.1.1"
colored = "2.0.0"
proconio = "0.4.3"
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2