How To: Make a Game Time Out

Demonstrates how to make a game time out after a period of inactivity.

The Complete Sample

The code in this tutorial illustrates the technique described in the text. A complete code sample for this tutorial is available for you to download, including full source code and any additional supporting files required by the sample.

To Make a Game Time Out

  1. Create a class that derives from Game.
  2. Determine the desired time out limit in milliseconds.

    // Time out limit in ms.
    static private int TimeOutLimit = 8000;
  3. Add a variable for tracking elapsed time since user activity took place.

    // Amount of time that has passed.
    private double timeoutCount = 0;
  4. 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
        //KeyboardState blankKeyboardState = new KeyboardState();
        GamePadState nonpacketGamePadState = new GamePadState(gamePadState.ThumbSticks, gamePadState.Triggers, gamePadState.Buttons, gamePadState.DPad);           
        //if ((blankKeyboardState == keyboardState) && (blankGamePadState == nonpacketGamePadState))
        bool keybidle = keyboardState.GetPressedKeys().Length == 0;
        bool gamepidle = blankGamePadState == nonpacketGamePadState;
        if ( keybidle && gamepidle)
            // no activity;
            return false;
        return true;
  5. In Update, if no user activity has taken place, increment the tracking variable by the elapsed time since the last call to Update. If user activity has taken place, set the tracking variable to zero.

    // Check to see if there has been any activity
    if (checkActivity(keyboardState, gamePadState) == false)
        timeoutCount += gameTime.ElapsedGameTime.Milliseconds;
        timeoutCount = 0;
  6. Next, 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, exiting.

    // Timeout if idle long enough
    if (timeoutCount > TimeOutLimit)

Community Additions