我试图在robocode环境中制作一个机器人。我的问题是,如果我想(例如)调用方法" fire()"在我的机器人类之外(所以扩展Robot并具有run,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方法)但是然后java扔了因为扩展Robot的类需要运行onHitByBullet ..方法。
答案 0 :(得分:1)
这似乎是一个设计问题。
您的解决方案有效,但是当您添加的方法多于onScan时,您需要将this
传递给您从MyFirstRobot进行的每次通话
相反,在Interpretater的构造函数中传递对fire(1)
的引用。
您的错误发生是因为Interpretator扩展了MyFirstRobot。当你在没有机器人引用的情况下调用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());
}
}
。看起来您只是使用Interpretator作为基于机器人做出决策的参考,因此Interpretator不是机器人。
进行这些更改(以及格式化)得到:
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
}
}
和
Target
答案 1 :(得分:0)
我找到的一个可能的答案是修改Intepreter.onScan(),使其看起来像
public class Interpretator extends MyFirstRobot
{
public Interpretator(){
}
public void onScan(MyFirstRobot robot){
robot.fire(1);
}
}
在onScannedRobot中只需输入 this 。
如果你有答案,请给出更好的答案。