Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use getch() without waiting for input?

 for (;;)
{
    cout << "You are playing for:" << playtime << "seconds." << endl;
    cout << "You have " << bytes << " bytes." << endl;
    cout << "You are compiling " << bps << " bytes per second." << endl;
    cout << "Press a to buy assembler monkey (produces 1 byte per second)/(cost 10 bytes)" << endl;
    switch(getch())
    {
        case 'a': bytes = bytes - 10; bps++; break;
    }
    bytes = bytes + bps;
playtime++;
Sleep(1000);
system("cls");
}

Let's say that's my incremental game. I want refresh my game after 1 second. How can I make getch() to wait for input without stopping all other stuff?

like image 565
Fairlight Avatar asked Jul 20 '14 08:07

Fairlight


1 Answers

Use kbhit() function to detect if a key was pressed :)

something like:

 for (;;)
{
    cout << "You are playing for:" << playtime << "seconds." << endl;
    cout << "You have " << bytes << " bytes." << endl;
    cout << "You are compiling " << bps << " bytes per second." << endl;
    cout << "Press a to buy assembler monkey (produces 1 byte per second)/(cost 10 bytes)" << endl;
    if(kbhit()){  //is true when a key was pressed
        char c = getch();   //capture the key code and insert into c

        switch(c)
        {
            case 'a': bytes = bytes - 10; bps++; break;
        }
    }
    bytes = bytes + bps;
    playtime++;
    Sleep(1000);
    system("cls");
}
like image 93
Mario Avatar answered Oct 05 '22 00:10

Mario