问题描述
我有一个应在 Robot 类中执行的命令队列。但是命令是 Robot 类的方法,应该在 execute 方法中调用它们。
如果我在 main 中写这个:
Robot test = new Robot("Pengu",Math.toradians(90),1);
test.spawnInWorld(world,'3');
test.setProgram(robot -> {
List<Command> commands = new ArrayList<>();
commands.add(r -> r.go(0.1));
commands.add(r -> r.go(0.2));
return commands;
});
我的机器人课有
public class Robot implements Command{
private Queue<Command> todo = new LinkedList<>();
private Function<Robot,List<Command>> program;
public void setProgram(Function<Robot,List<Command>> newProgram){
program = newProgram;
}
public void think(){
List<Command> temp = program.apply(this);
for(int i = 0; i < temp.size(); i++){
todo.add(temp.get(i));
}
}
public void act(){
while(todo.peek() != null){
if(todo.remove().execute(this) == false) {
break;
}
work();
}
}
public void work(){
if(todo == null){
sense();
think();
}
}
/// Pre-programmed Commands!!!
public boolean go(double distance) {
//step can be negative if the penguin walks backwards
double sign = Math.signum(distance);
distance = Math.abs(distance);
//penguin walks,each step being 0.2m
while (distance > 0) {
position.moveBy(sign * Math.min(distance,0.2),direction);
world.resolveCollision(this,position);
distance -= 0.2;
}
System.out.println("go in robot executed!");
return true;
}
public boolean turnBy(double deltaDirection) {
direction += deltaDirection;
return true;
}
public boolean turnTo(double newDirection) {
direction = newDirection;
return true;
}
public boolean say(String text) {
world.say(this,text);
return true;
}
public boolean paintWorld(Position pos,char blockType) {
world.setTerrain(pos,blockType);
return true;
}
@Override
public boolean execute(Robot robot) {
//Implementation of execute
return false;
}}
我的问题是:如何以某种方式实现 execute,即 execute 运行 Robot 类中的命令/方法?
@FunctionalInterface
public interface Command {
boolean execute(Robot robot);
}
这是功能接口。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)