我正在写一个双人蛇游戏。箭头键响应一条蛇,WASD键响应另一条蛇。但是我在我的代码中注意到,如果在同一时间按下每条蛇的一个键只有一条蛇转动。我有两个KeyListener,它们包含应该响应的四个键的数组。
class PlayerKeyPressListener implements KeyListener {
// Set of currently pressed keys
private final Set<Integer> pressed;
private int keyEvent[];
private Color c;
private int i;
public PlayerKeyPressListener(int[] a, Color col, int i) {
super();
pressed = new HashSet<Integer>();
keyEvent = a;
c = col;
this.i = i;
}
@Override
public void keyPressed(KeyEvent e) {
if(!(pressed.contains(keyEvent[0]) || pressed.contains(keyEvent[1])
|| pressed.contains(keyEvent[2]) || pressed.contains(keyEvent[3])))
pressed.add(e.getKeyCode());
proccessKey(e.getKeyCode());
}
@Override
public void keyReleased(KeyEvent e) {
pressed.remove(e.getKeyCode());
}
@Override
public void keyTyped(KeyEvent e) {/* Not used */ }
public void proccessKey(int key){
if(canTurn[i]) {
int d = grid.getDirection(c);
if(key == keyEvent[0]) {
if(d == 360)
grid.setDirection(d - 90, c); //Sets the direction of the snake with the specified color
else if(d == 180)
grid.setDirection(d + 90, c);
}
else if(key == keyEvent[1]) {
if(d == 360)
grid.setDirection(d + 90, c);
else if(d == 180)
grid.setDirection(d - 90, c);
}
else if(key == keyEvent[2]) {
if(d == 90)
grid.setDirection(d - 90, c);
else if(d == 270)
grid.setDirection(d + 90, c);
}
else if(key == keyEvent[3]) {
if(d == 90)
grid.setDirection(d + 90, c);
else if(d == 270)
grid.setDirection(d - 90, c);
}
canTurn[i] = false;
}
}
}
Heres是他们构建的地方:
int[] a = {KeyEvent.VK_LEFT, KeyEvent.VK_RIGHT, KeyEvent.VK_UP, KeyEvent.VK_DOWN};
int[] b = {KeyEvent.VK_A, KeyEvent.VK_D, KeyEvent.VK_W, KeyEvent.VK_S};
this.addKeyListener(new PlayerKeyPressListener(a, Color.blue, 0));
this.addKeyListener(new PlayerKeyPressListener(b, Color.red, 1));
有没有办法让两个玩家的响应更快?