WPF C# Tutorial – Create a Flappy Bird Game in Visual Studio

Adding Instructions to Functions for Flappy Bird Game

In this part of the tutorial we will show you what instruction we want to put for the functions and events in this game. We have added the variables and done the empty functions so far and now we will be adding instructions for the program to do. In this page we will look at how to code the start game function, main window function and key up/down events.

First lets start with public MainWindow() function. this function will run when the window loads and its part of the WPF C# default programming. We are going add our own instructions inside of it so we can get the game loaded in its proper state when the main window loads up.

        public MainWindow()
        {
            InitializeComponent();

            // set the default settings for the timer
            gameTimer.Tick += gameEngine; // link the timer tick to the game engine event
            gameTimer.Interval = TimeSpan.FromMilliseconds(20); // set the interval to 20 miliseconds

            // run the start game function
            startGame();

        }

 

Inside the main window function, we have 3 instructions. First one is linking the game timer tick event to the gam engine event we’ve created. Setting the game timer interval to trigger every 20 milliseconds and final running the start game function.

Canvas Key is Down Event

This function will trigger when the user presses a key on the keyboard while the application is running. We only want two keys to be pressed for this game it’s the space and R key. The space key will be used to jump the flappy bird and the R key will be used to restart the game when its over so they can try it again.

        private void Canvas_KeyisDown(object sender, KeyEventArgs e)
        {
            // if the space key is pressed
            if (e.Key == Key.Space)
            {
                // rotate the bird image to -20 degrees from the center position
                flappyBird.RenderTransform = new RotateTransform(-20, flappyBird.Width / 2, flappyBird.Height / 2);
                // change gravity so it will move upwards
                gravity = -8;
            }
            if (e.Key == Key.R && gameover == true)
            {
                // if the r key is pressed AND game over boolean is set to true
                // run the start game function
                startGame();
            }
        }

 

Inside this function first if statement is checking IF the key pressed in SPACE key then we can rotate the flappy bird -20 degrees so it looks up when its jumping.

flappyBird.RenderTransform = new RotateTransform(-20, flappyBird.Width / 2, flappyBird.Height / 2);

This line above is first checking for the flappy bird IMAGE we added to the canvas which has a Render Transform property inside of it, this property is used to rotate an object. Inside the rotate transform property first option is for the angle degrees so you can say 180 degrees or 50 degree or anything else long as its within 360. After that we need to tell where the centre of this object is in this case, we are dividing the flappy bird image by 2 to get the centre of the rotation.

Gravitity = -8; this line will reverse the gravity for the flappy bird so when the space bar is pressed it will move up instead of moving down.

The second if statement is checking if the R key is pressed AND (&&) if game over Boolean is set to true. This if statement is checking for two conditions and both of them will have to be true in order to make it run the instructions from within. If they are both true then we can run the start game function.

Canvas Key is Up event

This event will trigger when they keys are released. We want the bird to return to its original position when the space key is released and we want to simulate the gravity as normal again.

        private void Canvas_KeyisUp(object sender, KeyEventArgs e)
        {
            // if the keys are released then we will change the rotation of the flappy bird to 5 degrees from the center
            flappyBird.RenderTransform = new RotateTransform(5, flappyBird.Width / 2, flappyBird.Height / 2);
            // change the gravity to 8 so the bird will go downwards and not up
            gravity = 8;
        }

Inside of this event we are setting the rotation to looking down for the flappy bird. It’s the same render transformation and rotate transform property where we are setting the flappy bird to 5 degrees (looking slightly down) and centre from height and centre from width by dividing the original image by 2.

Gravity = 8; this line resetting the gravity to the bird show be going downwards in the game.

Start Game Function

This function will help us load all of the components such as score, pipe locations, bird location and the timer. Its really a good practice to have them in a single function this way its easier to program the game restart features.

        private void startGame()
        {
            // this is the start game function 
            // this function will load all of the default values to start this game

            // first make a temp integer with the value 200
            int temp = 200;

            // set score to 0
            score = 0;
            // set the flappy bird top position to 100 pixels
            Canvas.SetTop(flappyBird, 100);
            // set game over to false
            gameover = false;

            // the loop below will simply check for each image in this game and set them to their default positions
            foreach (var x in MyCanvas.Children.OfType<Image>())
            {
                // set obs1 pipes to its default position
                if (x is Image && (string)x.Tag == "obs1")
                {
                    Canvas.SetLeft(x, 500);
                }
                // set obs2 pipes to its default position
                if (x is Image && (string)x.Tag == "obs2")
                {
                    Canvas.SetLeft(x, 800);
                }
                // set obs3 pipes to its default position
                if (x is Image && (string)x.Tag == "obs3")
                {
                    Canvas.SetLeft(x, 1000);
                }
                // set the clouds to its default position
                if (x is Image && (string)x.Tag == "clouds")
                {
                    Canvas.SetLeft(x, (300 + temp));
                    temp = 800;
                }

            }
            // start the main game timer
            gameTimer.Start();

        }

Lets explain what is happening in this function. First we are creating a local integer called temp. this integer will help us place the cloud images far from each other and achieve that sweet parallax scrolling effect for this game. This temp integer has a value of 200 for now.

Score = 0; this line is resetting the score variable back to 0 when the game will start.

Canvas.SetTop(flappyBird, 100); in this line we are resetting the flappy bird image to 100 pixels from top of the screen. We want it to be ready when the game starts.

Gameover = false; this line is setting the Boolean game over back to false because when this function runs the game will have started so it needs to be false.

After that we have our game loop to set all of the pipes and clouds for the game.

foreach (var x in MyCanvas.Children.OfType<Image>())

this line above is running a for each loop for every component in the My Canvas element. We want to specifically look for Image objects so we are first creating a temporary variable called x that will save the objects inside of it so we can give it instructions on what we want to do.

// set obs1 pipes to its default position

if (x is Image && (string)x.Tag == "obs1")

{

Canvas.SetLeft(x, 500);

}

 

In the if statement above, the code is checking if X variable is a Image type AND it has a tag called obs1 then we need to set that x meaning the first group of pipes to 500 pixels from the left of the screen. We are doing this because when the game starts we want the pipes to move towards left of the screen. We are doing kind of same thing for the obs2 and obs3 except we are setting them further from the first pipe so they don’t overlap.

// set the clouds to its default position

if (x is Image && (string)x.Tag == "clouds")

{

Canvas.SetLeft(x, (300 + temp));

temp = 800;

}

 

In the if statement above its check is X is a type of Image and x has a tag called clouds. If both of these conditions are true then we can move those clouds across the screen. First thing to remember here is that we have two cloud objects with the same tag so we don’t want them to be on the same position as the other one so we will have to do some clever programming here. We will use the temp local integer we created earlier for this if statement. When the program loops first it will find the first clouds image and it will set it to 300 + 200 <- the original value of the temp so the first cloud image will be set to 500 pixels from the left, when it loops again to find the second cloud we are setting the temp to 800 so it will take the 300 + 800 <- the new value of temp integer and apply it to the second cloud. So the second cloud image will be positioned at 1100 pixels from left of the screen.

gameTimer.Start(); This last line is starting the main game timer so everything will be moving around.

Go to Page 6 to see the main game engine event and its code explanations.




2 responses to “WPF C# Tutorial – Create a Flappy Bird Game in Visual Studio”

  1. Дарья Марахова says:

    Thank you very much from Russia! You are amazing web-teacher!) I loved it!

  2. jwnolan says:

    I had some trouble because I named my project something else, but once I fixed that it worked great! Great tutorial!