【发布时间】: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