How To Use Game Timer

This article will show you how to use game timer in SwinGame. Timer is essential in time based games. This demonstrates some of the timer functions and procedures in SwinGame.

Level

Advanced

Details

Timer records the game time in miliseconds. In many games you will want something to happen at a specific time. To achieve this in your game you need to be able to start, stop, pause or resume the timer in your game.

To use this features of the SwinGame you need to do the following:

  1. Create a timer (Create Timer) variable.
  2. Start the timer (Start Timer). This will start counting the time.
  3. In the game loop prompt the user what options they have with the timer. For the code below the options are to pause, resume, stop or start the timer.
  4. Depending on what the user input is, pause (Pause Timer), resume (Resume Timer), stop (Stop Timer) or start (Start Timer) the timer.
  5. Ask for the number of ticks (Timer Ticks) that the timer has.
  6. Next convert the number of ticks from an integer to a string value so you can draw that number to the screen.

The code below shows a small program that demonstrates these features of a timer.

Source Code Widget

  • program HowToUseGameTimer;
    uses 
        sgGraphics, sgTypes, sgImages, sgUtils, sgTimers, sgAudio, sgResources, sgText, sgInput;
    
    procedure Main();
    var
        gameTime: Timer;
        ticks: Integer;
        toDraw: String;
    begin    
        OpenGraphicsWindow('Game Timer', 150, 150);
        gameTime := CreateTimer();
        StartTimer(gameTime);
    
        repeat
            ProcessEvents();
            ClearScreen(ColorWhite);
            DrawText('[P]ause', ColorBlack, 0, 0);
            DrawText('[R]esume', ColorBlack, 0, 10);
            DrawText('[S]top', ColorBlack, 0, 20);
            DrawText('[B]egin', ColorBlack, 0, 30);
            
            if KeyTyped(VK_P) then PauseTimer(gameTime);
            if KeyTyped(VK_R) then ResumeTimer(gameTime);
            if KeyTyped(VK_S) then StopTimer(gameTime);
            if KeyTyped(VK_B) then StartTimer(gameTime);
    
            ticks := TimerTicks(gameTime);
            Str(ticks, toDraw);
            DrawText(toDraw, ColorRed, 20, 70);
            RefreshScreen();
        until WindowCloseRequested();
    
        ReleaseAllResources();
    end;
    
    begin
        Main();
    end.
  • Source Code Coming Soon

  • Source Code Coming Soon

  • Source Code Coming Soon

  • Source Code Coming Soon

If there is a useful hint you will find it in a box like this

Possibilities

Suggested projects will appear here.