运行时等待输入

问题描述 投票:0回答:2

我正在尝试使用 C++ 控制台应用程序创建游戏

我的目标是让我的

do .. while()
在等待响应时运行。 它应该一直显示“..O..”直到按下“a”键然后显示“.O...”或者当按下“d”键时显示“...O”。 我的问题是我不能在不暂停应用程序等待输入的情况下使用
cin
getline

那么有没有办法做类似循环的事情,如果

cin
在 10 毫秒内没有返回值,它会打印“..O..”? 我不希望程序继续等待输入,可能就像每个
Sleep(10)
之间的
cin
...

我对它应该是什么样子的想法:

void out()
{
    int x;
    string key;
    do {
        cin >> key;
        //insert here something like break; that will
        //stop waiting for input after 10 milliseconds.
        system("cls");
        if (key != "a" && key != "d") {
            cout << "..O..";
        }
        else {
            if (key == "a") {
                cout << ".O..." << endl;
            }
            else {
                if (key == "d") {
                    cout << "...O." << endl;
                }
                else {
                    cout << "..O..";
                }
            }
        }
    } while (x == 0);
    x = 0;
}
c++ game-engine iostream cin
2个回答
0
投票

在您的问题中,如果未提供任何输入,应用程序必须处于初始位置,因此需要重新排序

void out()
{
    int x;
    string key;
    do {
        system("cls");
        cout << "..O..";

        cin >> key; //output will remain same as long as no input

        system("cls");
        if (key == "a") {
           cout << ".O..." << endl;
        }
        else if (key == "d") {
           cout << "...O." << endl;
        }

    } while (x == 0);
    x = 0;
}

0
投票

最好的办法是实施

GetAsyncKeyState()
,它使用虚拟键码来检查是否按下了一个键。

代码看起来像这样:

bool end = false;
    do {
        system("cls");
        cout << "..O..";

        cin >> key; //output will remain same as long as no input

        system("cls");
        if (GetAsyncKeyState(VK_LEFT)) {
           cout << ".O..." << endl;
        }
        else if (GetAsyncKeyState(VK_RIGHT) {
           cout << "...O." << endl;
        }

    } while (!end); //remember to add a way to end the loop.

来源:https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getasynckeystate

虚拟键码列表:https://learn.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes

© www.soinside.com 2019 - 2024. All rights reserved.