假设我想将可运行的这些方法调用(ahead()、turnLeft()、back() 等)放入集合列表或数组中,并且一个在另一个之后执行。这可以做到吗?顺便说一下,这是一个名为“RobotCode”的机器人游戏。 预先感谢。
import java.awt.*;
import java.util.ArrayList;
public class NeuBot extends Robot
{
int rapidFire = 2;
//RobotHit rbHit = new RobotHit(null);
public String name;
boolean firing = false;
int trigger;
int turnDirection = 2;
final int MOVES = 5;
boolean wasHit = true;
int moveOne = 1;
int moveTwo = 2;
int moveThree = 3;
ArrayList<Integer> moveLst = new ArrayList<Integer>();
public void run()
{
while (true)
{
//Methods Defined within the Robot Class
ahead(100);
back(200);
turnLeft(180);
turnRight(180);
onScannedRobot(null);
onHitRobot(null);
}
}
//Robot Has Target
public void onScannedRobot(ScannedRobotEvent e)
{
for (int i = 0; i < MOVES; ++i)
{
firing = true;
fire(rapidFire);
if (firing == true)
{
back(50);
out.println("Moved Back"); //TestX
}
}
turnRight(10);
ahead(20);
}
//
public void onHitRobot(HitRobotEvent e)
{
out.println("Hit");
wasHit = true;
if (wasHit == true)
{
//Move Ahead And Fire
ahead(20);
fire(rapidFire);
out.print("Fired Again!");
}
}
}
简单的解决方案:使用
Runnable
列表,如下所示:
List<Runnable> commands = List.of(
() -> ahead(100),
() -> back(200),
() -> turnLeft(180),
() -> turnRight(180),
() -> onScannedRobot(null),
() -> onHitRobot(null)
);
上面创建了一个不可修改的列表,但是也可以像 in 和动态添加命令一样使用 usual 列表:
List<Runnable> commands = new ArrayList<>():
commands.add( () -> ahead(100) );
commands.add( () -> back(200) );
// ...
这些列表可以在 Java 8 Streams 中使用:
commands.forEach(Runnable::run);
或在通常循环中:
for (Runnable command : commands) {
command.run();
// additional statements, e.g. Thread.sleep(...) for some delay
}