Game.java
import javax.swing.JFrame;
public class Game {
public static void main(String [] args) {
JFrame window = new JFrame("飞碟大战");
window.setResizable(false);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.add(new GamePanel());
window.pack();
window.setLocationRelativeTo(null);
window.setVisible(true);
}
}
GamePanel.java
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import javax.swing.JPanel;
public class GamePanel extends JPanel implements Runnable, KeyListener {
// 640 480
public static int WIDTH = 320;
public static int HEIGHT = 240;
public static int SCALE = 2;
// 游戏线程 游戏循环
private Thread thread;
private boolean running;
// 实现双缓冲
private BufferedImage image;
private Graphics2D g;
private Player player;
public static ArrayList<Bullet> bullets;
// 设置窗口大小以及事件的捕捉
public GamePanel() {
setPreferredSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
setFocusable(true);
requestFocus();
}
// 初始化游戏线程并启动游戏线程 增加键盘监听器
public void addNotify() {
super.addNotify();
if (thread == null) {
thread = new Thread(this);
thread.start();
}
addKeyListener(this);
}
private void init