Build A Number Guessing Game With C# And WinUI 3

by Rajiv Sharma 49 views

Hey guys! Let's dive into creating a super cool number guessing game using C# and WinUI 3. This is going to be a fun project where we'll not only build the game logic but also design an artistic user interface and set up CI/CD for our app. Ready? Let’s get started!

1. Setting Up the WinUI 3 Project

First things first, we need to create a new WinUI 3 project. Think of this as laying the foundation for our game. We're going to use the .NET CLI, which is a super handy tool for creating .NET projects. Open up your command prompt or terminal, and let’s run this command:

dotnet new winui

This command tells .NET to create a new WinUI 3 project for us. It’s like telling a chef to start prepping the ingredients. Once the project is created, you’ll have all the basic files and folders you need to start building your game. This includes the project file (.csproj), the main window XAML file (MainWindow.xaml), and the code-behind file (MainWindow.xaml.cs). Creating the WinUI 3 project is the crucial first step. This command initializes the project with all the necessary files and dependencies, making sure we're starting on the right foot. We'll then move on to designing the UI and implementing the game logic, ensuring a smooth and engaging user experience. This initial setup is vital for the subsequent stages of development, including the implementation of CI/CD pipelines. So, let's dive in and get this project up and running!

2. Designing the User Interface in XAML

Now, let's make our game look awesome! We’re going to design the user interface using XAML (Extensible Application Markup Language). XAML is like the blueprint for our UI – it defines how our game will look and feel. Open the MainWindow.xaml file. This is where the magic happens.

We'll need a few key elements:

  • A TextBlock for Instructions: This will tell the player what to do. Something like, “Guess a number between 1 and 100!”
  • A TextBox for User Input: This is where the player will type their guess.
  • A Button to Submit the Guess: Players need a way to submit their guess, right?
  • Another TextBlock for Feedback: This will tell the player if their guess was too high, too low, or correct.

Here’s a basic example of what your XAML might look like:

<Window
    x:Class="NumberGuessingGame.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:NumberGuessingGame"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
        <TextBlock Text="Guess a number between 1 and 100!" Margin="10"/>
        <TextBox x:Name="GuessInput" Width="200" Margin="10"/>
        <Button Content="Submit Guess" Click="SubmitGuess_Click" Margin="10"/>
        <TextBlock x:Name="FeedbackText" Margin="10"/>
    </StackPanel>
</Window>

Adding Some Style

To make our game look even better, let's add some styles. Think of styles as the decorations that make our game visually appealing. You can set things like font size, colors, and margins. This is where you can really let your artistic side shine! You can define styles directly in the XAML or in separate style resources. For example, you might want to change the background color or the font of the text. Designing the UI is a critical phase in any application development process, especially for games. A well-designed user interface not only makes the game visually appealing but also enhances user engagement and playability. In our number guessing game, the XAML layout is the foundation of the UI. We start by placing the essential elements such as the instructions, input box, submit button, and feedback text blocks. These components are strategically arranged to provide a clear and intuitive gameplay experience. Furthermore, adding styles to these elements, such as setting font sizes, colors, and margins, helps to create a polished and professional look. These stylistic touches can significantly improve the overall aesthetic appeal of the game. A good UI ensures that players can easily understand the game's objective and interact with it seamlessly. The artistic UI design, achieved through careful arrangement and styling, makes the game more enjoyable and user-friendly. This attention to detail in the UI design can be a key factor in the success of the game. For instance, using a calming color palette and a clear, readable font can create a relaxed and inviting atmosphere for the player. Similarly, consistent spacing and alignment of elements can make the interface feel more organized and professional. By focusing on these aspects, we can create a UI that not only looks good but also enhances the gameplay experience. Let's get creative and style this game to perfection!

3. Implementing the Game Logic in C#

Alright, let’s get to the brains of our game! We need to implement the logic that makes everything work. This is where C# comes in. Open the MainWindow.xaml.cs file. This is the code-behind file for our main window, and it’s where we’ll write the C# code to handle the game’s functionality.

Generating a Random Number

First, we need to generate a random number for the player to guess. We’ll use the Random class in C# to do this. Add a Random object as a private field in your MainWindow class, and then generate the number when the window is loaded.

using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;

namespace NumberGuessingGame
{
    public sealed partial class MainWindow : Window
    {
        private Random _random = new Random();
        private int _randomNumber;

        public MainWindow()
        {
            this.InitializeComponent();
            _randomNumber = _random.Next(1, 101); // Generates a number between 1 and 100
        }
    }
}

Handling Button Clicks

Next, we need to handle the button click event. When the player clicks the “Submit Guess” button, we need to check their guess and provide feedback. We'll add an event handler for the button's Click event.

private void SubmitGuess_Click(object sender, RoutedEventArgs e)
{
    if (int.TryParse(GuessInput.Text, out int guess))
    {
        if (guess < _randomNumber)
        {
            FeedbackText.Text = "Too low! Try again.";
        }
        else if (guess > _randomNumber)
        {
            FeedbackText.Text = "Too high! Try again.";
        }
        else
        {
            FeedbackText.Text = "Congratulations! You guessed the number!";
        }
    }
    else
    {
        FeedbackText.Text = "Invalid input. Please enter a number.";
    }
}

Managing Game State

We might also want to manage the game state, such as the number of guesses the player has made or whether the game is over. You can add additional variables and logic to handle this. Implementing the game logic is where the magic of our number guessing game truly comes to life. This involves writing the C# code that governs how the game functions, from generating the random number to evaluating the player's guesses. The core of the game logic resides in the MainWindow.xaml.cs file, where we define the behavior and interactions within the game. First and foremost, we need to generate a random number within a specific range, say between 1 and 100. This is the number the player will try to guess. We use the Random class in C# to achieve this, creating an instance of Random and calling its Next method to get a random integer. This number is stored for comparison against the player's guesses. Next, we handle the player's input by creating an event handler for the