我正在尝试制作一个简单的基于文本的游戏。当程序到达返回0时,我得到一个未处理的异常...访问冲突。当我注释掉生成板和显示板功能时,我没有收到错误。如果看到其他任何看起来很难看的东西,请告诉我。
class character
{
public:
bool alive;
bool exit;
int row;
int col;
character()
{
alive = true;
exit = false;
row = 0;
col = 0;
}
void receiveMove()
{
char a;
cout<<"Move to the exit with w,a,s,d:";
cin>>a;
switch(a)
{
case ('w'):
row -= 1;
break;
case ('a'):
col -= 1;
break;
case ('s'):
row += 1;
break;
case ('d'):
col += 1;
break;
default:
cout <<"Invalid Move";
}
}
};
class game
{
public:
int board[10][10];
void generateBoard()
{
for(int i = 0; i<10; i++)
{
for(int j = 0; j<10; j++)
{
board[i][j] = 0;
}
}
for(int i = 0; i<3; i++)
{
int trap = rand()%99+1;
int row = trap/9;
int column = trap%9;
board[row][column] = 1;
}
board[9][9] = 2; //set last square as exit
}
void displayBoard(int charRow, int charCol, bool &alive, bool &exit)
{
ClearScreen();
for(int i=0; i<10; i++)
{
for(int j=0; j<10; j++)
{
if(i == charRow && j == charCol)
{
cout << "X ";
if(board[i][j] == 1)
{
alive = false;
}
if(board[i][j] == 2)
{
exit = true;
}
}
else
{
cout << board[i][j]<< " ";
}
}
cout << "\n";
}
}
void checkForWin(bool exit)
{
if(exit)
{
cout <<"You win";
}
}
void checkForDead(bool alive)
{
if(!alive)
{
cout <<"You dead";
}
}
};
int main()
{
character Player;
game Game;
Game.generateBoard();
Game.displayBoard(Player.row,Player.col,Player.alive,Player.exit);
while(Player.alive && !Player.exit)
{
Player.receiveMove();
Game.displayBoard(Player.row,Player.col,Player.alive,Player.exit);
}
Game.checkForWin(Player.exit);
Game.checkForDead(Player.alive);
return 0;
}
答案 0 :(得分:0)
这一行
int row = trap/9;
可导致row
超过9(例如,如果陷阱为90或更多),这将溢出您的阵列。将其更改为
int row = trap/10;
int column = trap%10;
答案 1 :(得分:0)
好吧,在片段中
int trap = rand()%99+1;
int row = trap/9;
int column = trap%9;
board[row][column] = 1;
您正在为trap
指定1到99之间的随机值。由于在这种情况下row
将获得值11,您将超出数组board
中的范围。
编辑:你必须除以10,这是你的电路板的大小。