× Main Menu

WPF C# Tutorial – Create a Space Invaders game in Visual Studio

Adding events –

We are two different events for this game, one is for Key down which will trigger when any key on the keyboard pressed and second one key up event, this function will trigger when the keys are released. We can tell C# which keys to look out for and how to complete a task when those keys are pressed. Lets see how we can program those in to this game.


Right click on the canvas key is down and click on go to definition. This action will tell visual studio to create the canvas key is down event in the c# script so we don’t have to type it up. Once it done it come back to the xaml window again and do the same for the canvas key is up.

If you have done the go to definition action for both key is down and key is up then you should see the same code as above. Visual studio has added both of the events here for us.

On top of the window under the line “using System.Windows.Shapes” add the following line

using System.Windows.Threading;

This is important because we need to use the timer class from inside this namespace. Name spaces are collection of classes and function that can be used on different projects.

Now add the following functions as you see on the screen shots of in the code view below.

 

The three functions we have added are enemy bullet maker that will have the code to shoot back at the player, make enemies functions that’s going to generate the enemy sprites for this game and game engine event that will control the movement, shooting at enemies, moving and animating the space invaders on the screen.

Lets go and add some variables.

On top of the public MainWindow() line add the following variables. Each of them has comments on top of them to explain what is going on.

 

For this game we have 10 different variables. These variables were created predefine, we had lots of trials and error making this game so you can try out adding more to it after you have finished the game.

First two Booleans goLeft and goRight will help us control the player movement, then we have rectangle list called itemstoremove this list will hold all of the extra rectangle shapes we will have in this game for example bullets and enemies and then remove them when they are not needed.

Enemy images, bullet timer, bullet timer limit and enemy speed are all integers for this game and they will hold specific numbers for when the game is running. Dispatcher timer is the main game timer where we will instruct all the rules for this game including how to win and how the player can lose.

Image brush is a image texture class that we use to apply different images to the player character. This class will be use for the invader images too later on as you progress through the tutorial.

Go to Page 3 to start writing in the functions




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

%d bloggers like this: