Search code examples
c++countmazegame-loop

C++ maze count passing time


I've created functioning maze game in c++ in console.

I would like to add function to count time needed to pass the maze by player.

Total time could be displayed after pass the maze.

I would really appreciate any help or ideas.

main game-loop looks something like that:

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";

Solution

  • #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;
    }
    

    Essentially, what this does is start counting time at a certain point, then stop counting at a later point (in seconds), though cin and getch(), or anything else that pauses the program in order to get an input may cause the timer to stop. In certain libraries, it will use system time. In other libraries, it will use running time. Be careful of this, and if it does use running time, be sure to use an input method such as

    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;
         }
    

    The second method gets and holds the time for you, which is saved by passing your time variable by reference to the time function, which 'gets' time.