An Ultimate Guide That Helps You Build C# Game Programming

This C# game programming tutorial will show you how to use Visual Studio to create a run T Rex endless runner game using the C# programming language. You may have encountered this simple game while browsing the Google Chrome offline page. This game was designed for educational purposes, and hopefully you enjoy it while learning something new. You will use the Visual Studio 2019 version to create this game using the C# programming language.

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

In Visual Studio, please create a new Windows application project called T Rex Endless Runner and name it T Rex Endless Runner.

C#-game-programming-1

C_sharp_Game_Programming_1_2.

Go to the properties.

C_sharp_Game_Programming_1_3.

Window in the new form and make the changes listed below.

game-programming-3.

C#game-programming-4

This is how the form should look.

C#-game-programming-7.

Now in this C# game programming tutorial, you will need four picture boxes, one label, and a game timer for this game.

Following the C# game programming, start with the four picture boxes. Locate the toolbox, which is usually pinned to the left side of the screen. If you can't find it, go to View and click on the ToolBox.

Learn the Ins & Outs of Software Development

Caltech Coding BootcampExplore Program
Learn the Ins & Outs of Software Development

Timer and Picture Boxes

This is the picture box icon; drag it to the form.

C#-game-programming-5

This is the first picture box you have made. Now, go ahead and experiment with some settings in the properties window.

Examine the properties window while the picture box is selected.

C#-game-programming-6

This is how the picture box should look after all the options have been applied. This picture box will serve as the game's floor or ground, as you may have guessed.

C#-game-programming-8.

Change the following options in the properties window of another picture box.

Dprogramming-10.

Collision of Objects With Picture Boxes.

Right-click on the image and select ‘choose image’. Click on import under the project resource file to open the image selector dialogue box. Select all the images you downloaded and press the open button. There are four images in total, so import them all at once.

Dprogramming-9

Click OK after selecting the running image. Two more picture boxes are required.

Dprogramming-11

C#game-programming-13

Learn the Ins & Outs of Software Development

Caltech Coding BootcampExplore Program
Learn the Ins & Outs of Software Development

This is the label's final appearance. Score: 0

-game-programming-label.

Insert a timer into the form now, add a timer to the form by dragging it there.

C#game-programming-14

Jump Simulation

In the timer properties, make the following changes. Change the name to gameTimer, enable it to be true, and set the interval to 20.

C#game-programming-interval.

While it sets the time, click the lightning bolt icon in the properties window. This will open the events window to add an event for the timer. Enter MainGameTimerEvent as the search term. This will take you to the code; for the time being, return to the design view; you still need to add two more events to this game.

C#game-programming-event

Key Down and Key Up Events 

After you click on the form, the events window will change, and you will now find the key down and key up events. Enter “keyisdown” for the key down event and “keyisup” for the key up event.

C#game-programming-event1

Learn the Ins & Outs of Software Development

Caltech Coding BootcampExplore Program
Learn the Ins & Outs of Software Development

So far in this project, this is the code view.

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows.Forms;

namespace T_Rex_Endless_Runner

{

    public partial class Form1 : Form

    {

        bool jump = false;

        int jumpingSpeed;

        int frc = 12;

        int scoreofthegame = 0;

        int obstSpeed = 10;

        Random random = new Random();

        int pos;

        bool isgameover = false;

        public Form1()

        {

            InitializeComponent();

            ResetGame();

        }

        private void MainGameTimerEvent(object sender, EventArgs e)

        {

            trex.Top += jumpingSpeed;

            txtScore.Text = "Score = " + scoreofthegame;

            if (jump == true && frc < 0)

            {

                jump = false;

            }

            if (jump == true)

            {

                jumpingSpeed = -12;

                frc -= 1;

            }

            else

            {

                jumpingSpeed = 12;

            }

            if (trex.Top > 366 && jump == false)

            {

                frc = 12;

                trex.Top = 367;

                jumpingSpeed = 0;

            }

            foreach(Control t in this.Controls)

            {

                if (t is PictureBox && (string)t.Tag == "obstacle")

                {

                    t.Left -= obstSpeed;

                  if (t.Left < -100)

                    {

                        t.Left = this.ClientSize.Width + random.Next(200, 500) + (t.Width * 15);

                        scoreofthegame++;

                    }

                    if (trex.Bounds.IntersectsWith(t.Bounds))

                    {

                        gameTimer.Stop();

                        trex.Image = Properties.Resources.dead;

                        txtScore.Text += " Press T to restart the game";

                        isgameover = true;

                    }

                }

            }

            if (scoreofthegame > 5)

            {

                obstSpeed = 15;

            }

        }

        private void keyisdown(object sender, KeyEventArgs e)

        {

            if (e.KeyCode == Keys.Space && jump == false)

            {

                jump = true;

            }

        }

        private void keyisup(object sender, KeyEventArgs e)

        {

            if (jump == true)

            {

                jump = false;

            }

            if (e.KeyCode == Keys.T && isgameover == true)

            {

                ResetGame();

            }

        }

       private void ResetGame()

        {

            frc = 12;

            jumpingSpeed = 0;

            jump = false;

            scoreofthegame = 0;

            obstSpeed = 10;

            txtScore.Text = "Score: " + scoreofthegame;

            trex.Image = Properties.Resources.running;

            isgameover = false;

            trex.Top = 367;

            foreach (Control t in this.Controls)

            {

                if (t is PictureBox && (string)t.Tag == "obstacle")

                {

                    pos = this.ClientSize.Width + random.Next(500, 800) + (t.Width * 10);

                    t.Left = pos;

                }

            }

            gameTimer.Start();

        }      

    }

}

Learn the Ins & Outs of Software Development

Caltech Coding BootcampExplore Program
Learn the Ins & Outs of Software Development

Data Types, Integers, Booleans, and Strings

Now in this C# game programming tutorial, you will look at the definition of all the variables you used in this code:

  • Bool jump = false; / boolean to determine whether the player is jumping.

This is a Boolean expression known as jumping. This Boolean will be used to determine whether or not the T Rex has entered the game. You can only toggle between true and false.

  • jumpingSpeed = 10; / Set the jump speed with an integer.

This integer is referred to as jump speed. This will have a value of ten. The T Rex will jump 10 pixels from its current location and use the jump speed as gravity to pull the player down.

  • int frc = 12; / Integer representation of the jump's force.

This integer called force will be used to determine how quickly the T Rex jumps up and how high he can jump before collapsing.

The Score of the Game

  • int scoreofthegame = 0; / set the default score integer to 0

This integer will keep track of the game's score. Each time an obstacle successfully exits the form without colliding with the player, one is added to this integer.

  • int obstSpeed = 10; / the obstacles' default speed

The obstacles will be animated using this integer. This will draw the obstacles to the left of the screen, closer to the player.

  • random = random and = new Random(); / construct a new random class

This random number generator, known as rnd, will be used to calculate a random location for obstacles to spawn once the game begins and when they reach the far left of the screen.

In Visual Studio.NET C# or VB.NET, the InitializeComponent() method is a method that is automatically created and managed by the Windows Forms designer and defines everything you see on the form. When you run the app (or open the form in VS.NET), the code creates and configures controls in the same way that you did in the designer.

The main function of the form calls the reset function. This essentially means that you are instructing the reset function to execute when the game begins. This is the game's empty reset function. You will return to it later to add some instructions.

The game event that is linked to the main game timer event is shown above. Input all of the code from within it. 

Add the following to the “keyisdown” function.

In this function, you check if the space key is pressed, and if jumping equals false, you set jumping back to false. It may appear simple, but you are triggering the jump function, which will be used later in the timer event.

In the “keyisup” function, enter the following.

First, you must check if the “T” key is pressed and released, then you run the game reset function. Also, you need to check if jumping is true, then you can change jumping back to false.

Learn the Ins & Outs of Software Development

Caltech Coding BootcampExplore Program
Learn the Ins & Outs of Software Development

Game Reset Function

The reset function is shown below. Overall, this function will reset every variable, player, and obstacle in the game. It will activate this function when the game first loads and when the player presses the “T” button.

In this C# game programming, to begin building and running the game, click the start button. The game's final screenshot is below.

C#game-programming-outut

C#-game-programming-output2

C#game-programming-output1.

Now that you have reached the end of the C# game programming article, you will sum up everything you covered in this tutorial.

Next Steps 

You attempted to build a Trex endless runner game in visual studio using windows forms in this C# game programming tutorial. You defined force, interval, jumping speed, and position using variables. Following that, you used some events to build this Trex endless game, such as the main game timer event, the key is up and the key is down, as shown in the Trex runner code.

This is the path for you if you want to go beyond Mobile and Software Development and gain knowledge of the most in-demand programming languages and skills today. In that case, Simplilearn's Full Stack Developer - MERN Stack Course is a good fit. Look into this well-known bootcamp program for more information.

Do you have any comments or questions about this C# Game Programming tutorial? Please leave them in the comments section at the bottom of this page if you do. Our experts will gladly respond to your questions as soon as possible!

About the Author

Ravikiran A SRavikiran A S

Ravikiran A S works with Simplilearn as a Research Analyst. He an enthusiastic geek always in the hunt to learn the latest technologies. He is proficient with Java Programming Language, Big Data, and powerful Big Data Frameworks like Apache Hadoop and Apache Spark.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, OPM3 and the PMI ATP seal are the registered marks of the Project Management Institute, Inc.