我一直在尝试在 Xcode 中编写游戏,其中使用 char 类型的多维数组在终端中绘制游戏板。游戏应该就像一个地牢,里面有可以踩到的门,当你在生成一个新房间时。但有时我会遇到这个非常烦人的“(11db)”错误,其中我的一条线被突出显示:
“线程 1:EXC_BAD_ACCESS(代码=EXC_I386_GPFLT)”
这不是我第一次在 Xcode 中遇到 (11db) 错误,以前我已经能够修复它,但这次我似乎无法修复它。这个错误是什么意思?我发现最烦人的部分是它不会每次都发生。有时它会在我创建房间时运行程序时立即发生,有时它会在你穿过一扇门之后发生,我什至可以不用它。这是发生的代码:
door_x = randomNumber(height - 1, 1);
door_y = randomNumber(width - 1, 1);
//Check to see if door location is the same an an enemy or the player
for (int i = 0; i < enemies.size(); i++){
while ((door_x == enemies.at(i).getX() && door_y == enemies.at(i).getY()) || (door_x == player->getX() && door_y == player->getY())){
door_x = randomNumber(height - 1, 1);
door_y = randomNumber(width - 1, 0);
}
}
room[door_y][door_x] = DOOR;//Place door on map
此错误发生在上述 C++ 代码的最后一行。究竟出了什么问题,为什么?
这是创建新房间的整个函数和我的随机数函数。
int randomNumber(int max, int min){
int randomNumber = rand() %(max - min) + min;
return randomNumber;
}
void create_new_room(){
//Get random room height and room width
height = randomNumber(settings[0], settings[1]);
width = randomNumber(settings[2], settings[3]);
room = new char*[height];
for (int iter = 0; iter != height; iter++) {
room[iter] = new char[width];
}
for (int i = 0; i < height; i++){
for (int j = 0; j < width; j++){
room[i][j] = EMPTY;
}
}
enemies.clear();//Delete every object from the vector
//Create the enemies
int numEnemies = randomNumber(settings[4], settings[5]);
for (int i = 0; i < numEnemies; i++){
int randomHeight = randomNumber(height, 0);
int randomWidth = randomNumber(width, 0);
Enemy *e;//Create pointer to class to allow vector class push back
e = new Enemy(randomWidth, randomHeight, HEALTH);
enemies.push_back(*e);
delete e;//Delete pointer e to free memory and avoid any memory leak.
room[enemies.at(i).getY()][enemies.at(i).getX()] = ENEMY;//Place enemy on board
}
//Create Player
int player_y = randomNumber(height, 0);
int player_x = randomNumber(width, 0);
for (int i = 0; i < enemies.size(); i++){
while (player_x == enemies.at(i).getX()){
player_y = randomNumber(height, 0);
player_x = randomNumber(width, 0);
}
}
player = new Player(player_x, player_y, ATTACK);
//Place player on board
room[player->getY()][player->getX()] = PLAYER;
//Create a door
door_x = randomNumber(height - 1, 1);
door_y = randomNumber(width - 1, 1);
//Check to see if door location is the same an an enemy or the player
for (int i = 0; i < enemies.size(); i++){
while ((door_x == enemies.at(i).getX() && door_y == enemies.at(i).getY()) || (door_x == player->getX() && door_y == player->getY())){
door_x = randomNumber(height - 1, 1);
door_y = randomNumber(width - 1, 1);
}
}
room[door_y][door_x] = DOOR;//Place door on map
}
Settings[] 是我拥有的一组设置,它从文本文件中读取值,其中包含最大和最小随机值的用户设置。0 = 最大高度 1 = 最小高度 2 = 最大宽度 3 = 最小宽度 4 = 最大敌人 5 = 最小敌人
我也在我srand(time(0))
的主要功能的顶部使用。
我的代码有点乱,但在这里。