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

Mouse-Move Event

        private void Canvas_MouseMove(object sender, MouseEventArgs e)
        {
            // Get the x and y coordinates of the mouse pointer.
            System.Windows.Point position = e.GetPosition(this);
            double pX = position.X;
            double pY = position.Y;

            // Sets the Height/Width of the circle to the mouse coordinates.
            Canvas.SetLeft(player1, pX - 10);

            // if the player is positioned less than 260 pixels
            // we will set the net to the left image

            if (Canvas.GetLeft(player1) < 260)
            {
                playerImage.ImageSource = new BitmapImage(new Uri("pack://application:,,,/images/netLeft.png"));
            }

            // if the olayer positioned more than 260 pixels
            // we will set the net to the right image
            if (Canvas.GetLeft(player1) > 260)
            {
                playerImage.ImageSource = new BitmapImage(new Uri("pack://application:,,,/images/netRight.png"));
            }
        }

For this game there is two player image one image is facing left netLeft and one for the right netRight. Want we want to do is when the player is moving towards the left show the left facing image and show the right facing when moving towards the right. Once of the solutions we came up with is have space in the middle let’s say 260 pixels so if the player position Is less than 260 its facing left if its more its facing right. This is why we are checking if the player position Canvas.GetLeft(player1) > 260 or < 260. This way we can make the player object more dynamic and suitable for the game.In the first part of this function we are capturing the mouse x and y position, then we created two double variable which means they can hold very large numbers since we want to be very precise with the mouse movement its best to use double as sometimes the numbers may be something like this x = 1.33333321132123 or something like that so it’s best to use the right tool for the job aye. Both double px and py will contain the mouse x and y location on the canvas. Canvas.SetLeft(player1, px – 10) this line will assign player 1’s horizontal location to the mouse x movement.

This is the overall purpose of the mouse move event, capture the mouse movement, tether the player object to the horizontal movement and update the graphics to left or right. Now lets go to the reset game function.

Reset Game Function

        private void resetGame()
        {
            //restart the game with the current settings. 
            System.Diagnostics.Process.Start(Application.ResourceAssembly.Location);
            // This will go in the event handler for your button click.
            Application.Current.Shutdown();
            Environment.Exit(0);
        }

This is the smallest function for this game, all it does is it will exit the current window and restart another window on the same position. This way when we lose, player can restart the game and try again.

The first line will make copy of the window with its current settings, second and third line exit the current window and then the new window will load up when the correct settings saved from the first line. Its important we close the current application which is open because otherwise it will run in the background and eat up the memory. This is why we are using Application.Current.ShutDown() and Environment.Exit(0). Better safe than sorry I guess,

Now let’s take a look at the make presents function. As you have guessed already this function will make the presents that drops from the top for this game.

Make presents function

        private void makePresents()
        {
            ImageBrush presents = new ImageBrush(); // make a new image brush

            int i = r.Next(1, 6); // get a random number between 1 and 6

            // this switch statement will check what number comes back and assign a present according
            // for example if the number is 1 then it will give present 1 image 2 give present 2 and so on
            switch (i)
            {
                case 1:
                    presents.ImageSource = new BitmapImage(new Uri("pack://application:,,,/images/present_01.png"));
                    break;
                case 2:
                    presents.ImageSource = new BitmapImage(new Uri("pack://application:,,,/images/present_02.png"));
                    break;
                case 3:
                    presents.ImageSource = new BitmapImage(new Uri("pack://application:,,,/images/present_03.png"));
                    break;
                case 4:
                    presents.ImageSource = new BitmapImage(new Uri("pack://application:,,,/images/present_04.png"));
                    break;
                case 5:
                    presents.ImageSource = new BitmapImage(new Uri("pack://application:,,,/images/present_05.png"));
                    break;
                case 6:
                    presents.ImageSource = new BitmapImage(new Uri("pack://application:,,,/images/present_06.png"));
                    break;
            }

            // once the present image is set, we now can make a new rectangle for the presents
            // inside of this rectangle we set the height, width, tag and fill link to the presents image brush we created above
            Rectangle newRec = new Rectangle
            {
                Tag = "drops",
                Width = 50,
                Height = 50,
                Fill = presents,
            };

            // once the presents rectangle is created now, we can set it randomly on the canvas
            // the reason we have a * -1 end of the top location is because whatever number comes back we want to move the
            // presents off the screen so it can continue to drop down
            Canvas.SetTop(newRec, r.Next(60, 150) * -1);
            Canvas.SetLeft(newRec, r.Next(10, 450));

            // once the location is set now we can add it to the canvas
            myCanvas.Children.Add(newRec);
        }

In the beginning of the function we are making a new imageBrush class called presents this class will hold the images you see on the screen. We have 6 different presents pictures so we need to run a switch statement to randomly assign the images to the rectangles this function will create. We are creating an integer called I inside this integer we will generate a random number between 1 – 6. The switch statement after that is responsible for checking what number was selected and then load that image to the presents imageBrush class. So, if 1 is selected it will pick the presents_1.png from the images folder and assign it as the graphics for this rectangle if 2 is selected it will pick the presents_2.png from the images folder to assign it as the graphics for the rectangle and so on. Switch statements work similar to if statements except they are easier to read and you have multiple cases inside of it depending what you need to do. Each case needs a break keyword in the so it knows when to stop if the conditions are met.Make the presents function is responsible for making the presents rectangle, assigning them a background image and the adding them to canvas we see here. Let’s take a look on what it does.

Right after the switch statement we creating a new rectangle called newRect. While creating the rectangle we can assign its properties directly inside of it.

Rectangle newRec = New Rectangle { <- open curly brackets and closed curly bracket -> }; <- semi colon to end the line too. inside both of the curly brackets we can define the height, width, fill, tag and more. For this exercise we are defining the height to 50 pixels, width to 50 pixels, give it a tag called “drops” (this is important) and lastly the Fill will be linked to the presents we created earlier in this function.

Once all of the properties for the rectangle is set, we can give it a location where we want it to spawn. This is when we use Canvas.SetTop() and Canvas.SetLeft() functions. Inside both of these functions first we need to declare which object we want to move and where we want to move it. We want this rectangle to spawn in random locations so its more interactive and the player will have to use some skill to catch as many as they can before the game is over. We can use the random number generator to make it easy for us on where the objects will spawn. Let’s see how it works

Canvas.SetTop(newRec, r.Next(60, 150) * -1); in this line we are saying that we want the newRect to move between 60 – 150 pixels from the top now we want the object to spawn off screen so way on top. We can achieve this effect by multiplying (*) this number by negative 1 this way the number that will be generated lets say 50 once its times by negative 50 it will become -50 so now it will spawn -50 pixels from the top and as we are animating object it will look like its dropping from the sky. Nice. We are doing similar for the Canvas.Left option. Canvas.SetLeft(newRec, r.Next(10, 450)); in this one we are saying newRec object should move between 10 pixels from the left to 450 pixels from the left. We don’t have to do the times negative 1 here as we want the object to stay inside the canvas width.

Lastly myCanvas.Children.Add(newRec); This line will add this newRec to the screen and we should be able to see it coming down once the timer event is completed.

Go to page 3 for more




Comments are closed.