1

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.

Bugster
  • 1,552
  • 8
  • 34
  • 56

4 Answers4

1

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 );
}
Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
1

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.

Joel
  • 5,618
  • 1
  • 20
  • 19
1

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;
}
Trevor Hickey
  • 36,288
  • 32
  • 162
  • 271
0

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!