Home > Articles > Programming > Games

  • Print
  • + Share This
This chapter is from the book

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.

Virtual Methods

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.

Methods

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.

Properties

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:

app://{appguid}/_default#/Main.xaml?myparam1=one&myparam2=two

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.

GameTime

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.

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020