C# Tutorial – Make a Word Shuffle Game In Windows Form and Visual Studio

Hi, in this tutorial we will be making a word shuffle game in windows form. Words will be loaded from an external text file. We will add those words to the text file and load using C#. Each word in the text file will be saved as a list item then we will create a scramble function that will shuffle or scramble the words around in a random order and display it on the screen. There is a text box on the app to enter your  input, it will capture that input and compare it to the original word. If the word captured is correct then we will move on the next word from list and display to the screen or we will add 1 to the guessed integer.

Lesson Objectives:

  1. Make a word shuffle game in windows form using C#
  2. Use Key Press enter to check if the value entered matches the original word
  3. Load external text file
  4. Use list to capture the lines from the text file and save them as items
  5. Create a custom function to take in the text as an argument and scramble the words using New.GUID() method
  6. Keep track of how many times we guessed each word
  7. Show a final game won message when all of the words have been solved.

Video Tutorial

Get Word Shuffle Game on GitHub

Source Code Explained

Variables

List<string> words = new List<string>();
string newText;
int i = 0;
int guessed = 0;

In the provided code snippet for a word guessing game, several variables are declared to facilitate the game’s mechanics. The variable named “words” is a List of strings, serving as a repository for the words used in the game. These words are likely chosen as the targets for players to guess. By storing them in a list, the game can easily access and manipulate them as needed during gameplay.

Another variable, “newText,” is a string type and is presumably utilized to represent the current word being guessed by the player. This variable might be dynamically updated as the player makes progress in guessing the word, perhaps revealing correct guesses and keeping unrevealed letters hidden.

The integer variable “i” appears to function as an index or a counter within the game. It starts at 0, suggesting it might be used to iterate through the list of words or perform other operations requiring sequential access or counting.

Lastly, the variable “guessed” is another integer, possibly employed to track the player’s progress in the game. It likely increments as the player successfully guesses letters or words, providing feedback on their performance or determining when the game is won.

Together, these variables form the foundational components of the word guessing game, enabling the storage of words, tracking of player progress, and management of game state throughout the gameplay experience.

Form 1 Constructor

public Form1()
{
    InitializeComponent();
    Setup();
}

The constructor for Form1 in the Windows Forms application initializes the form’s components by calling the InitializeComponent() method. This method is typically auto-generated by the Visual Studio designer and is responsible for setting up the visual elements of the form, such as buttons, labels, and text boxes.

Additionally, the constructor invokes a custom function named Setup() immediately after initializing the form’s components. This function is responsible for performing any additional setup tasks required by the application upon its initialization or startup.

By calling Setup() within the constructor, the application ensures that necessary setup procedures are executed seamlessly when the program loads. This structured approach enhances the readability and maintainability of the codebase, as it clearly delineates the initialization process and any subsequent setup steps. Furthermore, it promotes code reusability and modularity, allowing for easy modification or extension of the setup logic as the application evolves.

Set Up Function

private void Setup()
{
    words = File.ReadLines("words.txt").ToList();
    newText = Scramble(words[i]);
    lblWord.Text = newText;
    lblInfo.Text = "Words: " + (i + 1) + " of " + words.Count;
}

The function named Setup() in the Windows Forms application serves the purpose of initializing the game environment by performing several essential tasks. Firstly, it reads a list of words from a text file named “words.txt” and stores them in a List<string> variable named “words”. This step ensures that the game has access to a pool of words from which players can make guesses.

Subsequently, the function scrambles the first word from the list of words using a custom method named Scramble(), and assigns the scrambled word to a string variable named “newText”. This scrambled word is then displayed on a label control named “lblWord”, allowing the player to begin guessing the word.

Moreover, the function updates another label control named “lblInfo” to provide the player with information about the current progress in the game. It displays the number of words attempted so far (denoted by the variable “i” incremented by 1) out of the total number of words available in the list.

Overall, the Setup() function plays a crucial role in initializing the game environment by loading words from a file, preparing the first word for guessing by scrambling it, and providing informative feedback to the player about their progress within the game.

Scramble text function

private string Scramble(string text)
{
    return new string(text.ToCharArray().OrderBy(x => Guid.NewGuid()).ToArray());
}

The function named Scramble() in the provided code snippet is designed to randomize the order of letters within a given word provided through the “text” parameter. This process involves rearranging the characters of the input word in a random sequence, thereby creating a scrambled version of the original word. The output of this function is a string representing the scrambled word.

The implementation of the Scramble() function utilizes a method chain to achieve the randomization of letters within the input word. Firstly, the input word is converted into an array of characters using the ToCharArray() method. Next, the OrderBy() LINQ extension method is applied to the array of characters, with the ordering criterion specified as a function of a globally unique identifier (GUID) generated by the Guid.NewGuid() method.

A GUID, or globally unique identifier, is a 128-bit identifier that is globally unique and typically generated using a specific algorithm. In this context, the Guid.NewGuid() method generates a unique GUID value each time it is called. When used as a sorting criterion within the OrderBy() method, these GUID values effectively randomize the order of elements in the array.

Finally, the randomized array of characters is converted back into a string using the string constructor, which accepts an array of characters as its argument. This results in the creation of a string representing the scrambled version of the original word, where the letters appear in a random order.

The Scramble() function takes a word as input and produces a randomized version of that word by shuffling its letters in a random sequence. The use of GUIDs within the sorting process ensures a high degree of randomness in the resulting scrambled word, enhancing the unpredictability and variability of the game experience.

Key Is Pressed Event

private void KeyIsPressed(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                if (words[i].ToLower() == textBox1.Text.ToLower())
                {
                    if (i < words.Count - 1)
                    {
                        MessageBox.Show("Correct!", "Moo Says: ");
                        textBox1.Text = "";
                        i += 1;
                        newText = Scramble(words[i]);
                        lblWord.Text = newText;
                        lblInfo.Text = "Words: " + (i + 1) + " of " + words.Count;
                        guessed = 0;
                        lblGussed.Text = "Guessed: " + guessed + " times.";
                    }
                    else
                    {
                        lblWord.Text = "You Win, Well done";
                        return;
                    }    
                }
                else
                {
                    guessed += 1;
                    lblGussed.Text = "Guessed: " + guessed + " times.";
                }
                e.Handled = true;
            }
        }

The provided code snippet represents an event handler named KeyIsPressed, which is triggered when the enter key is pressed within a Windows Forms application. This function plays a critical role in the program’s functionality, as it checks whether the user’s input matches the correct answer corresponding to the word loaded from a text file.

Upon the detection of the enter key press event, the function first verifies if the pressed key is the enter key. If so, it proceeds to compare the user’s input (retrieved from a TextBox named textBox1) with the correct answer stored in the “words” list at the current index “i”. The comparison is case-insensitive, as both the user input and the correct answer are converted to lowercase using the ToLower() method before comparison.

If the user’s input matches the correct answer, and there are more words remaining in the “words” list, a message box is displayed, indicating that the user’s guess is correct. The TextBox is cleared, and the index “i” is incremented to move to the next word in the list. The newly scrambled word is displayed in a label named lblWord, along with updated information about the current word index and the total number of words.

In case the user’s input does not match the correct answer, the “guessed” counter is incremented to track the number of incorrect guesses. The lblGuessed label is updated to reflect the updated count of incorrect guesses.

Regardless of whether the user’s input is correct or incorrect, the Handled property of the KeyPressEventArgs object “e” is set to true, indicating that the key press event has been handled, and further processing of the event by other event handlers should be suppressed.

The KeyIsPressed event handler function is a crucial component of the program, responsible for validating user input against the correct answer and managing the game’s progression based on the user’s responses. It provides immediate feedback to the user, updating the interface to reflect the outcome of their guess and guiding them through the word guessing game experience.




Comment on this tutorial and let us know how you got on -