標籤:style blog http color ar 使用 java sp for
第三部分請點這裡
這裡來實現Obstacle類。其實flappybird的本質就是小鳥原地掉,然後幾根柱子在走。這也是在Game類裡,用obs.move()來實現遊戲邏輯的原因。
我們首先必須確定幾個資料。
0、柱子之間的間隙
1、柱子的最小值和最大值
2、柱子之間的間距
3、柱子的寬度
在螢幕高度確定的情況下,只要我們確定了上半部分的柱子的高度,那麼根據間隙,就能畫出兩個柱子。(tip:做個減法而已)
因此,一個障礙需要兩個資料來標示:
0、x值
1、高度
而move的實現,就是x的遞減。
還需要實現一個重要的功能,就是 柱子的添加和刪除。我們必須要決定,何時刪除一個既有的柱子,並且何時添加一個新的柱子。
但是在那以前,我們必須要決定使用什麼資料結構來儲存柱子。
容易發現,柱子的動態添加和刪除有先進先出的性質,那麼自然就是實現了Queue介面的LinkedList了。
那麼我們何時添加一個柱子?
答:當最後一個柱子,和最右距離差一個柱子間間隙的時候。
何時刪除一個柱子:
答:當第一個柱子的x值加寬度小於0時。
注意:Judge類需要和Obstacle公用LinkedList,要不然沒法算分。。這個耦合度還得在下一次重構中好好想想怎麼解決。。
Obstacle類的全部代碼:
import javax.swing.*;import java.util.LinkedList;import java.awt.*;import java.awt.event.*;public interface Obstacle { public void move(); public LinkedList<Pillar> getObstacles();}class SimpleObstacle implements Obstacle { private static final int SPEED = 2; public LinkedList<Pillar> pillar = new LinkedList<Pillar> (); int border; SimpleObstacle(int border) { this.border = border; init(); } private static int getRandomHeight() { int res = (int)(Math.random() * (Pillar.getHeiLmt() - 100) + 100); return res; } private void init() { pillar.add(new Pillar(this.border,getRandomHeight())); } public LinkedList<Pillar> getObstacles() { return pillar; } public void move() { boolean del = false; for (Pillar p : pillar) { p.setX(p.getX() - SPEED); if (p.getX() + Pillar.getWidLmt() <= 0) del = true; } if (del) pillar.remove(); Pillar tmp = pillar.getLast(); if (tmp.getX() + Pillar.getWidLmt() + Pillar.getWidGap() <= border) pillar.add(new Pillar(this.border,getRandomHeight())); }}class Pillar { int height; int x; private static final int WIDGAP = 200; private static final int HEIGAP = 150; private static final int WIDLMT = 100; private static final int HEILMT = 300; Pillar(int x,int height) { this.x = x; this.height = height; } public void setX(int x) { this.x = x; } public int getX() { return x; } public int getHeight() { return height; } public static int getWidGap() { return WIDGAP; } public static int getHeiGap() { return HEIGAP; } public static int getWidLmt() { return WIDLMT; } public static int getHeiLmt() { return HEILMT; }}
【原創】純OO:從設計到編碼寫一個FlappyBird (四)