I try to find out my problem within an hour.
I am going to do what is happening.
char trap = 'Q';
char character = 'L';
....
.Q..
..L.
....
when L moves up and Q moves to the right, they collide and the program ends. but:
....
.QL.
....
....
when L moves to the left and Q moves to the right, they do not collide in the same way as in the example above, which happens:
....
..Q.
....
....
here is my code. sorry for my bad english :(
check if there is "w", "a", "s" or "d":
void cave::move(int& x, int& y, char m, char unit)
{
if ( m == 'W' || m == 'w' )
{
floor[x][y] = tile;
x -= 1;
for ( unsigned short int x = 0; x < 3; x++ )
{
if ( floor[x][y] == wall && floor[x][y] == trap[x] )
{
x += 1;
trapsMove();
}
}
floor[x][y] = unit;
}
else if ( m == 'A' || m == 'a' )
{
floor[x][y] = tile;
y -= 1;
for ( unsigned short int x = 0; x < 3; x++ )
{
if ( floor[x][y] == wall && floor[x][y] == trap [x] )
{
y += 1;
trapsMove();
}
}
floor[x][y] = unit;
}
else if ( m == 'S' || m == 's' )
{
floor[x][y] = tile;
x += 1;
for ( unsigned short int x = 0; x < 3; x++ )
{
if ( floor[x][y] == wall && floor[x][y] == trap[x] )
{
x -= 1;
trapsMove();
}
}
floor[x][y] = unit;
}
else if ( m == 'D' || m == 'd' )
{
floor[x][y] = tile;
y += 1;
for ( unsigned short int x = 0; x < 3; x++ )
{
if ( floor[x][y] == wall && floor[x][y] == trapx] )
{
y -= 1;
trapsMove();
}
}
floor[x][y] = unit;
}
else
control();
return;
}
ai moves the function
void cave::trapsMove()
{
int r[3];
for ( unsigned short int x = 0; x < 3; x++ )
{
r[x] = rand() % 4 + 1;
if ( r[x] == 1 )
move(traps_positionX[x],traps_positionY[x],'w',trap[x]);
else if ( r[x] == 2 )
move(traps_positionX[x],traps_positionY[x],'a',trap[x]);
else if ( r[x] == 3 )
move(traps_positionX[x],traps_positionY[x],'s',trap[x]);
else if ( r[x] == 4 )
move(traps_positionX[x],traps_positionY[x],'d',trap[x]);
}
return;
}
check if collide
bool cave::collision()
{
for ( unsigned short int x = 0; x < 3; x++ )
{
if ( floor[character_positionX][character_positionY] == trap[x] )
return true;
}
return false;
}