console random movement gen help

im needing help with mt game im making. im trying to make the letter i in my game move randomly without moving out of the map. please help asap. here is what i have. please respond with a way to show me how to make "i" move without leaveing the box made of # signs and is a char Map [20][20]

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
  				case 'i':
							
			            RandomMove = rand() %4 + 1;
							
				if(RandomMove == 1){
					Map[y][x] = ' ';
					x--;
				        if(Map[y][x-1])
					{
						Map[y][x] = 'i';
					}
				}
				else if(RandomMove == 2){
					Map[y][x] = ' ';
					x++;
					if(Map[y][x+1])
					{
						Map[y][x] = 'i';
					}
				}
				else if(RandomMove == 3){
					Map[y][x] = ' ';
					y--;
					if(Map[y-1][x])
					{
						Map[y][x] = 'i';
					}
			        }
			        else if(RandomMove == 4){
					Map[y+1][x] = ' ';
					y++;
					if(Map[y][x-1])
					{
						Map[y][x] = 'i';
					}
				}
Last edited on
Something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
  				case 'i':
int org_x = x;
int org_y = y;

x += (rand() %3) - 1; // adds values -1, 0, or 1
y += (rand() %3) - 1; // adds values -1, 0, or 1

if((x < 0) || (x >= 20))
  x = org_x;
if((y < 0) || (y >= 20))
  y = org_y;

if((x != org_x) || (y != org_y))
{
					Map[org_y][org_x] = ' ';
					Map[y][x] = 'i';
}
With function:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
int MoveRandom(int value, int max_val)
{
  int result = value + (rand() %3) - 1; // adds values -1, 0, or 1

  if((result < 0) || (result >= max_val))
    result = value;

  return result;
}

...


  				case 'i':
int org_x = x;
int org_y = y;
x = MoveRandom(x, 20);
y = MoveRandom(y, 20);

if((x != org_x) || (y != org_y))
{
					Map[org_y][org_x] = ' ';
					Map[y][x] = 'i';
}
Topic archived. No new replies allowed.