Exiting a Game After a Time Out
Complete Sample
The code in this topic shows you the technique. You can download a complete code sample for this topic, including full source code and any additional supporting files required by the sample.
Adding Time-Out Functionality to a Game
To make a game time out
-
Create a class that derives from Game.
-
Determine the desired time-out limit in milliseconds.
// Time out limit in ms. static private int TimeOutLimit = 4000; // 4 seconds
-
Add a variable for tracking the elapsed time since the most recent user activity.
// Amount of time that has passed. private double timeoutCount = 0;
-
When user input is checked, set a flag indicating whether any user activity has taken place.
GamePadState blankGamePadState = new GamePadState( new GamePadThumbSticks(), new GamePadTriggers(), new GamePadButtons(), new GamePadDPad()); bool checkActivity(KeyboardState keyboardState, GamePadState gamePadState) { // Check to see if the input states are different from last frame GamePadState nonpacketGamePadState = new GamePadState( gamePadState.ThumbSticks, gamePadState.Triggers, gamePadState.Buttons, gamePadState.DPad); bool keybidle = keyboardState.GetPressedKeys().Length == 0; bool gamepidle = blankGamePadState == nonpacketGamePadState; if (keybidle && gamepidle) { // no activity; return false; } return true; }
-
In Update, if there has not been any user activity, increment the tracking variable by the elapsed time since the last call to Update.
-
If there has been some user activity, set the tracking variable to zero.
// Check to see if there has been any activity if (checkActivity(keyboardState, gamePadState) == false) { timeoutCount += gameTime.ElapsedGameTime.Milliseconds; } else timeoutCount = 0;
-
Check whether the value of the tracking variable is greater than the time-out limit.
-
If the variable is greater than the limit, perform some time-out logic such as playing an idle animation or, in this case, exit the game.
// Timeout if idle long enough if (timeoutCount > TimeOutLimit) { Exit(); base.Update(gameTime); return; }