我需要设计一个有两个玩家的游戏。每个人都有一个球,应该能够左右移动球,第一个球员带有’a’‘d’按钮,第二个球员带有右,左箭头按钮。但是,当前一名球员需要等待另一名球员的动作完成才能移动自己的球。我该如何解决这个问题?这是我的代码的相关部分:
public class AnimationWindow extends JPanel{ public AnimationWindow() { super(); .... .... cezmiMover(); } public void cezmiMover(){ this.getInputMap().put(KeyStroke.getKeyStroke('a'), "left1"); this.getActionMap().put("left1", new AbstractAction() { public void actionPerformed(ActionEvent e) { board.cezmi1.moveLeft(); } }); this.getInputMap().put(KeyStroke.getKeyStroke('d'), "right1"); this.getActionMap().put("right1", new AbstractAction() { public void actionPerformed(ActionEvent e) { board.cezmi1.moveRight(); } }); this.getInputMap().put(KeyStroke.getKeyStroke("LEFT"), "left2"); this.getActionMap().put("left2", new AbstractAction() { public void actionPerformed(ActionEvent e) { board.cezmi2.moveLeft(); } }); this.getInputMap().put(KeyStroke.getKeyStroke("RIGHT"), "right2"); this.getActionMap().put("right2", new AbstractAction() { public void actionPerformed(ActionEvent e) { board.cezmi2.moveRight(); } }); } }
您需要使用一系列标志和某种“更新”循环来根据标志的状态来更新游戏的状态…
例如,首先创建一系列标志…
private boolean p1Left, p1Right, p2Left, p2Right = false;
这些可以由单个播放器对象轻松维护,但是您没有提供那么多代码…
接下来,您需要监视按键和按键释放事件,并根据需要设置标志的状态…
this.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_D, 0, false), "right1down"); this.getActionMap().put("right1down", new AbstractAction() { public void actionPerformed(ActionEvent e) { p1Right = true; } }); this.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_D, 0, true), "right1up"); this.getActionMap().put("right1up", new AbstractAction() { public void actionPerformed(ActionEvent e) { p1Right = false; } });
然后,您需要某种可以更新游戏状态的循环或计时器。就个人而言,我喜欢使用javax.swing.Timer,但仅此而已。
javax.swing.Timer
在更新循环的每次运行中,您需要检查每个标志的状态并相应地更新对象。
if (p1Right) { board.cezmi1.moveRight(); }