WPF C# Tutorial – Create a save the presents item drop down game in visual studio

Drop item timer event for the item drop down game

In this section we will explore the drop down timer for this game. this event is linked to the main timer and it will help us spawn and remove objects from the canvas. Lets take a look at how it all works so far.

        private void dropItems(object sender, EventArgs e)
        {
            ScoreText.Content = "Caught: " + score; // link score label to score integer
            missedText.Content = "Missed: " + missed; // link missed label to missed integer

            // if the current image is less than max item which is 5
            // if there is less than 5 items in the screen 

            if (currentItems < maxItem)
            {

                makePresents(); // run the make presents function
                currentItems++; // add 1 to the current items
                itemstoremove.Clear(); // clear the items to remove list
            }

            // now we need to tell the game what to do with the items thats on the screen e.g. Rectangles
            // run a loop to check how many rectangles there are on the screen and organise them in the x variable

            foreach (var x in myCanvas.Children.OfType<Rectangle>())
            {
                // check if x has a tag of drops
                if ((string)x.Tag == "drops")
                {
                    // if it does then do the following

                    int dropThis = r.Next(8, 20); // new integer called dropThis generates a random number between 8 and 20
                    // set the x's speed to drop this
                    Canvas.SetTop(x, Canvas.GetTop(x) + dropThis);

                    // make two new Rect objects link one to the player and one to the items
                    // this will be used to check for collision between the player and the presents
                    Rect items = new Rect(Canvas.GetLeft(x), Canvas.GetTop(x), x.Width, x.Height);
                    Rect playerObject = new Rect(Canvas.GetLeft(player1), Canvas.GetTop(player1), player1.Width, player1.Height);


                    //if player object collides with items

                    if (playerObject.IntersectsWith(items))
                    {
                        // add the item to the items to be removed list
                        itemstoremove.Add(x);
                        // deduct 1 from the current items list
                        currentItems--;

                        // add 1 to the score
                        score++;
                    }
                    else if (Canvas.GetTop(x) > 700)
                    {

                        // if the player missed the item and its gone passed 700 pixels from the main window
                        // add the item to the removed list
                        itemstoremove.Add(x);
                        // deduct 1 from the current items
                        currentItems--;
                        // add 1 to the missed integer
                        missed++;
                    }

                }


                // if the player missed more than 6 items
                if (missed > 6)
                {
                    // stop the main game timer
                    GameTimer.Stop();
                    // show a message box that says you lost click OK to try again
                    MessageBox.Show("You Lost" + Environment.NewLine + " Click OK to try again !");

                    // then run the reset game function
                    resetGame();
                }

            }

            // removing its from the scene
            // check how many rectangles are in the items move list
            // remove them from the list using the for each loop

            foreach (Rectangle y in itemstoremove)
            {
                myCanvas.Children.Remove(y);
            }
        }

This event is linked to the game timer, with each tick on the timer this function will run and check everything from inside. We set the timer to tick every 20 milliseconds so each time it ticks it will run all of the instructions from inside this event.

ScoreText.Content = "Caught: " + score; // link score label to score integer

missedText.Content = "Missed: " + missed; // link missed label to missed integer

These two lines are setting the score text label with the score integer and missed text label to the missed integer.

if (currentItems < maxItem)

{

makePresents(); // run the make presents function

currentItems++; // add 1 to the current items

itemstoremove.Clear(); // clear the items to remove list

}

This if statement is checking if the currentItems integer has less value than the max items integer, if this is true it will run the make presents function which creates the presents rectangles and add 1 to the current items and it will also clear any items inside the items to remove LIST we created in the beginning of the program.

// now we need to tell the game what to do with the items that’s on the screen e.g. Rectangles
// run a loop to check how many rectangles there are on the screen and organise them in the x variable
            foreach (var x in myCanvas.Children.OfType<Rectangle>())
            {
                // check if x has a tag of drops
                if ((string)x.Tag == "drops")
                {
                    // if it does then do the following
                    int dropThis = r.Next(8, 20); // new integer called dropThis generates a random number between 8 and 20
                    // set the x's speed to drop this
                    Canvas.SetTop(x, Canvas.GetTop(x) + dropThis);
                    // make two new Rect objects link one to the player and one to the items
                    // this will be used to check for collision between the player and the presents
                    Rect items = new Rect(Canvas.GetLeft(x), Canvas.GetTop(x), x.Width, x.Height);
                    Rect playerObject = new Rect(Canvas.GetLeft(player1), Canvas.GetTop(player1), player1.Width, player1.Height);
                    //if player object collides with items
                    if (playerObject.IntersectsWith(items))
                    {
                        // add the item to the items to be removed list
                        itemstoremove.Add(x);
                        // deduct 1 from the current items list
                        currentItems--;
                        // add 1 to the score
                        score++;
                    }
                    else if (Canvas.GetTop(x) > 700)
                    {
                        // if the player missed the item and its gone passed 700 pixels from the main window
                        // add the item to the removed list
                        itemstoremove.Add(x);
                        // deduct 1 from the current items
                        currentItems--;
                        // add 1 to the missed integer
                        missed++;
                    }

                }

                // if the player missed more than 6 items
                if (missed > 6)
                {
                    // stop the main game timer
                    GameTimer.Stop();
                    // show a message box that says you lost click OK to try again
                    MessageBox.Show("You Lost" + Environment.NewLine + " Click OK to try again !");

                    // then run the reset game function
                    resetGame();
                }
            }

This whole section is running a loop. A for each loop can run to check if a certain object exists in the canvas and if we find we can do various actions with it. In this one we are first looking rectangles in this canvas and saving that information inside the X variable we create with the for each loop declaration. Then we are checking IF x has a tag called drops if this is true it means we found the presents in the canvas.

After that we are creating a local integer called dropThis and it will contain a random number between 8 and 20. This integer will be used to set the speed of the presents. We are animating the presents rectangles by using Canvas.SetTop(x, Canvas.GetTop(x) + dropThis); line. This line may look familiar to you because we have used it before in make the presents functions. This line is going to find x which we have linked to the presents rectangles before and calculate the top position of it and add the speed from drop this integer, so it will continuously go down as the timer will be running.

We need to check if the player image is colliding with the presents image. To do this we are creating two Rect Objects and linking the rectangles to them. If you look at the line of code, we are stating Rect Items and Rect Player and inside those Rect properties we are giving the presents x loop information and player rectangle information. These will be saved in the memory and now we can check weather these two objects are overlapping each other. Finally, we can check if player object intersects with item then we can add the item to the items to remove list, reduce 1 from the current object because this object will be removed and add 1 to the score because we would have a caught the present.

We also need to check if we miss an object, to do this we are checking if the x objects top goes beyond 700 pixels meaning it has reach end of the window if this is true we can then add that x to the items to remove list, reduce 1 from the current items and add 1 to missed integer.

In the last part we have single if statement, in this one we are checking if the player missed more than 6 presents then we can end the game, stop the game timer, show a message box that says you lost, click ok to try again and then run the reset game function. This will run the reset function close the current window and open another window for the player to try it again.

That’s the whole loop, everything inside of needs to stay inside the represented curly brackets.

// removing its from the scene
// check how many rectangles are in the items move list
// remove them from the list using the for each loop

foreach (Rectangle y in itemstoremove)
{
myCanvas.Children.Remove(y);
}

This part is the main garbage collector, anything we add into this item to be removed list will be removed from the canvas i.e the app. So, we are running another for each loop this time we are checking if there are any rectangles in the items to remove list and if there are any, we can remove them from the canvas. Without this we can end up thousands of active rectangles in the app which will use a lot of memory and slow down the system even if its runs for long enough.

With all of that done lets run the game

mooict wpf c# save the presents game - start the debugging process to compile and run the game

Click on that start icon in the tool bar and it will run the app.

mooict wpf c# save the presents game screen for playing the game showing the score and missed numbers on screen mooict wpf c# save the presents game lost screen and showing the message box when you missed more than 6 items

Its working and it also reload the game when you click on in the message box. That’s awesome. If you managed to follow it so far well done, if there are any errors double check with the source code here and make sure you spelled them correctly.

Go to page 4 for the full source code




Comments are closed.