Click here to see the questionRobot Race How can I make multiple robots run simultaneously. I have created run method that keeps track of x and y co-ordinates for each action
import java.util.LinkedList;
import java.util.Queue;
public class Robot implements Runnable {
private int delay;
private String actions;
private String name;
int x = 0;
int y = 0;
// 2d array for 4 direction on cartesian grid
int[][] move = {{0,1}, {1,0}, {-1,0}, {0,-1}};
int dir = 0;
int time = 1;
Queue<Character> queue = new LinkedList<>();
public Robot(int delay, String actions, String name) {
this.delay = delay;
this.actions = actions;
this.name = name;
}
@Override
public void run() {
for (char ch: actions.toCharArray()) {
if (ch == 'F') {
x += move[dir][0];
y += move[dir][1];
} else if (ch == 'L') {
dir++;
} else if (ch == 'R') {
dir--;
}
// to avoid overflow
dir = (dir + 4) % 4;
System.out.println(time+ "s " +name+ ": Moves " +ch);
time++;
try {
Thread.sleep(delay * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new Robot(3, "FFFLRFRLFF", "Joe").run();
new Robot(1, "FFFFFLF", "Bill").run();
}
} `
How can I make multiple robots run simultaneously.
You need to start a separate Thread for each Robot.
The reason your class implements Runnable
is so it can be used as a Thread.
So to start a Thread for each Robot the basic code would be:
//new Robot(3, "FFFLRFRLFF", "Joe").run();
Robot robot1 = new Robot(3, "FFFLRFRLFF", "Joe")
new Thread(robot1).start();
When the Thread
starts it will invoke the run()
method.