2

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?

2
  • That sounds like a decent idea, yes. Commented Apr 11, 2013 at 14:00
  • You can try it and post relevant results (include also the Karel position/direction api) Commented Apr 11, 2013 at 14:00

2 Answers 2

3

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)]); 
Sign up to request clarification or add additional context in comments.

7 Comments

Sorry, here is the EscapeBot class. gist.github.com/anonymous/ea981988116d0b3f0be4 Not sure if this changes anything.
Nope, that's pretty much the same, except max_x is max_street and max_y is max_avenue
For some reason it's now throwing an error with the escapeRoom method. The random functions are working correctly however. Strange as that method wasn't really affected in anything that was done?
You are probably breaking the room boundaries. Verify that your frontIsClear() method is working correctly.
It doesn't seem to be breaking the boundaries at all, have ran the program 10 times or so and it has spawned correctly every time. I don't understand why the new code would make a difference to that method.
|
1

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(); } 

1 Comment

So you can for example make it spawn in a rectangle in the centre of the map.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.