2016-04-29 102 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