game timer suggestions

I am making a maze type of game and I was wondering, how would I create a background timer that keeps track every 120000 milliseconds and would then render an enemy.I already know how to render the enemies.



(p.s. code example would be a big help.)

popa6200
Not a very detailed question at all. What are you using so far for writing this? If you're using something like SFML, then timers are included, but for standard cpp... If you really want to track things down to milliseconds (questionable if you only want an enemy every 2 minutes), you can use <chrono> and <thread> (difficult), but I have no idea what your level of C++ is? You will also need to make sure your compiler is up to date with the C++11 standard.

http://www.cplusplus.com/reference/chrono/

http://www.cplusplus.com/reference/thread/thread/ <-- Good example of using a thread.

Depending on what you're doing to make this game work, you could also run a check if x seconds have passed simply using functions from <ctime> for everything timing based (or <chrono>) after each player move. This is pretty easy to do.

More detail on the question will probably get you a better answer.

> code example would be a big help.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <functional>
#include <thread>
#include <chrono>
#include <ctime>

void timer( int msecs, int nticks, std::function< void() > call_back )
{
    for( int i = 0 ; i < nticks ; ++i )
    {
        std::this_thread::sleep_for( std::chrono::milliseconds(msecs) ) ;
        call_back() ; // assumes that callback returns almost immediately
    }
}

void foo() 
{
    char cstr[1024] ;
    auto t = std::time(nullptr) ;
    std::strftime( cstr, sizeof(cstr), "%T", std::localtime(&t) ) ;
    std::cout << cstr << " tick" << std::endl ; 
}

int main()
{
    std::thread thread( timer, 1000, 7, foo ) ;
    std::cout << "started timer" << std::endl ;
    std::this_thread::sleep_for( std::chrono::seconds(3) ) ;
    std::cout << "waiting for timer to finish" << std::endl ;
    thread.join() ;
    std::cout << "done\n" ;
}

http://coliru.stacked-crooked.com/a/ef4f73c521bfaf32
Topic archived. No new replies allowed.