Reputation: 515
Ok, so I have been tasked with creating a number of robots that find their way out of a situation. i.e There is a hole in the wall and they have to find the way out no matter where they spawn.
I have created a loop that makes 10 different robots but they all spawn on the same place:
EscapeBot[] Karel = new EscapeBot[numOfRobots];
for (int i = 0; i < numOfRobots; i++) {
Karel[i] = new EscapeBot(London, 1, 1, Direction.NORTH);
Karel[i].escapeRoom();
Should I be declaring integers and then using math.random within the for loop where the co-ordinates and direction are?
Upvotes: 2
Views: 2961
Reputation: 159
How about doing it like this(If you want to let robot to be able to spawn annywhere, just replace the spawn variables with your map dimensions):
for (int i = 0; i < numOfRobots; i++) {
Karel[i] = new EscapeBot(London,
SPAWN_X + SPAWN_LENGTH * Math.random(),
SPAWN_Y + SPAWN_WIDTH * Math.random(),
Direction.NORTH);
Karel[i].escapeRoom();
}
Upvotes: 1
Reputation: 18148
I can't say for certain without seeing your EscapeBot
class, but that's probably want you want, e.g.
Random rand = new Random();
new EscapeBot(London, rand.nextInt(max_x - 1) + 1, rand.nextInt(max_y - 1) + 1, Direction.NORTH);
where max_x
is the maximum x-coordinate and max_y is the maximum y-coordinate, assuming 1-based indexing (if using 0-based indexing then remove the -1 and +1 parts). You may also want an array of directions, e.g.
Direction[] directions = new Direction { Direction.NORTH, Direction.SOUTH, .. }
so that your EscapeBot will be
new EscapeBot(London, rand.nextInt(max_x - 1) + 1, rand.nextInt(max_y - 1) + 1, directions[rand.nextInt(directions.length)]);
Upvotes: 3