I just started learning C++ about two days ago. It is my first programming language, but I feel that I have progressed far.
However, upon practicing coding, I stumbled across a dilemma in which I've spent over half-an-hour trying to work out.
I am creating a game called
Dungeon Crawl. There is a [7][10] array in which I have produced. It serves as the "map" of the game, laying out the positions of the characters. It looks like this:
. . . . . . . . . .
. P . . . . . . . .
. . . . . . E . . .
. . . T . . . . . .
. . . . E . . . . .
. . T . . . E . . .
. . . . . . . . . X
The 'E's stay in place, but if the player ('P') collides into it, the player dies. The objective is to reach the X, as it is the location of the "treasure".
I created a function called
tMove(), which is intended to locate 'T' by iterating through the array and using conditionals (if board[i][j] == 'T'). The function is used after the player is prompted to enter which direction they would like to go (Up/Down/Left/Right).
Anyway, once 'T' is located, it will cause 'T' to move in a random direction after testing if there is not an 'E' in the way and makes sure it does not pass outside of the board.
The problem is as follows: Sometimes the 'T's will disappear because the for loop finds the T that has moved already and replaces it with a '.'. How can I go about fixing this? Should I introduce different variables, and if so, how?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
|
void tMove() //for the AI 'T' and how it moves (SUPER LOOP NEST INC)
{
for(int i = 0; i < 7; i++)
{
for(int j = 0; j < 10; j++)
{
if(board[i][j] == 'T')
{
srand(time(0));
int tRand = rand() % 4;
switch(tRand) //if the remainder is 0,1,2,3
{
case 0:
if(board[i - 1][j] != 'E' && i > 0)
{
board[i][j] = '.'; //replace T with a '.'
board[i - 1][j] = 'T'; //T moves up
}
break;
case 1:
if(board[i + 1][j] != 'E' && i < 7)
{
board[i][j] = '.';
board[i + 1][j] = 'T'; //T moves down
}
break;
case 2:
if(board[i][j - 1] != 'E' && j > 0)
{
board[i][j] = '.';
board[i][j - 1] = 'T'; //T moves left
}
break;
case 3:
if(board[i][j + 1] != 'E' && j < 7)
{
board[i][j] = '.';
board[i][j + 1] = 'T'; //T moves right
}
break;
}
}
}
}
}
|