机器人竞赛 -> 机器人在笛卡尔网格上移动。 L 向左 90 度,R 向右 90 度,F 向前一 space。请参阅随附的屏幕截图
Robot race -> robot moves on cartesian grid. L is Left 90 degrees, R is right 90 degrees and F is forward one space. Please see attached screenshot
Click here to see the questionRobot Race
如何同时制作多个机器人 运行。我创建了 运行 方法来跟踪每个动作的 x 和 y 坐标
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.
您需要为每个机器人启动一个单独的线程。
您的 class 实现 Runnable
的原因是它可以用作线程。
因此,要为每个机器人启动一个线程,基本代码为:
//new Robot(3, "FFFLRFRLFF", "Joe").run();
Robot robot1 = new Robot(3, "FFFLRFRLFF", "Joe")
new Thread(robot1).start();
当 Thread
启动时,它将调用 run()
方法。
Click here to see the questionRobot Race 如何同时制作多个机器人 运行。我创建了 运行 方法来跟踪每个动作的 x 和 y 坐标
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.
您需要为每个机器人启动一个单独的线程。
您的 class 实现 Runnable
的原因是它可以用作线程。
因此,要为每个机器人启动一个线程,基本代码为:
//new Robot(3, "FFFLRFRLFF", "Joe").run();
Robot robot1 = new Robot(3, "FFFLRFRLFF", "Joe")
new Thread(robot1).start();
当 Thread
启动时,它将调用 run()
方法。