程序是一个简单打灰机的游戏:
灰机从左上角开始水平飞行,撞墙后下移一行,向相反方向飞。按键盘上任意键可以发射子弹,如果子弹击中灰机,灰机爆炸,从初始位置重新开始。如果灰机到达窗口底端,游戏结束。
现在的问题是:UFO从左往右飞,子弹能打中UFO,UFO能回到初始位置,如果UFO是从左往右飞,子弹即使打中UFO,UFO也不会爆炸,而是继续飞。
请帮我看看是不是checkForHit()方法有什么问题。
- Java code
/* * filename: UFO.java */import acm.graphics.*;import acm.program.*;import java.awt.Color;import java.awt.event.*;public class UFO extends GraphicsProgram { /* * UFO速度 */ private static final int UFO_SPEED = 10; /* * 子弹速度 */ private static final int BULLET_SPEED = 20; /* * 程序运行时延迟时间 */ private static final double DELAY_TIME = 50; /* * 初始UFO移动位置 */ private double xVal = UFO_SPEED; private double yVal = 0; /* * 初始子弹移动位置 */ private double xBVal = 0; private double yBVal = 0; public void run() { setup(); while (isGameOver) { moveUFO(); moveBullet(); checkForHit(); checkForCollition(); checkIsGameOver(); pause(DELAY_TIME); } } private void setup() { /* * 初始化UFO */ gr = new GRect(50,10); gr.setLocation(0,0); gr.setVisible(true); gr.setFilled(true); gr.setFillColor(Color.black); add(gr); /* * 初始化子弹 */ gb = new GRect(5,10); gb.setVisible(true); gb.setColor(Color.black); gb.setLocation(getWidth()/2, getHeight()-gb.getHeight()); add(gb); /* * 初始化底端 */ gl = new GLine(0,getHeight()-12,getWidth(),getHeight()-12); add(gl); this.addKeyListeners(); } /* * UFO移动方法 */ private void moveUFO() { gr.move(xVal, yVal); } /* * 子弹移动方法 */ private void moveBullet() { if(gb.getY()>-gb.getHeight()) { gb.move(xBVal, yBVal); } else { gb.setLocation(getWidth()/2, getHeight()-gb.getHeight()); yBVal = 0; } } /* * 检查UFO是否碰墙,如碰墙,下移一行,将向相反方向移动 */ private void checkForCollition() { if (gr.getX()+gr.getWidth()>getWidth()) { gr.setLocation(gr.getX(),gr.getY()+gr.getHeight()); xVal = -UFO_SPEED; } else if (gr.getX()< 0) { gr.setLocation(gr.getX(),gr.getY()+gr.getHeight()); xVal = UFO_SPEED; } } /* * 检查子弹是否击中UFO,若击中,UFO爆炸后,子弹和UFO同时还原到初始位置 */ private void checkForHit() { if ((gr.getY()+10)==gb.getY()){ if (gr.getX()<=gb.getX()){ if ((gr.getX()+50)>=(gb.getX()+5)){ xVal = 0; yVal = 0; xBVal = 0; yBVal = 0; gb.setVisible(false); gr.setVisible(false); pause(50); gr.setVisible(true); pause(50); gr.setVisible(false); pause(50); gr.setVisible(true); pause(50); gr.setVisible(false); pause(50); gr.setVisible(true); pause(50); gr.setVisible(false); pause(50); gr.setVisible(true); gb.setVisible(true); gr.setLocation(0,0); gb.setLocation(getWidth()/2, getHeight()-gb.getHeight()); xVal = UFO_SPEED; yVal = 0; xBVal = 0; yBVal = 0; } } } } /* * 检查是否结束,结束条件为UFO到达底端 */ private void checkIsGameOver() { if(gr.getY()+gr.getHeight()>=gl.getY()){ GLabel gll = new GLabel("Game Over!"); add(gll,getWidth()/2-gll.getWidth()/2,getHeight()/2-gll.getHeight()/2); isGameOver = false; } } /* * 每次按任意键,发射一发子弹 */ public void keyTyped(KeyEvent e) { yBVal = -BULLET_SPEED; } private GRect gr; private GRect gb; private GLine gl; private Boolean isGameOver = true;}