在 C++ 代码中指定的一定等待时间后执行某些操作?
我正在尝试用 C++ 制作一个基本的蛇游戏,我用 orl[x] 和 ory[y] 数组制作了一个基本网格,现在我正在尝试添加蛇。
基本上我希望蛇移动直到按下某个键并一次移动一个数组。我尝试使用计时器以外的其他东西,但它会立即执行。我需要一个计时器,以便蛇每秒都这样做,直到按下按键为止。如果你玩过贪吃蛇,你就会明白我的意思。
我需要用 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
可悲的事实是,标准 C++ 并不真正支持这种类型的行为。 Windows 和 Posix 都支持睡眠功能,可以让您执行此操作。对于更高级别的解决方案,您可以查看 Boost::Threads。
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.
如果你在Linux上,你可以使用“time.h”
这是一个等待几秒钟的快速函数。
如果您愿意,您可以将其修改为毫秒。
另外,你使用 ncurses 库吗?
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?
我添加这个答案是因为当前不存在 C++11 答案。
您可以使用
std::this_thread::sleep_for
I'm adding this answer since no C++11 answer currently exists.
You can do platform-independant waiting using
std::this_thread::sleep_for
如果您使用的是 Windows,请查看 SetWaitableTimer windows api 调用。
我无法提供示例,因为我现在使用的是 iPad,但它可以满足您的需求。
祝你好运!
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!