我正在尝试在GridWorld中控制Bug%s。我已经尝试了两种方法,但这两种方法都没有实际移动或改变bug。它们都进行了编译,但什么也没发生。
下面是要控制的Bug:
package info.gridworld.actor;
import info.gridworld.grid.*;
import info.gridworld.grid.Location;
import java.awt.Color;
public class MazeBug extends Bug {
public MazeBug() {
super(Color.blue);
}
public void forward(){
Grid<Actor> gr = getGrid();
if (gr == null)
return;
Location loc = getLocation();
Location next = loc.getAdjacentLocation(getDirection());
if (gr.isValid(next))
moveTo(next);
else
removeSelfFromGrid();
}
public void turnRight(){
setDirection(getDirection() + Location.RIGHT);
}
public void turnLeft(){
setDirection(getDirection() + Location.LEFT);
}
}这是我尝试用扫描仪的W,A和D键控制bug的第一种方法(不确定我是否正确地使用了扫描仪)
package info.gridworld.actor;
import java.util.Scanner;
import info.gridworld.grid.*;
public class KeyTests extends Actor
{
public static ActorWorld world = new ActorWorld(new BoundedGrid<Actor>(20, 20));
public static MazeBug currentBug;
public static void main(String[] args) {
world.show();
world.add(new Location(1,11),new MazeBug());
while(true){
Scanner k = new Scanner(System.in);
String buttonpress = k.nextLine();
if (buttonpress.equals("w"))
currentBug.forward();
if (buttonpress.equals("d"))
currentBug.turnRight();
if (buttonpress.equals("a"))
currentBug.turnLeft();
}
}
}下面是我尝试控制bug的第二种方法
package info.gridworld.actor;
import info.gridworld.grid.*;
public class KeyTests extends Actor
{
public static ActorWorld world = new ActorWorld(new BoundedGrid<Actor>(20, 20));
public static MazeBug currentBug;
public static void main(String[] args) {
world.add(new Location(1,11),new MazeBug());
java.awt.KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new java.awt.KeyEventDispatcher() {
public boolean dispatchKeyEvent(java.awt.event.KeyEvent event) {
String key = javax.swing.KeyStroke.getKeyStrokeForEvent(event).toString();
if (key.equals("w"))
currentBug.forward();
if (key.equals("d"))
currentBug.turnRight();
if (key.equals("a"))
currentBug.turnLeft();
world.show();
return true;
}
});
world.show();
}
}感谢您在高级课程中的帮助
发布于 2014-05-23 23:04:30
当GridWorld单步执行时,它所做的就是调用每个Actor's act方法,所以如果您的Actor有一个未填充的方法,它将只调用父方法,或者什么也不做。您的runner,因为它不是“Actor”,所以没有act方法,并且在第一次运行之后再也不会看到它。
在你的MazeBug中试试这个:
public void act()
{
java.awt.KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new java.awt.KeyEventDispatcher() {
public boolean dispatchKeyEvent(java.awt.event.KeyEvent event) {
String key = javax.swing.KeyStroke.getKeyStrokeForEvent(event).toString();
if (key.equals("w"))
forward();
if (key.equals("d"))
turnRight();
if (key.equals("a"))
turnLeft();
return true;
}
});
}注意::我从来没有用过EventListeners,所以对这段代码没有什么帮助。
https://stackoverflow.com/questions/23823470
复制相似问题