【问题标题】:Player detecting wall in array in C++玩家在 C++ 中检测数组中的墙
【发布时间】:2020-08-18 07:06:17
【问题描述】:

我希望我的玩家“P”能够在地图上移动,但不能移动到墙壁上或越过墙壁。在我实现 if 语句来检查墙壁之前,代码将正常工作。

我这样做的想法是,如果玩家朝某个方向移动,请先检查该方向是否有墙。如果有墙,则让玩家知道。 当我这样做时,发生了许多问题。玩家有时能够检测到墙壁,有时则不能。例如,如果我首先运行程序并向右移动“e”,它会让我知道有一堵墙,但是一旦我向左移动“w”并回到右边,它就会消失到墙上。 向上移动 'n' 和向下移动 's' 也是一个问题,因为它会上升两次,而不是一次。

为什么会这样,我该如何解决?

bool running = true;
int px = 2;
int py = 7;

char player = 'P';
//map
char map[8][8] = {
    { '#','#','#','#','#','#','#','#' },
    { '#',' ',' ',' ','#',' ',' ','#' },
    { '#',' ',' ',' ','#',' ',' ','#' },
    { '#','#','#',' ','#',' ',' ','#' },
    { '#',' ',' ',' ','#',' ',' ','#' },
    { '#',' ','#','#','#',' ',' ','#' },
    { '#',' ',' ',' ',' ',' ',' ','#' },
    { '#','#',' ','#','#','#','#','#' }
};

// print map
void printMap() {
    for (int i = 0; i < 8; i++) {
        for (int j = 0; j < 8; j++) {
            if (j == px && i == py) {
                cout << 'P';
            }
            else {
                cout << map[i][j] << " ";
            }
        }
        cout << endl;
    }
}
// player movement
void playerMove() {
    char move;

    cin >> move;
    if (move == 'e') {
        if (map[py][++px] == '#') { 
            cout << "there's a wall here!";
        }
        else {
            map[py][px] = ' ';
            map[py][++px] = player;
            system("cls");
            printMap();

        }
        
    }
    if (move == 'w') {
        if (map[py][--px] == '#') {
            cout << "there's a wall here!";
        }
        else {
            map[py][px] = ' ';
            map[py][--px] = player;
            system("cls");
            printMap();
        }
        
    }
    if (move == 'n') {
        if (map[--py][px] == '#') {
            cout << "there's a wall here!";
        }
        else {
            map[py][px] = ' ';
            map[--py][px] = player;
            system("cls");
            printMap();
        }
        
    }
    if (move == 's') {
        if (map[++py][px] == '#') {
            cout << "there's a wall here!";
        }
        else {
            map[py][px] = ' ';
            map[++py][px] = player;
            system("cls");
            printMap();
        }
    }
}


【问题讨论】:

  • if (map[py][++px]... 你不想这样。试试px+1
  • 您的playerMove() 函数没有任何边界检查。
  • 您的打印地图可以明智地显示玩家,而无需将玩家(或“空”)写入地图。所以,不要。

标签: c++ arrays multidimensional-array


【解决方案1】:

问题很可能是您如何检查墙壁的碰撞。

例如,如果我们查看 map[py][++px] == '#',我们会看到您修改了 px,因此即使该位置是墙,玩家位置也会被修改。

这也会导致else 部分出现问题,因为您随后会“清除”玩家不在的位置,并修改px再次

改用加法解决它:map[py][px + 1] == '#'

正如我已经提到的,添加边界检查以确保例如px + 1 没有越界。

【讨论】:

  • 你是对的,但有趣的是,一旦墙壁检查被固定,边界检查只需要在地图下边缘的墙壁间隙处。
猜你喜欢
  • 1970-01-01
  • 2021-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多