frame。setLocationRelativeTo(null);
frame。setVisible(true);
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Fly");
startGame(frame);
}
运行原理:绘制界面时通过创建JFrame来新建一个容器,将所需组件添加到JPanel内部,最后把JPanel放入容器即可。用户可以通过鼠标单击事件即可启动游戏。实现主要代码如下:
public void mouseClicked(MouseEvent e){
switch (state) {
case START:
state = RUNNING;
break;
}
}
2。绘制飞行物(结果见图5。1。2)
核心代码如下:
/**Graphics g画笔,画飞行物对象 */
public void paint(Graphics g){
g。drawImage(background,0,0,null);
paintHero(g);
paintFlyingObjects(g);
paintBullets(g);
paintScore(g);
paintState(g);
}
/**画状态图(启动,暂停)*/
public void paintState(Graphics g){
switch (state) {
case START:
g。drawImage(start,0,0,null);
break;
case PAUSE:
g。drawImage(pause,0,0,null);
break;
}
}
/**画分数*/
public void paintScore(Graphics g){
g。setColor(new Color(0xFF0000));//设置颜色为纯红
g。setFont(new Font(Font。SANS_SERIF,Font。BOLD,22));
g。drawString("Score: "+score, 10, 25);
g。drawString("Life: "+hero。getLife(), 10, 45);
}
/**画英雄机*/
public void paintHero(Graphics g){
g。drawImage(hero。image,hero。x,hero。y,null);
}
/**画敌人*/
public void paintFlyingObjects(Graphics g){
for(int i=0;i<flyings。length;i++){
FlyingObject f = flyings[i];
g。drawImage(f。image,f。x,f。y,null);
}
}
/**画子弹对象*/
public void paintBullets(Graphics g){
for(int i=0;i<bullets。length;i++){
Bullet b = bullets[i];
g。drawImage(b。image,b。x,b。y,null);
}
}
3.绘制游戏说明界面
核心代码如下:
public class Frame2 extends JPanel{
public static final int WIDTH = 400; //宽
public static final int HEIGHT = 654; //高
private JTextArea jTextArea;
private JScrollPane jScrollPane;
private ImageIcon imageIcon;
private String instructions = "进入游戏页面后,单击鼠标即可开始游戏。
使用鼠标进行上、下、左、右移动" + "可以控制英雄机的移动。游戏开始后,英
雄机拥有3条生命,任何飞行物碰撞到"+"英雄机则减少一条生命,一旦英雄机生
命值为0游戏结束。";
public Frame2() {
imageIcon = new ImageIcon("src/entity/pictures/background.png");
jTextArea = new JTextArea(instructions,8, 15){
Image image = imageIcon。getImage();
Image grayImage = GrayFilter。createDisabledImage(image);
{来-自~优+尔=论.文,网www.youerw.com +QQ752018766-
setOpaque(false);
} // 设置透明
@Override
public void paint(Graphics g) {
g。drawImage(grayImage, 0, 0, this);
super。paint(g);
}
};
jTextArea。setFont(new Font(Font。DIALOG_INPUT,Font。BOLD,24)); java飞机大战游戏的设计与实现(4):http://www.youerw.com/jisuanji/lunwen_92932.html