为什么我的键盘命中是评估错误的

Why my keyboard hit is evaluating false

本文关键字:评估 错误 我的 键盘 为什么      更新时间:2023-10-16

我是C 编码蛇游戏的noob编码。整个程序都完美地吸引了板,水果和蛇头,但是我似乎无法使用键盘命中功能使蛇头坐标更改。当通过输入函数以获得蛇运动的键盘笔触时,似乎IF(KBHIT(在运行程序时会评估false,我的错误是什么,我该如何使蛇头移动?

谢谢。

#include <iostream>
#include <stdlib.h> 
#include <time.h>
#include <windows.h>
#include <conio.h>
using namespace std;
int X, Y, fruitX, fruitY;
enum eDir { STOP = 1, UP = 2, DOWN = 3, RIGHT = 4, LEFT = 5 }; //declare variables
eDir direction;
const int height = 20;
const int width = 20;
int board[height][width];
bool gameOver;
void setup()
{
    gameOver = false;
    srand(time(NULL));          // initilize game set up
    fruitX = (rand() % width);
    fruitY = (rand() % height);
    X = height / 2;
    Y = width / 2;
    direction = STOP;
    int board[height][width];
};
void draw()
{
    system("cls");
    for (int i = 0; i < width + 2; i++)
        cout << '#';
    cout << endl;
    for (int i = 0; i < height; i++)    //loop through matrix to draw board
    {
        for (int j = 0; j < width; j++)
        {
            if (j == 0)
                cout << '#';
            if (i == Y && j == X) // draw snake head
                cout << 'T';
            else if (i == fruitY && j == fruitX) // draw fruit
                cout << 'F';
            else
                cout << ' ';
            if (j == width - 1)
                cout << '#';
        }
        cout << endl;
    }
    for (int i = 0; i < width + 2; i++)
        cout << '#';
    cout << endl;
};
void input()
{
    if (_kbhit())
    {
        switch (_getch())
        {
        case 'w':
            direction = UP;
            break;
        case 's':
            direction = DOWN;
            break;
        case 'a':
            direction = LEFT;
            break;
        case 'd':
            direction = RIGHT;
            break;
        default:
            break;
        }
    }
};
void logic()
{
    switch (direction)
    {
    case UP:
        Y--;
        break;
    case DOWN:
        Y++;
        break;
    case LEFT:
        X--;
        break;
    case RIGHT:
        X++;
        break;
    default:
        break;
    }
};
int main()
{
    setup();
    while (!gameOver)
    {
        draw();
        input();
        logic();
        return 0;
    }
};

对于一件事,您在游戏循环中进行 return 0;,它仅在一次迭代后杀死程序,我认为您不打算。

我使用类似的方法制作了蛇,我的看起来像这样:

bool play = true;
while(play) {
    while (_kbhit) {
        switch (_getch) {
        case 'w':
            //code
            break;
        case 's':
            //code
            break;
        case 'a':
            //code
            break;
        case 'd':
            //code
            break;
        }
    }
}

该方法对我有用,我认为唯一的区别是我使用了一段时间循环,而不是if。