我目前在c ++控制台应用程序中编写一个简单的游戏。我希望实时显示一个计时器,该计时器在执行第一个动作时开始,并在计时器达到预定时间(例如5分钟)时停止游戏。我不知道如何在c ++中这样做,所以我想知道是否有人对如何做到这一点有任何想法?
先谢谢,约翰。
答案 0 :(得分:2)
您可以在游戏开始时使用gettime()来获取开始时间。在游戏过程中,使用相同的方法并从开始时间减去检查所需的持续时间。您可以为此目的创建单独的流程
答案 1 :(得分:0)
#include <ctime> // ctime is still quite useful
clock_t start = clock(); // gets number of clock ticks since program start
clock_t end = 5 * CLOCKS_PER_SEC; // this is 5 seconds * number of ticks per second
// later, in game loop
if (clock() - start) > end { // clock() - start returns the current ticks minus the start ticks. we check if that is more than how many we wanted.
答案 2 :(得分:0)
#include <stdio.h>
#include <time.h>
int main ()
{
unsigned int x_hours=0;
unsigned int x_minutes=0;
unsigned int x_seconds=0;
unsigned int x_milliseconds=0;
unsigned int totaltime=0,count_down_time_in_secs=0,time_left=0;
clock_t x_startTime,x_countTime;
count_down_time_in_secs=10; // 1 minute is 60, 1 hour is 3600
x_startTime=clock(); // start clock
time_left=count_down_time_in_secs-x_seconds; // update timer
while (time_left>0)
{
x_countTime=clock(); // update timer difference
x_milliseconds=x_countTime-x_startTime;
x_seconds=(x_milliseconds/(CLOCKS_PER_SEC))-(x_minutes*60);
x_minutes=(x_milliseconds/(CLOCKS_PER_SEC))/60;
x_hours=x_minutes/60;
time_left=count_down_time_in_secs-x_seconds; // subtract to get difference
printf( "\nYou have %d seconds left ",time_left,count_down_time_in_secs);
}
printf( "\n\n\nTime's out\n\n\n");
return 0;
}
答案 3 :(得分:0)