WPF C# Tutorial – Create a fun Balloon popping game in visual studio
- Subject: WPF C# Tutorials
- Learning Time: 2 hours
Start Programming –
Let’s add the Threading name space to this project so we can use the dispatcher timer. Each line of code has been commenting in the program. Every line that starts with the // double slash is a comment, inside of visual studio it will show as a green line. In these lines you can write notes, explain your code for some one or eve just add what the line is doing for future reference.
This line using System.Windows.Threading; allows us to use the timer class from inside of it. Timer is the main game object that we need to make the balloons move, track their positions, spawn new balloons and more.
Add the variables –
Here are the variables for this game. Add the above the public MainWindow() line. All of these are global variables and can be accessed from any of the functions inside of this program.
//create a new timer called game timer
DispatcherTimer gameTimer = new DispatcherTimer();
// set initial speed to 3
int speed = 3;
// set initial intervals to 90
int intervals = 90;
// create a new random number generator class
Random rand = new Random();
// a list to remove items from the canvas
List<Rectangle> itemRemover = new List<Rectangle>();
// background image texture class
ImageBrush background = new ImageBrush();
// integer to keep track of different balloon images
// this integer will be used move the balloons left or right slightly
// missed balloon count integer
// boolean to check if the game is active or not
// score counter
// create a new media player to link the pop sound to
private MediaPlayer player = new MediaPlayer();
The main window function –
This function will come default with every project, this function runs when the main window loads so we can set instructions here to load when the window does.
//start loading the default settings
gameTimer.Tick += gameEngine; // link the timer to the game engine event
gameTimer.Interval = TimeSpan.FromMilliseconds(20); // set timer interval to 20 milliseconds
// set the background image for the canvas
background.ImageSource = new BitmapImage(new Uri("pack://application:,,,/files/background-Image.jpg"));
MyCanvas.Background = background;
// run the reset game function
Under the initialize component line add them all. In this function we are setting up the game timer first the tick this will link with the gameEngine event we created earlier. Set the game timer interval to run every 20 milliseconds. So this gameEngine event will run every 20 milliseconds in this game.
Set the canvas background to the background image we created and run the reset game function.
Go to Page 3 to start adding events for this game
- balloon pop game
- visual studio games development
- wpf arcade game
- wpf clicking game
- wpf play sound
- wpf tutorial
- wpf tutorial and project files