是否可以在 "main" 机器人 class 之外调用机器人方法?

Is it possible to call a robot method outside of "main" robot class?

我正在尝试在 robocode 环境中制作一个机器人。我的问题是,如果我想(例如)在我的机器人 class 之外调用方法 "fire()" (所以 class 扩展了 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 方面的专家,所以也许我遗漏了一些东西,但我尝试创建另一个 class 并让它扩展我的机器人 class(因此继承了 Robot 方法)但是 java 抛出了错误,因为扩展 Robot 的 class 需要 运行、onHitByBullet .. 方法。

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

public class Interpretator extends MyFirstRobot
{
public Interpretator(){

}

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

并且在 onScannedRobot 中简单地将参数 this.

有的话一定要给个更好的答案。

这似乎是一个设计问题。

您的解决方案有效,但是当您添加的方法多于 onScan 时,您将需要将 this 传递给您从 MyFirstRobot

进行的每个调用

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

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

进行这些更改(连同格式设置)得到:

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
    }
}