我正在建造一个迷宫,怪物正在追踪玩家并向其移动。我有一个称为SwapCells的函数,我认为问题出在其中。SwapCells用于移动Monster和Player。我有一个ScheduledExecutorService,它运行使用SwapCells的Monstermover。游戏开始时,Monster开始移动,现在的问题是当我开始移动播放器时,ScheduledExecutorService停止工作,我只能移动播放器。我认为问题在于,与MoveMonster不同,Keylistener不是ScheduledExecutorService的一部分,因此,当我调用依次运行SwapCell的KeyListener时,它将使ScheduledExecutorService停止。有什么建议吗?请帮助!
private final int CELLSIZE = 20;
private ArrayList<Level> levels = new ArrayList<Level>();
private Player player;
private Monster monster;
private DisplayInfo display;
private int xSize;
private int ySize;
private int currentLevel = 0;
private int direction = 0;
//private CountDownTimer timer = new CountDownTimer(15);
public Game(int xSize, int ySize) {
player = new Player(0,0);
monster = new Monster(0,1);
setXSize(xSize);
setYSize(ySize);
setLayout(new GridLayout(ySize, xSize));
addLevel();
addKeyListener(new KeyListener() {
// POSSIBLE PROBLEM IS HERE !!
@Override
public void keyPressed(KeyEvent event) {
if(!hitWall) }
swapCells(getCurrentLevel().getMap()[x+dx][y+dy], getCurrentLevel().getMap()[x][y], player);
}
}
}
});
ScheduledExecutorService executor = Executors.newScheduledThreadPool(3);
executor.scheduleAtFixedRate(() -> moveMonster(), 0L, 1000L, TimeUnit.MILLISECONDS);
}
public void swapCells(Cell cell1, Cell cell2, Mover mover) {
Icon tempIcon = cell1.getLabel().getIcon();
String tempID = cell1.getID();
// sets mover's x and y value
mover.setX(cell1.getX());
mover.setY(cell1.getY());
// sets mover's cell to new cell
getCurrentLevel().getpMaze().setCell(cell1, mover);
getCurrentLevel().getMap()[cell1.getX()][cell1.getY()].setID(cell2.getID());
getCurrentLevel().getMap()[cell1.getX()][cell1.getY()].getLabel().setIcon(cell2.getLabel().getIcon());
getCurrentLevel().getMap()[cell2.getX()][cell2.getY()].setID(tempID);
getCurrentLevel().getMap()[cell2.getX()][cell2.getY()].getLabel().setIcon(tempIcon);
}
public void moveMonster() {
PerfectMaze currentMaze = getCurrentLevel().getpMaze();
ArrayList<Cell> trackToPlayer = currentMaze.getTrack(currentMaze.getMonsterCell(), currentMaze.getPlayerCell(), "P");
Collections.reverse(trackToPlayer);
Cell nextCell = trackToPlayer.get(1);
//swapCells(nextCell, currentMaze.getMonsterCell(), monster);
swapCells(getCurrentLevel().getMap()[nextCell.getX()][nextCell.getY()], getCurrentLevel().getMap()[monster.getX()][monster.getY()], monster);
}
您仅应与Swing“事件调度线程”(EDT)中的Swing组件进行交互。但是您创建了一个ExecutorService
,它的线程直接在操纵Swing组件。相反,他们应该通过SwingWorker
将任务提交给EDT以进行图形更新。