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

The MainWindow() Function

The main function is added by default, we can load our own instructions with this function as the main window loads. Take a look at what we added to the main window function below

        public MainWindow()

            // set up the timer and events
            // link the dispatcher timer to a event called game engine
            dispatcherTimer.Tick += gameEngine;
            // this timer will run every 20 milliseconds
            dispatcherTimer.Interval = TimeSpan.FromMilliseconds(20);
            // start the timer
            // load the player images from the images folder
            playerSkin.ImageSource = new BitmapImage(new Uri("pack://application:,,,/images/player.png"));
            // assign the new player skin to the rectangle
            player1.Fill = playerSkin;
            // run the make enemies function and tell it to make 30 enemies

This function is loading all of the default values for the game. To start we are linking the dispatcher timer tick to the game engine event we created earlier. The interval time is being set up to 20 milliseconds and then we start the timer when all of the options been set.

Player skin is getting linked with the player PNG file we imported earlier and then we are applying the fill to the player1 rectangle we made in the canvas.

The last line is stating run the make enemies’ function and we are sending the number 30 inside this function. This means the function will make 30 different space invaders for this game. When a function accepts certain arguments or options inside the declaration brackets, we must send it with that information otherwise it will not work for +example

Make enemies func+9++8++9+879+8+988tion title looks like this public void makeEnemies(int limit) <- look at inside the bracket, its asking for an integer and it will save it as limit so when we call this function we can say makeEnemies(30) <- means make 30 different enemies or makeEnemies(10) <- it will make 10 different enemies. The function will not accept anything other than an integer since we have declared it in the code. Follow along the tutorial to see how it actually makes the enemies.

Canvas Key is Down Event

This event will trigger when then keys are pressed on the keyboard. We need to tell the app what to when left or right key is pressed

private void Canvas_KeyisDown(object sender, KeyEventArgs e)
            // this is the key down event
            // if the left key is pressed set go left to true
            // if the right key is pressed set go right to true
            if (e.Key == Key.Left)
                goLeft = true;
            if (e.Key == Key.Right)
                goRight = true;

Inside of this function we have two if statements, first we check if the left key is pressed if so we set the go left Boolean to true and we do the same for the right key with the go right Boolean.

Canvas Key is Up event

This event does similar things to the key down event except this event will trigger when the keys are released on the keyboard. The first two if statement is exactly the same as key is down event except they are setting the go left and go right Boolean to false. This way the player will stop moving when the keys are released.

        private void Canvas_KeyIsUp(object sender, KeyEventArgs e)
            // this is the key up event
            // if the left key is let go set go left to false
            // if the right key is let go set go right to false

            if (e.Key == Key.Left)
                goLeft = false;
            if (e.Key == Key.Right)
                goRight = false;

            // below you have the if statement that will make the bullets
            // check if the space key is let go
            if (e.Key == Key.Space)
                // clear all the items from the items to remove list first

                // make a new rectangle called new bullet and add a tag called bullet, height 20 width 5 backgroubnd white and border to red
                Rectangle newBullet = new Rectangle
                    Tag = "bullet",
                    Height = 20,
                    Width = 5,
                    Fill = Brushes.White,
                    Stroke = Brushes.Red

                // place the bullet where the player is
                Canvas.SetTop(newBullet, Canvas.GetTop(player1) - newBullet.Height);
                Canvas.SetLeft(newBullet, Canvas.GetLeft(player1) + player1.Width / 2);
                // add the bullet to the screen


We also have a third key release event code in this function. That’s the space key. Now we want to create the bullet when the key is released not pressed. You may ask why not programme it when the key is pressed instead of released? Wouldn’t that make more sense? Yes, it would but there is a problem though, players can press and hold the space key to spam thousands of bullets on the screen. By programming it in the release event we short that problem out so they need press and release space key again to fire 1 bullet. Let’s take a closer look at what is going on with this code inside the space release event.

First the code will clear the items from inside the items to remove list. Remember this list will help optimise the code and the game as it will take the expired rectangles out of the game. With each space key press, we need to clear the list from inside this way it doesn’t get too big as the game goes on.

The code then will make new rectangles as we press and release the space key. This new rectangle will have its own properties inside the curly brackets { …. }. Each new bullet rectangle will have a ag called bullet, height 20 pixels, width 5 pixels, white background colour and red border colour.

After the bullet rectangle is created, we will then give the x and y axis location for the bullet. We are doing this by accessing the canvas top and canvas left position inside the code. Canvas.SetTop(newBullet, Canvas.GetTop(player1) – newBullet.Height); this line is setting the bullet right on top of the player object.

Canvas.SetLeft(newBullet, Canvas.GetLeft(player1) + player1.Width / 2); this line will place the x axis of the bullet right in the middle of the player. So it will look like the player is firing the bullet from the cannons which are placed in middle of the image.

Last line of this function is adding this object to the canvas so its visible when we are playing the game.

Go to page 4 to start making the enemy maker function

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