![](/img/trans.png)
[英]How can I make sure that write happens before read in concurrenthashmap at the same time by different thread at same bucket and on a same key?
[英]How can i make multiple Key Bindings work at the same time?
我需要设计一个有两个玩家的游戏。 每个人都有一个球,应该能够左右移动球,第一个球员带有'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
,但这就是我。
在更新循环的每次运行中,您需要检查每个标志的状态并相应地更新对象。
if (p1Right) {
board.cezmi1.moveRight();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.