如何在不输入C ++控制台游戏的情况下实现输入

时间:2019-01-19 16:08:47

标签: c++ input console

我被输入卡住了,没有回车输入。 我尝试从conio.h使用kbhit()+ getch(),但在我的系统上不起作用(Win10和Ubuntu-unistd.h和termios.h)。程序只是跳过这些功能的块。
然后,我使用了Windows.h中的GetAsynkKeyState。它可以在游戏(关卡)中运行,尽管有故障,但不能在菜单中使用。程序也将通过输入分派来跳过(或其他)代码块。
菜单输入:

// The menu interface
bool Menu::SelectLevel() {
    cout << "Select the level:" << endl;
    size_t arrow_pos = 0;
    // Prints level's names and char to exit the game
    for (size_t i = 0; i <= _levels.size(); ++i) {
        // Draw arrow before selected level
        if (i == arrow_pos) {
            cout << '>' << i + 1 << " - " << _levels[i].first[0] << endl;;
        }
        // Draw arrow before the exit select
        else if (i == _levels.size() && i == arrow_pos) {
            cout << '>' << "Exit" << endl;
        }
        // Draw the exit option
        else if (i == _levels.size()) {
            cout << ' ' << "Exit" << arrow_pos << endl;
        }
        // Draw levels list
        else {
            cout << ' ' << i + 1 << " - " << _levels[i].first[0] << endl;
        }
    }
    // Input from keyboard TODO DOESN'T WORK!:
    // If 's' pressed move arrow down
    PoollingDelay(1);
    if (GetAsyncKeyState(0x53) & 0x8000) {
        ++arrow_pos;
        // If arrow reached top it goes to the bottom
        if (arrow_pos == _levels.size() + 1) {
            arrow_pos = 0;
        }
    }
    // If 'w' pressed move arrow up
    else if (GetAsyncKeyState(0x57) & 0x8000) {
        --arrow_pos;
        // If arrow reached bottom it goes to the top
        if (arrow_pos == 65535) {
            arrow_pos = _levels.size() + 1;
        }
    }
    // If Return pressed
    else if (GetAsyncKeyState(VK_RETURN) & 0x8000) {
        // Don't think it would be worthy
        if (arrow_pos < 1 || arrow_pos > _levels.size() - 1) {
            throw runtime_error("Wrong select: " + to_string(arrow_pos));
        }
        // If player tired of this shit
        if (arrow_pos == _levels.size() - 1) {
            ClearTerminal();
            return false;
        }
        // Play
        PlayLevel(arrow_pos);
    }
    ClearTerminal();
    return true;
}

级别输入:

// TO DO DOESN'T WORK!:
void Level::ReadCommand() {
    PoollingDelay(100);
    if (GetAsyncKeyState(0x57)) {
        Move(_NORTH);
    }
    else if (GetAsyncKeyState(0x41)) {
        Move(_WEST);
    }
    else if (GetAsyncKeyState(0x53)) {
        Move(_SOUTH);
    }
    else if (GetAsyncKeyState(0x44)) {
        Move(_EAST);
    }
    else if (GetAsyncKeyState(0x45)) {
        throw runtime_error(exit_the_lvl);
    }
}

1 个答案:

答案 0 :(得分:0)

简短的回答:您不能仅使用C ++及其标准库。

这是因为该语言并非旨在处理低级硬件事件。为此,您需要依赖一个单独的库来处理I / O。它们很多,有些或多或少易于集成。对于简单的游戏,SDL很不错。