學習路徑
- Swing 基礎:
JFrame 窗口、JPanel 繪圖面板、paintComponent(Graphics g) 繪製邏輯。
- 遊戲循環:使用
javax.swing.Timer (推薦) 或單獨線程 while(running) { update(); repaint(); sleep(); }。
- 輸入處理:
KeyListener 鍵盤控制炮台旋轉/發射。
- 圖片資源:
- 自繪:
g.drawRect、g.fillOval 簡單幾何圖形。
- 外部圖片:
ImageIO.read(getClass().getResource("/img/plane.png")) 從 classpath 加載。
- 素材站:OpenGameArt.org、Kenney.nl、itch.io (免費/CC0)。
- 碰撞檢測:矩形相交
Rectangle.intersects() 或圓形距離判斷。
最小可行原型
public class GamePanel extends JPanel implements ActionListener {
Timer timer = new Timer(16, this); // ~60 FPS
Image planeImg;
int planeX, planeY;
// ... 初始化加載圖片
@Override public void actionPerformed(ActionEvent e) {
updatePositions();
checkCollisions();
repaint();
}
@Override protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(planeImg, planeX, planeY, this);
// 繪製炮台、子彈、分數
}
}
推薦書籍
- 《Killer Game Programming in Java》 (Andrew Davison) — 經典免費電子書。
- 《Beginning Java Game Development with LibGDX》 — 現代框架入門。