【问题标题】:Creating a timed game in c++用 C++ 创建一个定时游戏
【发布时间】:2014-03-25 09:23:35
【问题描述】:

我目前正在用 c++ 控制台应用程序编写一个简单的游戏。我想实时显示一个计时器,该计时器在它执行的第一个动作时开始,并在计时器达到预定时间(例如 5 分钟)时停止游戏。我不知道如何在 C++ 中执行此操作,所以我想知道是否有人对如何执行此操作有任何想法?

提前致谢,约翰。

【问题讨论】:

  • 你可以使用SetTimer结束游戏。
  • 您需要更具体地了解您遇到的问题,跟踪时间还是让它在控制台中实时显示?

标签: c++ visual-studio visual-c++


【解决方案1】:

您可以在游戏开始时使用 gettime() 来获取开始时间。在游戏期间,使用相同的方法并从开始时间中减去以检查所需的持续时间。您可以为此创建一个单独的进程

【讨论】:

    【解决方案2】:
    #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.
    

    【讨论】:

      【解决方案3】:
       #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;
      }
      

      【讨论】:

        【解决方案4】:

        对于任何寻找答案的人,您可以使用 Easylogging++ 性能跟踪功能

        this link;和thisthis 样本

        (披露,我是这个库的主要作者,不是想打广告,但因为这个功能适用于这个问题,所以提到这个)

        【讨论】:

          猜你喜欢
          • 2013-10-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-12-07
          • 2011-09-17
          • 1970-01-01
          • 1970-01-01
          • 2021-02-28
          相关资源
          最近更新 更多