The Game Class
The Game class is where all of the magic in your game takes place. Almost everything in your game is driven in some part by this class, and it is the root of your project. Let's dive in and see what it is made of.
The Game object you're class derives from has many knobs and buttons (figuratively) to help control your game and its flow. It has several virtual methods you can override to help control different features, some of which we've seen already.
Initialize, as you would expect, is called once just after the object is created. It is where you would do most of your initialization (aside from loading content) for your game. This is an ideal place to add new game components for example (which are discussed later in this chapter). LoadContent and UnloadContent are two other areas where you should load (or unload) your content. Content is loosely defined and can be any external data your game needs, whether it's graphics, audio, levels, XML files, and so on.
The Update method is where you handle updating anything your game requires, and in many games, you can do things such as handle user input. Because most games are essentially a simulation with external forces, you need a central spot where you can perform the operations to advance that simulation. Common things you'd do include moving objects around the world, physics calculations, and other simulation updates.
Draw probably needs no further explanation. All drawing code for each scene occurs here. There are two other drawing methods you can override: BeginDraw and EndDraw. These are called directly before and after Draw is called, respectively. If you override the EndDraw call, you need to ensure you call the base.EndDraw or manually call GraphicsDevice.Present; otherwise, you never see your scenes drawn on screen.
Much like the pre- and post-drawing methods, there are also BeginRun and EndRun methods you can override that are called before the game begins and just after the game run ends. In most cases, you do not override these, unless you are doing something such as running multiple simulations as individual game objects.
You can override the method ShowMissingRequirementMessage. Most people probably don't even realize it is there. By default, this does nothing on non-Windows platforms, and on Windows, it shows a message box giving you the exception detail. This enables customization if the platform you run on doesn't meet the requirements of your game, which is normally only an issue on a platform such as Windows where you can't guarantee which features it supports.
The last three methods you can override are mirrors of events you can hook. OnActivated is called at the same time the Activated event is fired, and it happens when your game becomes activated. Your game is activated once at startup, and then anytime it regains focus after it has lost focus. To mirror that, you use the OnDeactivated method, which is called when the Deactivated event is fired, and that happens when your game becomes deactivated, such as it exits or it has lost focus. On Windows and Windows Phone 7, your game can lose focus for any number of reasons (switching to a new app, for example), whereas on Xbox 360, you see this only if the guide screen displays.
Finally, the OnExiting method is called along with the Exiting event. As you can probably guess, this happens just before the game exits.
Most of the methods on the Game class are virtual so there aren't many here to discuss, and they're almost all named well, so you can guess what they do. The Exit method, which causes the game to start shutting down. The ResetElapsedTime method resets the current elapsed time, and you'll learn more about it later in this chapter. The Run method is what starts the game running, and this method does not return until the game exits. On Xbox 360 and Windows, this method is called by the autogenerated main method in program.cs at startup, and on Windows Phone 7, this method throws an exception. Due to platform rules, you can't have a blocking method happen during startup on Windows Phone 7. A timer starts and periodically calls RunOneFrame, which does the work of a single frame. You can use this method on Xbox 360 and Windows, but you shouldn't have to use it since the game object is doing that for you.
The SuppressDraw method stops calling Draw until the next time Update is called. Finally, the Tick method advances one frame; namely, it calls Update and Draw.
After covering all of the methods, properties are naturally the next item on the list. You've already seen the Services property, which enables you to add new services to the game and query for existing ones. You've also already seen the Content and GraphicsDevice properties, which store the default content manager and graphics device.
A property called InactiveSleepTime gives you some control of how your game handles itself when it is not the foreground window. This value tells the system how long to "sleep" when it is not the active process before checking to see if it is active again. The default value of this is 20 milliseconds. This is important on Windows were you can have many processes run at once. You don't want your game to run at full speed when it isn't even active.
Speaking of being active, the IsActive property tells you the current state of the game. This maps to the Activated and Deactivated events, too, as it turns true during Activated and false during Deactivated. Chapter 12, "Adding Interactivity with User Input" discusses the IsMouseVisible property, even though you can probably guess what it does.
The LaunchParameters property is used for Windows Phone 7 to get information about parameters required for launching, but this can be used for any platformand translates the command-line parameters on Windows into this object. It is a dictionary of key value pairs. On Windows, if your command line is as follows, the object would have a dictionary with three members:
game.exe /p /x:abc "/w:hello world"
The first member would have a key of "p" with a value of an empty string. The second member would have a key of "x" with a value of "abc." The third member has a key of "w" with a value of "hello world."
On Windows Phone 7, applications are launched with a URI that includes these parameters; for example, if your launch command is as follows, the object would have a dictionary with two members:
The first member would have a key of "myparam1" and a value of "one." The second member would have a key of "myparam2" and a value of "two."
The last two properties are IsFixedTimeStep and TargetElapsedTime. Timing is so important to game development there is a whole section on that! Because anticipation is probably overwhelming, that section is next.
You may not realize it, but a lot of things in a game depend on time. If you create a race game and your cars are going 60 miles per hour, you need to know how much to move them based on a given time. The framework tries to do a lot of the work of handling time for you.
There are two major ways to run a game, and in the framework, they are referred to as "fixed time step," and "variable time step." The two properties mentioned in the previous section—IsFixedTimeStep and TargetElapsedTime—control how time is handled. IsFixedTimeStep being true naturally puts the game into fixed time step mode, whereas false puts the game into variable time step mode. If you are in fixed time step mode, TargetElapsedTime is the target time for each frame. The defaults for projects are true for IsFixedTimeStep and 60 frames per second for TargetElapsedTime (which is measured in time, so approximately 16.6667 milliseconds).
What do these time steps actually mean? Variable time step means that the amount of time between frames is not constant. Your game gets one Update, then one Draw, and then it repeats until the game exits. If you noticed, the parameter to the Update method is the GameTime.
The GameTime object has three properties that you can use. First, it has the ElapsedGameTime, which is the amount of time that has passed since the last call to Update. It also includes TotalGameTime, which is the amount of time that has passed since the game has started. Finally, it includes IsRunningSlowly, which is only important in fixed time step mode.
During variable time step mode, the amount of time recorded in ElapsedGameTime passed to update can change depending on how long the frame actually takes (hence, the name "variable" time step).
Fixed time step is different. Every call to Update has the same elapsed time (hence, it is "fixed"). It is also different from variable time step in the potential order of Update and Draw calls. While in variable time step, you get one update for every draw call; in fixed time step, you potentially get numerous Update calls in between each Draw.
The logic used for fixed time step is as follows (assuming you've asked for a TargetElapsedTime of 60 frames per second).
Update is called as many times as necessary to catch up to the current time. For example, if your TargetElapsedTime is 16.667 milliseconds, and it has been 33 milliseconds since your last Update call, Update is called, and then immediately it is called a second time. Draw is then called. At the end of any Draw, if it is not time for an Update to occur, the framework waits until it is time for the next Update before continuing.
If at any time, the runtime detects things are going too slow (for example, you need to call Update multiple times to catch up), it sets the IsRunningSlowly property to true. This gives the game the opportunity to do things to run faster (such as rendering less or doing fewer calculations).
If the game gets extremely far behind, though, as would happen if you paused the debugger inside the Update call if your computer just isn't fast enough, or if your Update method takes longer than the TargetElapsedTime, the runtime eventually decides it cannot catch up. When this happens, it assumes it cannot catch up, resets the elapsed time, and starts executing as normal again. If you paused in the debugger, things should just start working normally. If your computer isn't good enough to run your game well, you should notice things running slowly instead.
You can also reset the elapsed time yourself if you know you are going to run a long operation, such as loading a level or what have you. At the end of any long operation such as this, you can call ResetElapsedTime on the game object to signify that this operation takes a while, don't try to catch up, and just start updating from now.
Notice that in Windows Phone 7 projects, the new project instead sets the TargetElapsedTime to 30 frames per second, rather than the 60 used on Windows and Xbox 360. This is done to save battery power, among other reasons. Running at half the speed can be a significant savings of battery life.