In this blog post, I will be sharing the code for a Wordle solver composed in C#. The code uses an easy approach to find the correct word that's built into the Wordle puzzle. It's a fun project for one interested in games looking for a Wordle game to code.
The code:
using System;
class Program {
public static void Main (string[] args) {
// Call the RandomWordChooser function to get a random word from a pre-defined list
string word=RandomWordChooser();
// Check if the word is valid
bool isvalid=IsValid(word);
Console.WriteLine("Is the word I chose a valid word?: "+ isvalid);
Console.Write("\n");
// Start the game by calling the Play function with the chosen word
Play(word);
}
// Function to randomly choose a word from a pre-defined list
public static string RandomWordChooser(){
string word="";
string[] list={"apple", "blank", "color", "dance", "eagle", "fancy"};
Console.WriteLine("Please pick a number from 0-5");
int num=int.Parse(Console.ReadLine());
// Check if the number chosen is valid and return the corresponding word
if(num == 0 || num == 1 || num == 2 || num == 3 || num == 4||num == 5)
{
word=list[num];
}
else if(num < 0 || num > 5){
Console.Write("Invalid number");
}
return word;
}
// Function to check if the chosen word is valid (in this case, it needs to be 5 characters long)
public static bool IsValid(string word){
bool valid=false;
if(word.Length==5){
valid=true;
}
else {
valid=false;
}
return valid;
}
// Function to check the player's guess and provide feedback (X for correct letter and position, / for correct letter but wrong position, - for incorrect letter)
public static string CheckWord(string word){
string correctword=word;
string output="";
Console.WriteLine("\n"+"Please guess a 5 letter word");
string guess=Console.ReadLine();
// Loop through each letter of the guess and compare it to the corresponding letter in the correct word
for(int i=0; i<correctword.Length; i++)
{
string letter=guess.Substring(i,1);
if(correctword.Length==guess.Length)
{
if(correctword.Substring(i,1)==guess.Substring(i,1))
{
Console.Write("X");
output+=("X");
}
else if(correctword.Contains(letter))
{
Console.Write("/");
output+=("/");
}
else
{
Console.Write("-");
output+= "-";
}
}
}
return output;
}
// Function to play the game by calling the CheckWord function up to 6 times, or until the player guesses the correct word
public static void Play(string word)
{
for(int i=0; i<6; i++){
string check= CheckWord(word);
if(check=="XXXXX")
{
Console.WriteLine("\n"+"Win");
return;
}
}
Console.WriteLine("Lose");
}
}