I am attempting to make a simple text based game. When the program reaches return 0, I get an unhandled exception...access violation. When I comment out the generate board and display board functions, I do not get the error. Let me know if see anything else that looks ugly.
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;
}
This line
int row = trap/9;
can lead to row
being more than 9 (e.g. if trap is 90 or more), which will overflow your array. Change it to
int row = trap/10;
int column = trap%10;