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

假设这是我的增量游戏。我想在 1 秒后刷新我的游戏。如何让 getch() 在不停止所有其他内容的情况下等待输入?

4

3 回答 3

5

使用khbit()函数来检测是否按下了键:)

就像是:

 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");
}
于 2015-03-20T20:06:18.640 回答
1

您可以使用另一个线程来获取用户输入。

是不必要的for (;;),您应该使用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;
    }
}
于 2014-07-20T10:41:04.730 回答
1

对我有用的getch()不是使用,而是使用scanf(). 为了停止scanf停止,您必须使用:

scanf("%c \n",example);

请记住,这example是一个指针 ( char* example;)

于 2020-10-03T12:15:34.703 回答