× Main Menu

WPF C# Tutorial- Create a simple Binary Calculator game in Visual Studio

In this tutorial we will show you how to make a fun binary calculator game. Learning binary is very important when it comes to computer science. This game will help you understand how binary is calculated and while you are at it will give you a little challenge to calculate the numbers directly off the screen. We have a binary calculator game tutorial in this website it was made on visual basic so it needs a little updating now. WPF forms are really great for creating responsive and efficient apps for windows and other devices. This will be a perfect little project for you understand how the GRID system work in WPF along will buttons, events and off course add dash of colour on everything why not.

Lesson objectives –

  • Create a simple binary calculation game in visual studio with WPF C#
  • Work with multiple text boxes, font sizes and add various restrictions to WPF controls
  • Run for each loop to identify the text boxes and interact with them
  • Generate random numbers and check if the random number is correct in the game
  • Convert strings to integers and perform calculations
  • Enable and disable various controls in WPF

To begin open up Visual Studio. For this tutorial Visual Studio 2017 is being used buy you can follow with any version that support WPF framework.

Lets just quickly go over how binary calculation works and what we are trying to do here. We want to make a 256-bit binary table and calculate the results from Binary to numbers.

Here is the table we want to use in this game

256

128 64 32 16 8 4 2

1

As you can see the binary numbers start from right to left. Each time we jump a column it will double itself so 1 becomes 2 and 2 becomes 4 and 4 becomes 8 and so on. If we add all of them together we will get 511 so we can generate any number from 0 – 511 by using this table. Lets take a look

Lets say you want to make the number 33 see how we can use this table to calculate it

256

128 64 32 16 8 4 2 1
0 0 0 1 0 0 0 0

1

In binary of number 33 is going to be = 000100001

32 + 1 = 33

When the number is 0 it means the value is inactive and when the number is 1 it means it is active. So when you see a 1 in the table it will all add up together and 0’s can be ignored as they are inactive. Lets try again

Let’s make 413 in this table

256 128 64 32 16 8 4 2 1
1 1 0 0 1 1 1 0 1

Binary of number 413 is = 110011101

256 + 128 + 16 + 8 + 4 + 1= 413

Its simple yet elegant. Now let’s make the game.

Create a new project, call it Binary Calculator and Click OK.

mooict wpf c# Binary Calculator game project naming window

This is the empty WPF form. You can see the main window on the top and the XAML code in the bottom. We will add our own XAML to it now and you will see how it changes in the main window.

mooict wpf c# Binary Calculator game default window screen shot

Below is the full XAML code for this application. You can start implementing it to your app. Each line of the code will be explained next.

Title=”Binary Calculator C# by Moo ICT” Height=”450″ Width=”800″>

In the title tag add the title for the app and include Height 450 and width 800

<Grid Name=”mainGrid” Height=”431″>

This is grid start tag, we have named this grid mainGrid and set a height to 431

<Grid.RowDefinitions>

<RowDefinition Height =”100″></RowDefinition>

<RowDefinition Height =”50″></RowDefinition>

<RowDefinition Height =”100″></RowDefinition>

</Grid.RowDefinitions>

First, we need to add 3 ROWs to this application. The top Row will contain the buttons and the label, mid rows will contain labels for the text boxes and text boxes and the last row will include the labels and check answer buttons. So, it’s important to plan out what you are making and how it should look like before we start coding in the process. Since this is a simple app these 3 rows will be sufficient for our purposes.

<Grid.ColumnDefinitions>

<ColumnDefinition Width=”1*” />

<ColumnDefinition Width=”1*” />

<ColumnDefinition Width=”1*” />

<ColumnDefinition Width=”1*” />

<ColumnDefinition Width=”1*” />

<ColumnDefinition Width=”1*” />

<ColumnDefinition Width=”1*” />

<ColumnDefinition Width=”1*” />

<ColumnDefinition Width=”1*” />

</Grid.ColumnDefinitions>

With rows come columns. Think of this as a table. We need 3 rows and 9 columns. We need 9 columns because we have 9 different numbers to add and we want to be aligned perfectly for this app.

<Label Grid.Column=”0″ Grid.Row=”1″ HorizontalAlignment=”Center” FontSize=”20″>256</Label>

<Label Grid.Column=”1″ Grid.Row=”1″ HorizontalAlignment=”Center” FontSize=”20″>128</Label>

<Label Grid.Column=”2″ Grid.Row=”1″ HorizontalAlignment=”Center” FontSize=”20″>64</Label>

<Label Grid.Column=”3″ Grid.Row=”1″ HorizontalAlignment=”Center” FontSize=”20″>32</Label>

<Label Grid.Column=”4″ Grid.Row=”1″ HorizontalAlignment=”Center” FontSize=”20″>16</Label>

<Label Grid.Column=”5″ Grid.Row=”1″ HorizontalAlignment=”Center” FontSize=”20″>8</Label>

<Label Grid.Column=”6″ Grid.Row=”1″ HorizontalAlignment=”Center” FontSize=”20″>4</Label>

<Label Grid.Column=”7″ Grid.Row=”1″ HorizontalAlignment=”Center” FontSize=”20″>2</Label>

<Label Grid.Column=”8″ Grid.Row=”1″ HorizontalAlignment=”Center” FontSize=”20″>1</Label>

These are labels on top of the text boxes, each of these label need to aligned to their correct text box so the users know what they are calculating when the program runs. Lets break down one of them and it will be easier to explain it. As you have read earlier binary starts from right to left. The left side will show the larger numbers and the right side will show the smallest numbers.

<Label Grid.Column=”0″ Grid.Row=”1″ HorizontalAlignment=”Center” FontSize=”20″>256</Label>

In this label its assigned to GRID Column 0 and GRID Row 1, horizontal alignment is set to centre and its font size is 20. This label has a content which simply states 256. So this one is position to the left hand side.

<Label Grid.Column=”1″ Grid.Row=”1″ HorizontalAlignment=”Center” FontSize=”20″>128</Label>

This one above is set to Grid Column 1 and Grid Row 1. So, it’s the next one down from 256 label. It also has a centre alignment and font size of 20. This label contains the number 128.

As you work your way down you will see that the Grow will remain the same but we will change their Column location and their values.

Now let’s get to the text boxes –

<TextBox Margin=”0,10,0,13″ MaxLength=”1″ Grid.Row=”2″ Background=”LightCoral” MaxLines=”1″ FontSize=”20″ TextAlignment=”Center” Tag=”256″ HorizontalAlignment=”Center” Width=”77″/>

We start the tag with <TextBox it will have a small margin of 10 pixels from the top and 13 pixel from the right, Max length means we will only allow the user to put 1 digital inside of this text box, this will be placed in the second row of this main grid. Background colour is set to light coral, we will allow this text box to only have 1 line, font size is set to 20 and text alignment and horizontal alignment is centred. The TAG in the end of the textbox is very important. This TAG is set to 256 once again it’s the last one from the left. So we need to make sure that we do not have any spaces or errors in the tag because we will use the tag to calculate the accurate binary from the app.

If you look at rest of the text boxes in this XAML code you see the similar pattern as we have done with the labels before it. Make sure you read them carefully as you type them up.

<Label FontSize=”25″ Content=”Binary Calculator in WPF” Grid.ColumnSpan=”5″ HorizontalAlignment=”Left” Width=”356″ Height=”100″ VerticalAlignment=”Top”/>

This is the title label it will show up on top of the app.

<Label Name=”questionTxt” HorizontalContentAlignment=”Center” FontSize=”25″ Content=”Question” Margin=”0,92,0,-41″ Foreground=”Green” RenderTransformOrigin=”0.5,0.5″ Grid.Row=”2″ Grid.ColumnSpan=”6″ Grid.Column=”1″ Width=”533″ />

<Label Name=”answerTxt” HorizontalContentAlignment=”Center” FontSize=”25″ Content=”Answer in Binary” Margin=”0,141,0,-90″ Foreground=”Maroon” RenderTransformOrigin=”0.5,0.5″ Grid.Row=”2″ Grid.ColumnSpan=”6″ Grid.Column=”1″ Width=”533″ />

Above we have two labels, one is where the questions will show and the second one where the answers will when the user clicked on the check answer button.

<Button Name=”checkButton” Click=”checkAnswer” FontSize=”16″ Margin=”0,204,0,-142″ Content=”Check!” Grid.ColumnSpan=”2″ Grid.Column=”3″ Grid.Row=”2″ HorizontalAlignment=”Center” Width=”155″ />

<Button Click=”startGame” Margin=”10,9,6,0″ Content=”Start” Grid.Column=”8″ Height=”33″ VerticalAlignment=”Top” Background=”LightGreen”/>

<Button Click=”showHelp” Margin=”10,53,6,0″ Content=”Help” Grid.Column=”8″ Height=”33″ VerticalAlignment=”Top” Background=”LightPink”/>

Above we have all 3 buttons for this game. The first one is the check button, this button will be used to check the user answer against the computers question.

The start game button will be used to start the game with a new question

The help button will show a simple help instruction for users to understand how to play this game.

Both start and help button will be placed on the top right corner of the game and check button will be placed bottom of the application window.

Take a look at how this interface should look like.

mooict wpf c# Binary Calculator game updated window screen shot

If your window looks different than this one, please check the XAML code again above and see what’s missing. If you are all good to go then lets get to adding events for this application.

Adding Events for the buttons

Inside the button Tag right click on the checkAnswer keyword and click on Go to Definition. Visual Studio IDE helps us a lot by adding some of the template functions and events for us so we don’t have to type it up. If you click no the go to definition it will take you to the code window and you see the event that’s been added.

mooict wpf c# Binary Calculator game adding click event to check answer button

Your code window should look like this, you should have a checkAnswer event added to it.

mooict wpf c# Binary Calculator game check answer click event added

Now lets go back to the XAML code by clicking on the MainWindow.xaml tab on top of your visual studio window.

mooict wpf c# Binary Calculator game tab in visual studio for XML and C sharp script

Right click on the StartGame keyword inside the button tag and click on the go to definitions option

mooict wpf c# Binary Calculator game adding the start game event with the start button click

This will add a start game event in your code window. Lets go back to the XAML file and add one more event.

mooict wpf c# Binary Calculator game start game event linked and added screen shot

Right click on the showHelp keyword inside the button tag and click no the go to definitions option.

mooict wpf c# Binary Calculator game adding show help event to the help button

The last event for this program has been added. See you have 3 different events for this app now. We can start adding our instructions to it.

mooict wpf c# Binary Calculator game screen shot of all 3 events to the c sharp code

Note – the Green lines that start with a // are comments. Its not mandatory to put them but it’s a very useful to explain what is going on with the code. As part of our learning journey we need to learn how to comment in the code so it would be beneficial for you to add them along with the normal codes. These comment do not effect your code or the program in any way because they are ignored by the C# compiler at run time so you can write however and what ever you want to.

To start off add the variables for this app. We need 3 variables

mooict wpf c# Binary Calculator game adding variables and making changes to the main window function

Int total; this is a integer called total. We are not assigning any value to it now but will do later on.

Random randomNumber = new Random(); we are importing a class called Random to this app and creating a new instance of it called randomNumber. This way we can generate different random numbers when we need to for this calculation quiz.

Int randomint; Once again we are making another integer and not setting a value straightaway. We will add a value to it later on. This integer will be used to hold the random numbers generated by the variable before it.

Notice we are naming these variables logically. Do not name your variable a1, a2, ad3, or so on. The headaches that come with try to decipher your own work is time consuming and pointless. Do the right thing and name each variable, function, event and objects logically so next time you can simply load it up and understand what was done to it without trying to remember what you did in this project in the first place.

Inside the MainWindow() you can see that we have given it some instructions for the checkButton. Initially we want to disable this button so only when the player clicks on start game it becomes active.

So to this we use the code like CheckButton.IsEnabled = False; so the program knows this button will be enabled when the app loads.

Start Game Event Code –

This event will trigger when the start button is clicked. The codes are comment as you can see with the green lines. Time to break down this function

First we are generating a random number inside the random int integer. The whole binary table can count up to 511 so we need to make sure the numbers we generate stay within this limit. This is why we are instructing the code to generate a number between 0 and 511. It will save that number inside of this random int integer.

After the random number has been generated, we will show the question to the user. In this case we are adding “What is” <- this part is a string PLUS randomint integer PLUS “in binary”. If the random number is 51 it will show what is 51 in binary. The only part that’s changing in this line is the random number part.

Answertxt.content = “”; means we are emptying the answer text label. After that we are enabling the check answer button so the user can enter their number in the text boxes and check if its correct

Lastly in this function we need to reset all of the text boxes and give them an input of 0. Why are we using a loop for this? Because its quicker and more efficient. Lets say we want to check the text boxes content to 0 one by one we have 9 of them so the code would be something like this

txtBox1.Text = “0”;

txtBox2. Text = “0”;

txtBox3. Text = “0”; and so, on instead of that we are letting the code check if there are any text boxes in this app which we know we have 9 of them so when it finds them all it will set all of their texts to 0. Neat right.

The code will read like this for each component x in main grid that’s a type of a text box, we save their info inside the x variable and then we can modify their properties from it without needing to access them via their name or tag. Cool that’s the start game event. Now lets move to the show help event.

Show Help Event Code –

Below is the show help event code, this is a simple event it will only show a message box when its clicked, giving instructions to the player on how to interact with the game. Take a closer look

Result will be:We can access the Message box directly we don’t need to make any variables or other stuff in visual studio. The message box can show strings or texts inside of the box. For this one we do need to modify the strings slightly. We want to show the information in different lines so its not jumbled into one. In order to that we are using the Environment.NewLine command. When we join it with the other strings in the code it will then add the lines that come after it below the first one. So when we are using “Its very hot today ” + Environment.NewLine + “I want an ice cream.”

Its very hot today

I want an ice cream

Type this function up and let’s move on to the main one, the check answers event.

Check Answer Event Code –

This is the main event that will run this game and make it interesting.

The start function generates the random number and enables the check answer button, this button will calculate to see if that number is equals to the players selection. Since we are using numbers to binary and moving them from binary to numbers, we have to find a creative solution to solve this problem without complicating the logic.

In the first two lines we are resetting the total integer to 0 and emptying the answer text label on the screen.

We have another for each loop in this function, just like we did before instead go through manually we are letting the code do most of the heavy lifting for us. So, we have another foreach loop that’s saving all the text boxes with the X variable. After we have initiated the for each loop we check if any of the text boxes contain a 1 if so, we will look at their tag and add them together in the total integer. This is why we have the line if (x.Text == “1”) {total += Convert.ToInt32(x.tag); once again if there is a 1 in the text box then we will take that particular text boxes tag and add it to total. This way we can check if the random number generated as the question and the total is equal to each other simple right.

Let’s illustrate this point

Say the question is what is 100 in binary?

The for each loop will go through each of the text boxes on the screen, find the ones with a 1 and then take their tags and add them to the total integer

 

256

128 64 32 16 8 4 2 1
0 0 1 1 0 0 1 0

0

Start loop

Did not find a 1 ignore to next

Did not find a 1 ignore to next Found a 1, Tag = 64 add to total and total = 64 Found a 1, tag = 32 add to total and total = 96 Did not find a 1 ignore to next Did not find a 1 ignore to next Found a 1, tag = 4 add to total and total = 100 Did not find a 1 ignore to next

Did not find a 1 ignore and end loop

See how it works.

In the answer text label, we need to show the Binary number we have created so as the loop is looking for the 1 in the text boxes, outside of the if statement we take all of their text representation and add them to the answer text label as a string

So, the string should show 001100100 when we click on check answer button.

In the last part of the code we have an if and else statement. This part of the code will check if the answer is correct show the answer correct message and if not, it will the answer is incorrect message.

We’ve tried to keep this application as simple as possible without having to complicate any parts, there lots of other ways to calculate the binary numbers, but we found that this way we can have fun and learn something new together. If you have made it this far without any issues then very well done. If you had some issues with the code either XAML or C# double check this tutorial and again and see where it went wrong.

See you on the next one. Moo Out.

Full C# Source Code –

 




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

%d bloggers like this: