How to use getch() without waiting for input?

允我心安 提交于 2020-06-12 06:38:08

问题


 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?


回答1:


Use khbit() 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");
}



回答2:


You could use another thread, to get the user input.

The for (;;) is unnecessary, instead you should use while (true).

#include <Windows.h>
#include <iostream>
#include <conio.h>

using namespace std;

DWORD WINAPI SpeedThread(LPVOID lpParam);



int main ()
{
    int playtime = 0,
        bytes = 0,
        bps = 1;

    bool bKeyPressed = false;

    CreateThread( NULL, 0, SpeedThread, &bKeyPressed, 0, NULL);

    while (true)
    {
        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 (bKeyPressed && bytes >= 10)
        {
            bytes -= 10;    
            bps++; 

            bKeyPressed = false;
        }
        bytes = bytes + bps;
        playtime++;
        Sleep(1000);
        system("cls");
    }

}

DWORD WINAPI SpeedThread (LPVOID lpParam)
{
    bool * bKeyPressed = (bool *) lpParam;

    while (true)
    {
        if (_getch () == 'a')
            *bKeyPressed = true;
    }
}


来源:https://stackoverflow.com/questions/24848755/how-to-use-getch-without-waiting-for-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!