![](/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.