微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我有一个应该在 Robot 类中执行的命令队列但是命令是 Robot

如何解决我有一个应该在 Robot 类中执行的命令队列但是命令是 Robot

我有一个应在 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 举报,一经查实,本站将立刻删除。