【发布时间】:2021-07-12 14:52:37
【问题描述】:
我目前正在为我的 C++ 编程课制作一个小游戏,教授要求我们为游戏设置一个计时器。我们根本没有讨论过如何使用计时器和任何标准计时器库,所以我们只能靠自己了。我找到了 std 库,并尝试为游戏实现一个简单的计时器并设法做到了,但我似乎无法弄清楚如何将时间从它格式化为更用户友好的版本,如 HH:MM:SS .毫秒。我所拥有的只是从开始稳定时钟到结束它的原始时间,我可以以秒、毫秒、分钟等为单位显示它,但这看起来不像我想要的那么好。我找到了一些解决方案,但它们对我来说太难了,甚至无法解构并尝试应用。有什么简单的方法可以做我想做的事吗? 我实现计时器的部分代码:
// Initialize game timer using <chrono>
chrono::steady_clock::time_point start = chrono::steady_clock::now();
// While game is running (player alive and enemy robot lefts) update map
while (!GameEnd){
show_maze(maze_map);
cout << endl;
playerMove(x, y, GameEnd, died, maze_map);
}
// Terminate game timer and calculate time elapsed
chrono::steady_clock::time_point end = chrono::steady_clock::now();
chrono::steady_clock::duration time_elapsed = end - start;
// Show last map state before either player died or no more robots left
show_maze(maze_map);
// Boo / congratulate player for his performance on the game
cout << "Game Over! You " << (died ? "died by hitting a fence/robot :(" : "won because all the robots died. Congratulations!") << endl;
cout << "Your game lasted for " << chrono::duration_cast<chrono::milliseconds>(time_elapsed).count() << " milliseconds.\n\n";
【问题讨论】: