0

我正在尝试在 robocode 环境中制作机器人。我的问题是,如果我想(例如)在我的机器人类之外调用方法“fire()”(所以扩展 Robot 并具有运行的类,onHitBybullet,...方法),我该怎么做?

这只是我尝试过的事情之一(我的最新):

package sample;

import robocode.HitByBulletEvent;
import robocode.Robot;
import robocode.ScannedRobotEvent;
import sample.Interpretater;

public class MyFirstRobot extends Robot {

Interpretater inter;

public void run() {
    intel = new Interpretator();
    while (true) {
        ahead(50); // Move ahead 100
        //turnGunRight(360); // Spin gun around
        back(50); // Move back 100
        //turnGunRight(360); // Spin gun around
    }
}

public void onScannedRobot(ScannedRobotEvent e) {
    /*If I write fire() here, it will work, but I want to call it 
    from some other class (intel)*/
    inter.onScan();
}

public void onHitByBullet(HitByBulletEvent e) {
    turnLeft(90 - e.getBearing());
}
}   

解释器代码:

包装样品;

public class Interpretator extends MyFirstRobot
{
public Interpretator(){

}

public void onScan(){
    fire(1); //won't work, throws "you cannot call fire() before run()"
}
}

我根本不是Java专家,所以也许我遗漏了一些东西,但是我尝试创建另一个类并使其扩展我的机器人类(因此继承了Robot方法),但是由于扩展了Robot的类,Java抛出了错误需要运行,onHitByBullet .. 方法。

4

2 回答 2

1

这似乎是一个设计问题。

您的解决方案有效,但是当您添加比 onScan 更多的方法时,您将需要传递this给您从 MyFirstRobot 发出的每个调用

this相反,在解释器的构造函数中传递对的引用。

发生您的错误是因为解释器扩展了 MyFirstRobot。当您在fire(1)没有机器人参考的情况下调用时,它会在尚未运行的解释器上调用它run()。看起来您只是将解释器用作基于机器人做出决策的参考,因此解释器不是机器人。

进行这些更改(连同格式)将获得:

package sample;

import robocode.HitByBulletEvent;
import robocode.Robot;
import robocode.ScannedRobotEvent;
import sample.Interpretater;

public class MyFirstRobot extends Robot {

    Interpretater inter;

    public void run() {
        inter = new Interpretator(this); // intel looked like a typo
        while (true) {
            ahead(50); // Move ahead 100
            // turnGunRight(360); // Spin gun around
            back(50); // Move back 100
            // turnGunRight(360); // Spin gun around
        }
    }

    public void onScannedRobot(ScannedRobotEvent e) {
        /*
         * If I write fire() here, it will work, but I want to call it from some
         * other class (intel)
         */
        inter.onScan();
    }

    public void onHitByBullet(HitByBulletEvent e) {
        turnLeft(90 - e.getBearing());
    }
}

public class Interpretator {

    MyFirstRobot robot;

    public Interpretator(MyFirstRobot robot_arg) {
        // constructor sets instance variable
        robot = robot_arg;
    }

    public void onScan() {
        robot.fire(1); // use reference
    }
}
于 2016-03-27T14:19:31.550 回答
0

我发现的一个可能的答案是修改 Intepreter.onScan() 使其看起来像

public class Interpretator extends MyFirstRobot
{
public Interpretator(){

}

    public void onScan(MyFirstRobot robot){
        robot.fire(1); 
    }
}

而在 onScannedRobot 中,只需将this作为参数。

如果你有一个,请给出更好的答案。

于 2016-03-27T13:42:05.273 回答