我正在制作Pacman游戏,但它与正常游戏略有不同。该游戏最初有3次机会。机会1由用户通过光标控制,所有移动都记录在文件中,直到Pacman被鬼魂抓住。
因此,简而言之,我想调度/处置KeyPressed
事件,以便不会调用已执行的操作事件,我将手动调用它。我的代码如下:
addKeyListener(new TAdapter());
class TAdapter extends KeyAdapter {
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (ingame)
{
if (key == KeyEvent.VK_LEFT)
{
System.out.println("moved L");
reqdx=-1;
reqdy=0;
try {
if(bw!=null)
bw.write("L");
} catch (IOException ex) {
Logger.getLogger(Board.class.getName()).log(Level.SEVERE, null, ex);
}
}
else if (key == KeyEvent.VK_RIGHT)
{System.out.println("moved R");
reqdx=1;
reqdy=0;
try {
if(bw!=null)
bw.write("R");
} catch (IOException ex) {
Logger.getLogger(Board.class.getName()).log(Level.SEVERE, null, ex);
}
}
else if (key == KeyEvent.VK_UP)
{System.out.println("moved U");
reqdx=0;
reqdy=-1;
try {
if(bw!=null)
bw.write("U");
} catch (IOException ex) {
Logger.getLogger(Board.class.getName()).log(Level.SEVERE, null, ex);
}
}
else if (key == KeyEvent.VK_DOWN)
{System.out.println("moved D");
reqdx=0;
reqdy=1;
try {
if(bw!=null)
bw.write("D");
} catch (IOException ex) {
Logger.getLogger(Board.class.getName()).log(Level.SEVERE, null, ex);
}
}
else if (key == KeyEvent.VK_ESCAPE && timer.isRunning())
{
ingame=false;
}
else if (key == KeyEvent.VK_PAUSE) {
if (timer.isRunning())
timer.stop();
else timer.start();
}
}
else
{
if (key == 's' || key == 'S')
{
ingame=true;
GameInit();
}
}
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == Event.LEFT || key == Event.RIGHT ||
key == Event.UP || key == Event.DOWN)
{
reqdx=0;
reqdy=0;
}
}
}
public void actionPerformed(ActionEvent e) {
System.out.println("action performed : " + e);
PlayGame();
}
public void PlayGame(Graphics2D g2d) throws IOException {
if (dying) {
Death();
} else {
if(pacsleft<=2)
{
System.out.println(pacsleft + " Yessss");
}
MovePacMan();
DrawPacMan(g2d);
moveGhosts(g2d);
CheckMaze();
}
}
我想在这里发送所有事件,条件如下。
if(pacsleft<=2)
{
System.out.println(pacsleft + " Yessss");
}