實現玩家飛機(Hero)的創建、四向移動、螢幕邊界約束,遵循「單一職責、解耦」原則,不在 Hero 內處理子彈發射、敵機管理等邏輯。
createHero()),提供 moveLeft/Right/Up/Down()。FLY 索引對應飛機圖片。WIDTH、HEIGHT。public class Hero extends Fairy {
private static Hero hero;
private static final Log log = Log.getLog("Hero");
private Hero(int x, int y) {
super(Resources.FLY, x, y); // 傳入圖片索引、初始座標
}
/** 單例工廠 */
public final static Hero createHero(int x, int y) {
if (hero == null) hero = new Hero(x, y);
return hero;
}
/** 向左移動,左邊界保留 16 像素 */
public final void moveLeft() {
if (getX() >= 16) move(-8, 0);
}
/** 向右移動,右邊界預留 16 像素 */
public final void moveRight() {
if (getX() <= Platform.WIDTH - 16) move(8, 0);
}
/** 向上移動,頂部保留 8 像素 */
public final void moveUp() {
if (getY() >= 8) move(0, -8);
}
/** 向下移動,底部預留 38 像素(狀態欄/操作區) */
public final void moveDown() {
if (getY() <= Platform.HEIGHT - 38) move(0, 8);
}
}
public abstract class Fairy {
protected int x, y;
protected Image img;
public Fairy(int resId, int x, int y) {
this.img = ResourceManager.getImage(resId);
this.x = x; this.y = y;
}
public void move(int dx, int dy) { x += dx; y += dy; }
public int getX() { return x; }
public int getY() { return y; }
public void paint(Graphics g) {
g.drawImage(img, x, y, Graphics.TOP | Graphics.LEFT);
}
}
// 遊戲初始化
Hero hero = Hero.createHero(Platform.WIDTH/2, Platform.HEIGHT - 50);
// 按鍵處理
protected void keyPressed(int keyCode) {
switch (KeyCodeAdapter.getInstance().adoptKeyCode(keyCode)) {
case KeyCodeAdapter.LEFT_KEY: hero.moveLeft(); break;
case KeyCodeAdapter.RIGHT_KEY: hero.moveRight(); break;
case KeyCodeAdapter.UP_KEY: hero.moveUp(); break;
case KeyCodeAdapter.DOWN_KEY: hero.moveDown(); break;
}
repaint();
}
Hero.MARGIN_LEFT 等常量,便於適配不同分辨率。BulletManager、敵機由 FoeManager 處理,符合高內聚低耦合。getCollisionRect(),精準碰撞檢測。