2016-04-29 82 views
2

我已经在控制台中用C++创建了运行迷宫游戏。C++迷宫计数传递时间

我想添加函数来计算玩家通过迷宫所需的时间。

通过迷宫后可显示总时间。

我真的很感激任何帮助或想法。

游戏主循环看起来就像这样:

do { 
    show(); // function do display maze , 2d array 
    cout << "Your position: " << x << " " << y << endl; 
    cout << "Coins gained: " << coins << endl; 
    cout << "blahblahblah" : "<<endl; 
    m = getche(); 
    cout << endl; 
    move(m); // function to recognize which way player want to go, including checking for not going through the wall 
    cout << endl; 
    system("CLS"); 
} while (x != 12 || y != 18 || coins < 10); //for pass the maze player have to move on these position and gain x coins 

system("CLS"); 
cout << "You Won!" << endl; 
cout << "Click enter to move on. \n"; 
+0

你的帖子不清楚你实际需要什么帮助。你有一个_specific_问题或什么_specific_你需要帮助吗? \ –

+0

如果你的编译器支持C++ 11'std :: chrono'将会是开始的地方:http://en.cppreference.com/w/cpp/chrono – drescherjm

回答

1
#include <time.h> 
#include <iostream> 

int main() { 
    int start, end, total; 
    start = time(NULL); 
//place loop here 
    //game ends, calc time 
    end = time(NULL); 
    total = end - start; 
    std::cout << "You completed the maze in " << total << " seconds."; 
    return 0; 
} 

从本质上讲,这确实是开始在某一时刻开始的时间,然后停止在以后计数(单位:秒),虽然cin和getch()或暂停程序以获取输入的任何其他内容都可能导致定时器停止。在某些库中,它将使用系统时间。在其他库中,它将使用运行时间。请注意这一点,如果它不使用运行时间,一定要使用的输入法如

int main(){ 

     time_t myTime,myTimeEnd; 
     time(&myTimeEnd); 
     myTime = myTimeEnd; 
    //code 
     time(&myTime); 
     int total = myTimeEnd - myTime; 
     std::cout<< "Time taken is " << total << " seconds."; 
     return 0; 
    } 

第二种方法获取并持有你的时间,这是由引用传递你的时间变量保存到时间函数,这是'得到'时间。

+0

哦,我以前用过chrono,所以它会不要太难。感谢帮助。 – Matthaius