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]

 ``123456789101112131415161718192021222324252627282930313233343536`` `````` 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:
 ``1234567891011121314151617`` `````` 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:
 ``123456789101112131415161718192021222324`` ``````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.