Bugster
Bugster

Reputation: 1594

Execute something after a certain waiting time specified in the code in C++?

I'm trying to make a basic snake game in C++, I made a basic grid with a orl[x] and ory[y] arrays, and now I'm trying to add the snake.

Basically I want the snake to move until a certain key is pressed and move one array at a time. I tried using something else than timers but it is executed instantly. I need a timer so that the snake keeps doing that every second until a key is pressed. If you ever played snake you know exactly what I mean.

I need to make a timer in C++, but I don't want to implement an ENORMOUS code by creating a timer and not understand anything from my own code. I want it as simple as possible.

Any idea how I could do this? I looked into the time header library but found nothing useful in there.

Upvotes: 1

Views: 4214

Answers (4)

Drew Dormann
Drew Dormann

Reputation: 63946

I'm adding this answer since no C++11 answer currently exists.

You can do platform-independant waiting using std::this_thread::sleep_for

void millisecond_wait( unsigned ms )
{
    std::chrono::milliseconds dura( ms );
    std::this_thread::sleep_for( dura );
}

Upvotes: 1

user206705
user206705

Reputation:

If you're using windows, check out the SetWaitableTimer windows api call. I can't supply an example as I'm on an iPad at the minute, but it does what you need.

Good luck!

Upvotes: 0

Trevor Hickey
Trevor Hickey

Reputation: 37914

If your on linux, you can use "time.h"
Here is a quick function to wait a number of seconds.
You could modify it for milliseconds if you'd like.
Also, are you using the ncurses library?

#include <iostream>
#include <cstdlib>
#include <time.h>

void SleepForNumberOfSeconds(const int & numberofSeconds);

int main(){

    std::cout << "waiting a second.." << std::endl;
    SleepForNumberOfSeconds(1);
    std::cout << "BOOM!" << std::endl;

    std::cout << "waiting 5 seconds.." << std::endl;
    SleepForNumberOfSeconds(5);
    std::cout << "AH YEAH!" << std::endl;

    return EXIT_SUCCESS;
}

void SleepForNumberOfSeconds(const int & numberofSeconds){

    timespec delay = {numberofSeconds,0}; //500,000 = 1/2 milliseconds
    timespec delayrem;

    nanosleep(&delay, &delayrem);

    return;
}

Upvotes: 1

Joel
Joel

Reputation: 5674

The sad truth is that Standard C++ doesn't really have support for this type of behavior. Both Windows and Posix support a sleep function which would allow you to do this. For a higher level solution you may look at Boost::Threads.

Upvotes: 2

Related Questions