c++ structure: repeat set of functions at a certai

2019-06-10 14:26发布

So I'm stuck with a little c++ program. I use "codeblocks" in a w7 environment.

I made a function which shows a ASCII map and a marker. A second function updates the markers position on that map.

I would like to know how I could make my main structure so that the marker gets updated and the map showed, and this repeated at a certain time rate. Which functions can I use to make this happen. What strategy should I follow?

every x times/second DO { showmap(); updatePosition();}

I am a c++ beginner and I hope you can help!

3条回答
家丑人穷心不美
2楼-- · 2019-06-10 15:05

Depending on what else your program needs to be doing, you may need to employ event driven programming. If updating that marker is the only thing it will be doing, a simple while loop with a sleep will suffice, as demonstrated in other answers.

In order to do event driven programming you generally need an event loop - which is a function that you call in main, which waits for events and dispatches them. Most event loops will provide timer events - where, basically, you ask the event loop to call function X after a given time interval elapses.

You most likely don't want to write your own event loop. There are many choices for an event loop, depending on many things like programming language and required portability.

Some examples of event loops:

查看更多
够拽才男人
3楼-- · 2019-06-10 15:07

Seems that you want to implement an infinite loop like games engine does.

Try to do this:

while (true)
{
    showmap();
    updatePosition();
    sleep(1);
}
查看更多
走好不送
4楼-- · 2019-06-10 15:19

A loop with usleep

unsigned XtimesPerSecond = 5;    // for example
unsigned long long microseconds = 1000000 / XtimesPerSecond;

do
{
    showmap();
    updatePosition();
    usleep(microseconds);
} while(true);
查看更多
登录 后发表回答