public void keyPressed(KeyEvent e) {
int setNum = 1;
if(e.getKeyCode() == 'u'|| e.getKeyCode() == 'U' && setNum == 1) {
setNum = 2;
}
这是2Player Tetris游戏代码::键设置的一部分
if(e.getKeyCode() == 'u'|| e.getKeyCode() == 'U' && setNum == 2) {
setNum = 1;
}
if(setNum == 1) {
if(e.getKeyCode() == 'a' || e.getKeyCode() == 'A') {
board1.tryMove(board1.curPiece, board1.curX - 1, board1.curY);
}
if(e.getKeyCode() == 'd' || e.getKeyCode() == 'D') {
board1.tryMove(board1.curPiece, board1.curX + 1, board1.curY);
}
if(e.getKeyCode() == 's' || e.getKeyCode() == 'S') {
board1.oneLineDown();
}
if(e.getKeyCode() == 'w' || e.getKeyCode() == 'W') {
board1.tryMove(board1.curPiece.rotateLeft(), board1.curX, board1.curY);
}
if(e.getKeyCode() == KeyEvent.VK_SHIFT) {
board1.dropDown();
}
if(e.getKeyCode() == KeyEvent.VK_RIGHT) {
board2.tryMove(board2.curPiece, board2.curX + 1, board2.curY);
}
if(e.getKeyCode() == KeyEvent.VK_LEFT) {
board2.tryMove(board2.curPiece, board2.curX - 1, board2.curY);
}
if(e.getKeyCode() == KeyEvent.VK_DOWN) {
board2.oneLineDown();
}
if(e.getKeyCode() == KeyEvent.VK_UP) {
board2.tryMove(board2.curPiece.rotateLeft(), board2.curX, board2.curY);
}
if(e.getKeyCode() == KeyEvent.VK_SPACE) {
board2.dropDown();
}
}
当setNum = 1时;播放器1可以使用WASD播放,播放器2可以使用箭头键播放
else if(setNum == 2) {
if(e.getKeyCode() == '2' || e.getKeyCode() == '2') {
setNum = 1;
}
if(e.getKeyCode() == 'a' || e.getKeyCode() == 'A') {
board2.tryMove(board2.curPiece, board2.curX - 1, board2.curY);
}
if(e.getKeyCode() == 'd' || e.getKeyCode() == 'D') {
board2.tryMove(board2.curPiece, board2.curX + 1, board2.curY);
}
if(e.getKeyCode() == 's' || e.getKeyCode() == 'S') {
board2.oneLineDown();
}
if(e.getKeyCode() == 'w' || e.getKeyCode() == 'W') {
board2.tryMove(board2.curPiece.rotateLeft(), board2.curX, board2.curY);
}
if(e.getKeyCode() == KeyEvent.VK_SHIFT) {
board2.dropDown();
}
if(e.getKeyCode() == KeyEvent.VK_RIGHT) {
board1.tryMove(board1.curPiece, board1.curX + 1, board1.curY);
}
if(e.getKeyCode() == KeyEvent.VK_LEFT) {
board1.tryMove(board1.curPiece, board1.curX - 1, board1.curY);
}
if(e.getKeyCode() == KeyEvent.VK_DOWN) {
board1.oneLineDown();
}
if(e.getKeyCode() == KeyEvent.VK_UP) {
board1.tryMove(board1.curPiece.rotateLeft(), board1.curX, board1.curY);
}
if(e.getKeyCode() == KeyEvent.VK_SPACE) {
board1.dropDown();
}
}
setNum = 2; Player1可以使用箭头键播放,而Player2可以使用wasd键播放。
但是我的代码无效。我该怎么办?
答案 0 :(得分:0)
有用的答案是可能应该在离开事件侦听器之前进行键处理。也就是说,使用匿名内部类中的适当参数调用相关方法。
字面上的最小答案是将nanoseconds
的声明移到适当的范围。如果适当的范围不是类(即它不会是字段),那么您还有另一个问题,那就是必须有效地将其确定为最终类型,但是还有很多其他问题需要解决。