首页 > 解决方案 > 移动在 C++ 控制台游戏中不起作用(使用 _kbhit 和 _getch)

问题描述

我使用二维数组作为坐标。为目标创建和显示带有随机坐标的板正在工作。但是,运动不起作用(它是 w、a、s、d)。我使用功能_kbhit_getch运动。

#include <iostream>
#include <conio.h>
#include <ctime>
using namespace std;

bool gameOver = false;
char board[10][10];
int goalX, goalY, playerX, playerY, score;
enum eDirection
{
    STOP = 0, LEFT, RIGHT, UP, DOWN
};
eDirection direction;

void Setup();
void Show(int playerX, int playerY, int goalX, int goalY, enum eDirection);
void Input(int playerX, int playerY, int goalX, int goalY, enum eDirection);
void Logic(int playerX,
           int playerY,
           int goalX,
           int goalY,
           enum eDirection,
           int score);

int main()
{
    Setup();

    while (!gameOver)
    {
        system("cls");
        Show(playerX, playerY, goalX, goalY, direction);
        Input(playerX, playerY, goalX, goalY, direction);
        Logic(playerX, playerY, goalX, goalY, direction, score);
    }
}

void Setup()
{
    direction = STOP;
    score = 0;
    playerX = 5;
    playerY = 5;

    srand(time(NULL));
    goalX = rand() % 10;
    goalY = rand() % 10;

}

void Show(int playerX, int playerY, int goalX, int goalY, enum eDirection)
{

    for (int i = 0; i < 10; i++)
    {
        for (int j = 0; j < 10; j++)
        {
            board[i][j] = '*';
            board[playerX][playerY] = 'P';
            board[goalX][goalY] = 'G';
            cout << board[i][j];

        }
        cout << endl;
    }
}

void Input(int playerX, int playerY, int goalX, int goalY, enum eDirection)
{
    if (_kbhit())
    {
        switch (_getch())
        {
            case 'w':
                direction = UP;
                break;
            case 'a':
                direction = LEFT;
                break;
            case 's':
                direction = DOWN;
                break;
            case 'd':
                direction = RIGHT;
                break;
        }
    }
}

void Logic(int playerX,
           int playerY,
           int goalX,
           int goalY,
           enum eDirection,
           int score)
{
    switch (direction)
    {
        case UP:
            playerY++;
            break;
        case LEFT:
            playerX--;
            break;
        case DOWN:
            playerY--;
            break;
        case RIGHT:
            playerX++;
            break;
    }

    if (playerX == goalX && playerY == goalY)
    {
        score += 10;
        goalX = rand() % 10;
        goalY = rand() % 10;
    }

}

标签: c++2d2d-games

解决方案


推荐阅读