C# Tutorial – Create a Football Penalty Shootout game in visual studio

In this tutorial we will create a football penalty shootout game in visual studio using c# programming language. In this game you are able to click on a selective targets around the goal post and as you select one it will shoot the football towards it. The goal keeper has its own independent movements and he can block your goals from being made. The overall structure of the game is simple and easy to understand.  We are creating this tutorial in Visual Studio 2017 using the Windows Form application and C# programming language. Make sure you download the game assets from the link in this tutorial page to follow along.

Lesson Objectives –

  1. Create a football penalty shootout game in visual studio using c#
  2. Create click events using picture boxes
  3. Create goal keeper movements using lists and strings
  4. Using a timer object to animate the ball and the goal keeper
  5. Using image sprites and changing the goal keepers state within the game
  6. Using various data types such as Integers, Booleans, Strings and List to make the game work
  7. Using windows form components such as Picture Boxes, Timers and Labels to complete the game

Project Preview

Download the Football Penalty Shootout Game images here

Below are the resources we are going to be using for this game

This is the background of the game
This is the football
This is the target icon, this will be placed in 5 different areas around the penalty bar.
This is the goal keeper stand sprite
This is the goal keeper saving right
This is the goal keeper saving left
This is the goal keeper saving top left
This is the goal keeper saving top right
This is the goal keeper saving top

Start a new project in Visual Studio, call it Football Penalty Shootout Game, make sure you have picked the windows form application and click OK.

In the form Properties change the size of the form to 915, 717 and change the text to “Football Penalty Shootout Game”.

In the same properties window find the background image and click on the 3 dotted button.

Once you clicked on it you will see this box, Click on the import button under the project resource file.

Now browse to the assets you downloaded from MOOICT, select them all and click OK.

From the resource selection window find the background image and click OK.

In the properties window under the background image, there is an option called background image layout, choose NONE from the drop down menu. We don’t want the background to have any effects in this game.

From the tool box drag and drop a picture box.

Right click on the picture box and click on Choose Image.

Select the target image from the resource selection window.

In the properties window for the picture box change the background colour to yellow.

In the same properties window change the name to topleft (no spaces) size to 40, 38, Size Mode to Stretch image and tag to “topLeft”. The tag is important and make sure you do not add any space and carefully place the capital letter in it Make sure its all as this tutorial.

The reason this has a tag of top left is because its placed on the top left of the goal post. Now you can copy and paste this picture to match the layout below.

Now that the goal aims are done, add another picture box to the form, once again right click on the picture box and pick the stand-small image from the resource selection window.

<– Pick the stand-small image for the new picture box

For this new picture box change the following in the properties window

Name: goalKeeper

Back Colour: Transparent

Location: 426, 174

Size Mode: Auto Size

Add another picture box to the form, right click on the picture box and from the resource selection window choose the football image and click OK.

Change the following for this new picture box in the properties window

Name: football

Back Colour: Transparent

Location: 431, 515

Size Mode: Auto Size

Recap- We set up the background, the goal post targets, the goal keep and the football. To complete the User interface of the game we need to add 2 labels.

Drag and drop two labels on the form.

Click on Label 1 and lets change some settings in its properties window.

Name: missText

Back Colour: Transparent

Font: Bold Size 14

Fore Colour: White

Location: 12, 16

Text: Miss: 0

<– Final Result

Now click on the label 2 and change the following in the properties window

Name: goalText

Back Colour: Transparent

Font: Bold Size 14

Fore Colour: White

Location: 800, 16

Text: Goal: 0

<– Final Result

Drag and drop two timers to the form.

They should look like this when they are dropped to the form. Click on the Timer 1 and lets change few things in its properties.

change the name to keeperTimer and interval to 20. Leave the rest as is. Now click on the timer 2 and change the following in its properties

Change the name to ballTimer and interval to 20.

<– Click on the little lightning bolt icon on the properties window while you have the ballTimer selected.

In this box type in shootball and press enter. This will take you over to the code view, come back to the design view we need add more events for this game.

Click on the keeper time and go to the events window by clicking on the small lightning bolt icon.

Inside the tick event type moveKeeper and press enter.

Come to the design view for our last event.

HOLD CTRL KEY and CLICK on all of the target picture boxes.

You can select multiple objects in visual studio. Make sure that you have only selected all of the target picture boxes. Now if you look at the events window for all of them you can find a click event from the list.

In the click event type in setTarget and press enter.

Now we have added the 3 events that we need for this game.

Now lets take a look at how the code view is looking thus far.

Start Coding

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 Football_Penalty_Shootout_Game
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void shootball(object sender, EventArgs e)
        {

        }

        private void moveKeeper(object sender, EventArgs e)
        {

        }

        private void setTarget(object sender, EventArgs e)
        {

        }
    }
}

This is what the code view should look like for you now, we are going to add the variables and functions we need for the game first.

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 Football_Penalty_Shootout_Game
{
    public partial class Form1 : Form
    {

        Random rnd = new Random(); // creating a random number generator

        // this is the list of the goal keeper positions saved as strings
        List<string> keeperPosition = new List<string> { "left", "right", "topsave", "topleft", "topright" };

        int ballX = 0; // this is the ball horizontal position
        int ballY = 0; // this is the ball vertical position

        string state; // this string will save the state which the goal keeper is currently on

        string playerTarget; // this string will save the players current target

        bool aimSet = false; // this is the aim set boolean

        int goal; // this will save the amount of goals we scored
        int miss; // this will save the amount of goals we missed

        public Form1()
        {
            InitializeComponent();
        }

        private void shootball(object sender, EventArgs e)
        {

        }

        private void moveKeeper(object sender, EventArgs e)
        {

        }

        private void setTarget(object sender, EventArgs e)
        {

        }

        private void checkScore()
        {

        }

        private void changeState()
        {

        }
    }
}

Add the highlighted code in the code view, all the codes are explained in the comments, make sure you type them in there as well which will help understand the code further. The first list of highlighted code above are the variables for the game, we have a random number generator, list of strings, integers, strings and a Boolean. All of these variable help us make this game work. Make sure you have inserted them clearly and accurately. In the bottom of the code view you will see the two highlighted empty functions called checkScore and changeState both of these function are empty right now but we will show you the code to include inside them. The main thing to note down right now is to do this code in the right order.

Shoot Ball Event

        private void shootball(object sender, EventArgs e)
        {
            //in this event we will check which aim was clicked and where the ball has landed

            football.Left -= ballX; // linking the football left to ballx integer
            football.Top -= ballY; // linking the football top to bally integer

            //below is the big if statement, this is checking all the 5 conditions
            // if the ball is selected to hit a target and it reaches that target
            // then we can reset the ball back to the starting position

            if (football.Bounds.IntersectsWith(right.Bounds) && playerTarget == "right"
                || football.Bounds.IntersectsWith(topright.Bounds) && playerTarget == "topRight"
                || football.Bounds.IntersectsWith(top.Bounds) && playerTarget == "top"
                || football.Bounds.IntersectsWith(left.Bounds) && playerTarget == "left"
                || football.Bounds.IntersectsWith(topleft.Bounds) && playerTarget == "topLeft"

                )

            {
                football.Left = 431; // set the balls left to this position
                football.Top = 500; // set the balls top to this position
                ballX = 0; // 0 to the ball x speed
                ballY = 0; // 0 to the bally speed
                aimSet = false; // set aim back to false
                ballTimer.Stop(); // stop the ballTimer

            }
        }

Above is the shoot ball event. This event will run when the ballTimer is activated. in the beginning of the event we have football.Left -= ballx and football.Top -= bally, this line links the football to the ballx and bally variables. When the numbers change within those variables the ball will follow those numbers. For example if the ballx is -1 the will move towards the left of the screen and if its 1 then it will move towards right of the screen, same is applied to the vertical y position.

Next is the big If statement. In side of if statement we are able to call multiple statements and we are also able to add anything we want to them as along they return a true or false value.

IF(ball moving left AND ball collides with the left picturebox)

{

If the statements are true then we can add more instructions in here such as move the ball back to the default position and reset the ballx and bally variables, set aim to false and stop the timer.

}

Now we have 5 different aim points good thing in programming we are able to use multiple statements inside of one if statement.

IF(ball moving left AND (&&) ball collides with the left picturebox

OR (||) ball moving right AND (&&) ball collides with the right picturebox

OR (||)ball moving top AND (&&) ball collides with the top picturebox

.. And so on

)

{

If the statements are true then we can add more instructions in here such as move the ball back to the default position and reset the ballx and bally variables, set aim to false and stop the timer.

}

By using the || symbol we are able tell the program that if the first statement isn’t true, then try another to see if that matches the condition. This way we can go over all the 5 targets and then stop the ball when it reaches its destination ready to played again.

Move Keeper Event

Below is the move keeper event, this event is kind of long so as you are following it through make sure you follow the brackets and symbols accordingly. This event will move the goal keeper to the directed state it’s in. The logic behind this event is we save the goal keepers state in the state string, when the data inside that string changes we move the goal keeper accordingly. All the codes are explained in the comments.

private void moveKeeper(object sender, EventArgs e)
        {
            // this is the timer that animates the goal keeper
            // below is the switch statement which will check where the goal keeper will go
            // so we can animate him accordingly
            switch (state)
            {
                case "left":
                    // if the state is left
                    // if the goal keeper picture box is position greater than 192 from the left
                    if (goalKeeper.Left > 192)
                    {
                        // then we animate the goal keeper moving left to save the goal
                        goalKeeper.Left -= 6;
                        goalKeeper.Top = 209;
                    }
                    else
                    {
                        // else we reset the goal keeper back to the default position
                        goalKeeper.Left = 421;
                        goalKeeper.Top = 162;
                        goalKeeper.Image = Properties.Resources.stand_small;
                        keeperTimer.Stop();
                    }
                    break;
                case "right":
                    // if the state is right
                    // if the goal keeper picture box is position less than than 548 from the left
                    if (goalKeeper.Left < 548)
                    {
                        // then we move the goal keeper towards the right
                        goalKeeper.Left += 6;
                        goalKeeper.Top = 209;
                    }
                    else
                    {
                        // else we move the goal keeper back to default position
                        goalKeeper.Left = 421;
                        goalKeeper.Top = 162;
                        goalKeeper.Image = Properties.Resources.stand_small;
                        keeperTimer.Stop();
                    }
                    break;
                case "topleft":
                    // if the state is top left
                    // if the goal keeper picture box is position greater than 71 from the top
                    if (goalKeeper.Top > 71)
                    {
                        // then we move the goal keeper towards the left and the top
                        goalKeeper.Left -= 8;
                        goalKeeper.Top -= 3;
                    }
                    else
                    {
                        // else we move the goal keeper back to default position
                        goalKeeper.Left = 421;
                        goalKeeper.Top = 162;
                        goalKeeper.Image = Properties.Resources.stand_small;
                        keeperTimer.Stop();
                    }
                    break;
                case "topright":
                    // if the state is top right
                    // if the goal keeper picture box is position greater than 71 from the top
                    if (goalKeeper.Top > 71)
                    {
                        // then we move the goal keeper towards the top and right of the form
                        goalKeeper.Left += 5;
                        goalKeeper.Top -= 3;
                    }
                    else
                    {
                        // else we move the goal keeper back to default position
                        goalKeeper.Left = 421;
                        goalKeeper.Top = 162;
                        goalKeeper.Image = Properties.Resources.stand_small;
                        keeperTimer.Stop();
                    }
                    break;
                case "topsave":
                    // if the state is top save
                    // if the goal keeper picture box is position greater than 71 from the top
                    if (goalKeeper.Top > 71)
                    {
                        // then we move the goal keeper towards the top of the form
                        goalKeeper.Top -= 3;
                    }
                    else
                    {
                        // else we move the goal keeper back to default position
                        goalKeeper.Left = 421;
                        goalKeeper.Top = 162;
                        goalKeeper.Image = Properties.Resources.stand_small;
                        keeperTimer.Stop();
                    }
                    break;
            }
        }

Set Target mouse click event

This is the event that’s linked to all the target picture boxes. The reason we have used one event and 5 is because there are ways for us to find out which picture box sent the trigger for this event and then take accurate action based on that. By working this way we save time and redundant codes which we don’t need. So to keep things efficient lets take a look at this event.

To start off we need to make sure that players can’t multi click on the buttons this is why we start with the if(aimset) {return;} What this if statement does is when the aim set is false meaning when the ball is animating then we will not allow the player to click any other buttons and activate it. Until the aim set boolean is set back to false this event will not trigger again. Neat.

After that we are starting both ball timer and keeper timer because we want them both to animate when the player has chosen their target. After that the change state function will which is responsible for changing the goal keeper image.

var senderObject is a variable that will save information about who sent the trigger for this event, remember we have 5 different targets on the screen and we can’t shoot the ball at all of them so we need to know which one sent the trigger for this event. This is how we find it. var senderObject = (PictureBox) sender; tells the program exactly which picture box was clicked.

When we find the picture box then we will change the picture boxes background colour to white, just to give a feedback on the click event. Remember it’s a developers responsibility to let the users know when they have successfully interacted with the game such as giving some small feedback that their action was taken into account.

Then in this event we need to check the tag of each of these picture boxes clicked. The first one is if the sender object has a tag of topRight then we will move the ball towards the top right of the goal post. After that if the picture box clicked has a tag of right, then we move the ball towards the right of the goal post and so on. Each of the if statements have been commented in the code so please follow along carefully and make sure you do not miss out the curly brackets or the semi colons, it’s a common mistake just saying.

End of ALL of these if statement we finally run the check score function. This function will be explained next.

      private void setTarget(object sender, EventArgs e)
        {
            // this event is linked to all the aim picture boxes on the screen
            if (aimSet) { return; } // this if statement saves us from double clicking

            ballTimer.Start(); // start the ball timer
            keeperTimer.Start(); // start keeper timer

            changeState(); // run the change state function

            // this variable finds which picture box sent this event
            var senderObject = (PictureBox)sender;

            senderObject.BackColor = Color.Beige;

            //if the picture box click has the tag top right
            // then do the following
            if (senderObject.Tag.ToString() == "topRight")
            {
                ballX = -7; // change ball x to -7
                ballY = 15; // change the ball y to 15
                playerTarget = senderObject.Tag.ToString(); //change player target to the tag
                aimSet = true; // change aim set to true
            }

            //if the picture box click has the tag right
            // then do the following
            if (senderObject.Tag.ToString() == "right")
            {
                ballX = -11; // change ball x to -11
                ballY = 15; // change the ball y to 15
                playerTarget = senderObject.Tag.ToString(); //change player target to the tag
                aimSet = true; // change aim set to true
            }

            //if the picture box click has the tag top
            // then do the following
            if (senderObject.Tag.ToString() == "top")
            {
                ballX = 0; // change ball x to 0
                ballY = 20; // change the ball y to 20
                playerTarget = senderObject.Tag.ToString(); //change player target to the tag
                aimSet = true; // change aim set to true
            }

            //if the picture box click has the tag left
            // then do the following
            if (senderObject.Tag.ToString() == "left")
            {
                ballX = 7; // change ball x to 7
                ballY = 11; // change the ball y to 11
                playerTarget = senderObject.Tag.ToString(); //change player target to the tag
                aimSet = true;  // change aim set to true
            }

            //if the picture box click has the tag top left
            // then do the following
            if (senderObject.Tag.ToString() == "topLeft")
            {
                ballX = 8; // change ball x to 8
                ballY = 15; // change the ball y to 15
                playerTarget = senderObject.Tag.ToString(); //change player target to the tag
                aimSet = true; // change aim set to true
            }

            checkScore(); // run the check score function
        }

Check Score Function

Below is the check score function. As you remember from earlier this is the empty function we created earlier now we have all of the instructions to put in to it. First the function starts with a big if statement as we have seen before, this time we are checking if the goal keeper and the player picked the same target. If they have then we add 1 to the miss and show the miss text on the screen, else then goal keeper missed the ball and you have scored so we add 1 to the score and show the score on the goals label. This is a simple function, make sure you pay extra attention to the quotation marks and the OR || symbols in the if statement.

        private void checkScore()
        {
            // this function checks the score of the game
            // below is another big if statement this one is checking the following
            // IF the player and goal keeper picks the same position
            // then its a miss since the goal keeper will save it
            // else it will be a score
            if (state == "left" && playerTarget == "left"
                || state == "right" && playerTarget == "right"
                || state == "topsave" && playerTarget == "top"
                || state == "left" && playerTarget == "left"
                || state == "topleft" && playerTarget == "topLeft"
                || state == "topright" && playerTarget == "topRight"

                )
            {

                miss++; // if one of the conditions are met then we increase miss by 1
                missText.Text = "Missed: " + miss; // show the miss on the screen
            }
            else
            {
                goal++; // if the conditions are not met then we add 1 to the goals
                goalText.Text = "Scored: " + goal; // show the goals on the screen

            }
        }

Change State Function

This is the change state function, in this function we have put in the instruction to which direction the goal keeper is going to choose and when he does we will change the images accordingly. Now to begin we start the keeper timer.

Then we are creating an integer called i and within this integer we will randomly choose an item from the keeper position list we created early in this game, remember there are 5 different positions the goal keeper can go to, in computer the numbers always start 0 so we will have 0, 1, 2, 3, 4 to complete all the different positions saved inside that list. By using the random number generator we can make the game more dynamic so we don’t which direction the goal keeper will go.

the state string will hold the position we picked by using i integer in the line before, after that we need to run another switch statement to determine which was picked and what instructions to give the game next.

If the random number picked is 0 then we will change the goal keepers image to left, if the random number picked is 1 then we will change the goal keeper image to right image and so on and so forth. Each line of the code is commented so make sure that you are following it accurately.

        private void changeState()
        {
            keeperTimer.Start(); // start the keeper timer

            // below we are creating an integer called i
            // and it will random choose a position from the keeper position list
            int i = rnd.Next(0, keeperPosition.Count);

            // access the name of the position by using the to string function
            state = keeperPosition[i].ToString();

            // below is the switch statement that checks which position was picked
            // and with each position we will put the goal keepers picture
            switch (i)
            {

                case 0:
                    // 0 is the first position so it will be the left save image
                    // when 0 picked the program will pick the left image from the resources
                    goalKeeper.Image = Properties.Resources.left_save_small;
                    break;
                case 1:
                    // 1 is the second position it will show the right save image
                    // when 1 is picked the programing show the right save image from the resources
                    goalKeeper.Image = Properties.Resources.right_save_small;
                    break;
                case 2:
                    // 2 is the top saving position
                    // when 2 is picked the program will show the top saving image
                    goalKeeper.Image = Properties.Resources.top_save_small;
                    break;
                case 3:
                    // 3 is the top left saving position
                    // when 3 is picked the program will show the top left save image from resources
                    goalKeeper.Image = Properties.Resources.top_left_save_small;
                    break;
                case 4:
                    // 4 is the last position and its the top right save position
                    // when 4 is picked it will show the top right save image from the resources
                    goalKeeper.Image = Properties.Resources.top_right_save_small;
                    break;

            }
        }

Final Results- Click on the start button

Lets debug the program and see what’s it doing

The game works great, if you have encountered any errors, look back the code and see what’s missing. Well done following through thus far.

What we haven’t done but you should try to implement in the game, if the game you created is working right now you will notice that you can take as many shots as you want and game will play it all, there is no game ending script in place. Hmm now think where you can put that how can you limit the amount the player plays before they win or lose the game. It’s not very difficult you can do it. Moo out.

 

 




5 responses to “C# Tutorial – Create a Football Penalty Shootout game in visual studio”

  1. Tr says:

    Coming from a C, C++ background, I would love to be able to copy/paste simple elements of this and learn contiguously without having to write simple things.

  2. jason man says:

    why does he fly

  3. Siddharth says:

    An Object reference is required for the non-static field, or property ‘Control.Left’
    same for the top
    and
    Form1 does not contain a definition for Image

  4. Taussig David Laszlo says:

    Hello , I have a problem. I made that game for a project and it didnt worked.Please can u help me? I have 28 errors , but all errors is essentially one error. “Picturebox does not contain a definition for “left” and no accessible extension method “left” accessing a first argument of type ‘PictureBox’ could be found(are u missing a using directive or an assembly reference?”

  5. Anhar Ali says:

    Hi, you should use Left with a capital L. C# is case sensitive.