Frage

I wrote a program that simulates the Game of Life. Basically the world is implemented by a bi-dimensional std::vector of bool. If the bool is true the cell is alive, if is false the cell is dead. The output of the program is the system at each time step, completely in ASCII code:

[ ][0][ ]
[ ][ ][0]
[0][0][0]

The problem is that the program runs obviously fast and each time step is printed too quickly: I can't see how the system evolves. Is there some trick to slow down the output (or directly the program)?

EDIT: I'm on Mac OS X 10.7. My compiler is GCC 4.7.

War es hilfreich?

Lösung

You can use standard C++ (C++11):

#include <thread>
#include <chrono>
#include <iostream>

int main() {
    while (true) {
        // draw loop
        std::this_thread::sleep_for(std::chrono::milliseconds(20));
    }
}

Alternatively, you could use a library that lets you specify an interval at which to call your draw function. OS X has Grand Central Dispatch (a.k.a. libdispatch). Using GCD you could create a dispatch timer source that calls your draw function with a specified frequency.

dispatch_source_t timer = dispatch_source_create(
    DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());

dispatch_source_set_timer(timer, DISPATCH_TIME_NOW,
    duration_cast<nanoseconds>(milliseconds(20)).count(),
    duration_cast<nanoseconds>(milliseconds( 5)).count());
// the API is defined to use nanoseconds, but I'd rather work in milliseconds
// so I use std::chrono to do the conversion above

dispatch_source_set_event_handler(timer,
    []{ your_draw_function(); });
// I'm not sure if GCC 4.7 actually supports converting C++11 lambdas to
// Apple's C blocks, or if it even supports blocks. Clang supports this.

dispatch_resume(timer);

dispatch_main();

libdispatch reference

Andere Tipps

Whatever system you are using, it will have some kind of sleep function that you can call that will suspend your program for a specified period of time. You do not specify what OS you use, so I cant give exact details, but it sounds like the approach you are looking for.

If you call sleep for a certain length of time after drawing each update of the image, your program will sleep for that time before resuming and drawing the next update. This should give you chance to actually see the changes

If you want higher resolution time sleep you can look at nanosleep and usleep

1.You can use

int tmp; std::cin >> tmp;

and program will ask you before to go further.

2.You can use loop over some calculations. Like

double Tmp[1000000];
for( int i = 0; i < 1000000; i++ )
  Tmp[i] = i;
for( int i = 0; i < 1000000; i++ )
  Tmp[i] = sin(sin(sin(Tmp[i])));

3.You can check which delay-functions you have available for you. Example is "Sleep(nSeconds)" here

4.You can save and verify you system time. Like:

 while (time() < time_end){};
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top