Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a Timer in c++?

Tags:

c++

timer

I am developing a simple game in c++, a chase-the-dot style one, where you must click a drawn circle on the display and then it jumps to another random location with every click, but I want to make the game end after 60 seconds or so, write the score to a text file and then upon launching the program read from the text file and store the information into an array and somehow rearrange it to create a high score table. I think I can figure out the high score and mouse clicking in a certain area myself, but I am completely stuck with creating a possible timer. Any help appreciated, cheers!

like image 425
psychonaut Avatar asked Apr 24 '11 20:04

psychonaut


2 Answers

In C++11 there is easy access to timers. For example:

#include <chrono>
#include <iostream>

int main()
{
    std::cout << "begin\n";
    std::chrono::steady_clock::time_point tend = std::chrono::steady_clock::now()
                                               + std::chrono::minutes(1);
    while (std::chrono::steady_clock::now() < tend)
    {
        // do your game
    }
    std::cout << "end\n";
}

Your platform may or may not support <chrono> yet. There is a boost implementation of <chrono>.

like image 51
Howard Hinnant Avatar answered Oct 19 '22 16:10

Howard Hinnant


Without reference to a particular framework or even the OS this is unanswerable.

In SDL there is SDL_GetTicks() which suits the purpose.

On linux, there is the general purpose clock_gettime or gettimeofday that should work pretty much everywhere (but beware of the details).

Win32 API has several function calls related to this, including Timer callback mechanisms, such as GetTickCount, Timers etc. (article)

Using timers is usually closely related to the meme of 'idle' processing. So you'd want to search for that topic as well (and this is where the message pump comes in, because the message pump decides when (e.g.) WM_IDLE messages get sent; Gtk has a similar concept of Idle hooks and I reckon pretty much every UI framework does)

like image 20
sehe Avatar answered Oct 19 '22 16:10

sehe