[英]Is it possible to call a robot method outside of “main” robot class?
我正在嘗試在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 ..方法。
這似乎是一個設計問題。
您的解決方案可以工作,但是當您添加的方法數量超過onScan時,您需要this
方法傳遞給您從MyFirstRobot進行的每次調用
而是在Interpretater的構造函數中傳遞this
的引用。
發生錯誤是因為Interpretator擴展了MyFirstRobot。 當您在沒有機械手引用的情況下調用fire(1)
,它將在尚未運行run()
Interpretator上對其進行調用。 看起來您只是在使用Interpretator作為參考來基於機器人進行決策,因此Interpretator並不是Robot。
進行這些更改(以及格式化)將獲得:
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
}
}
我發現的可能答案是修改Intepreter.onScan()使其看起來像
public class Interpretator extends MyFirstRobot
{
public Interpretator(){
}
public void onScan(MyFirstRobot robot){
robot.fire(1);
}
}
而在onScannedRobot中,只需將this作為參數即可。
如果有答案,請給出更好的答案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.