2012-10-12 71 views
0

我創建了一個包含所有內容的pacman遊戲,但問題在於幽靈和它們的動畫需要大量的代碼。對於不同的對象在Java中的每個循環

例如:

每鬼需要3如果在那個是每鬼20行代碼的時刻和語句,如果我有在遊戲中是無用的編碼3×20 = 60行3個鬼..

與我的PHP經驗我會說..使用foreach循環或類似的東西..但我應該怎麼做到這一點在Java?有人能給我一個例子嗎?我現在這樣做的方式發佈如下:

創建幽靈對象;

DrawPacMan ghost1 = new DrawPacMan(); 
DrawPacMan ghost2 = new DrawPacMan(); 

和繪畫是這樣:

int g1x = 0; 
boolean g1r = true; 
public void paintComponent(Graphics g) { 
    super.paintComponent(g); 
    // pacman movement 
    diameter = 75; 
    pacman.drawPacMan(g, getHorPlaats(), getVerPlaats(), diameter, getView(), Color.yellow); 
    // ghosts movement 
    if(g1r == true) { 
     g1x += ghostSpeed;   
    }  
    if(g1r == false) {   
     g1x -= ghostSpeed; 
    } 
    if(g1x == 500 || g1x == 0) { 
     g1r = !g1r; 
    } 
    System.out.println(g1r); 
    ghost1.drawGhost(g, g1x, 40, diameter, Color.red); 
    ghost2.drawGhost(g, 170, 70, diameter, Color.blue); 
} 
+0

究竟是你想解決的問題是什麼?太多的代碼行?代碼的低效率重用?廣泛的時間處理鬼魂的移動? –

+2

@ Dr.Dredel OP很清楚地說明了他的問題:這是代碼設計。 –

回答

7

它看起來對我來說,你不是在面向對象的方式接近這一點。爲什麼不使用鬼魂集合,例如。 List<Ghost>並用它的位置,顏色等來定義Ghost對象?

這行:然後

ghost1.drawGhost(g, g1x, 40, diameter, Color.red); 

將與

ghost.draw(g); 

更換和你遍歷列表,呼籲draw()每個。

for(Ghost ghost : ghosts) { 
    ghost.draw(g); // pass in the graphics context 
    } 

每個鬼知道它的位置,顏色,狀態等,並且可以創建你喜歡儘可能多:

List<Ghost> ghosts = new ArrayList<Ghost>(); 
    for (int i = 0; i < 10; i++) { 
     ghosts.add(new Ghost()); 
    } 
+0

@OPThis是一個更好的方式...也許讀一點關於戰略模式 – Atul

+0

感謝您的例子!但我的列表應該如何?我對Java非常陌生,但我不知道大部分函數。 – Reshad

+0

@Reshad - 請參閱上面修改後的答案 –

0
  1. 傳遞鬼對象作爲另一個參數在同一個函數paintComponent(Graphics g,Ghost gr)
  2. 您可以使條件語句inline,例如g1r == true? G1X + = ghostSpeed:G1X - = ghostSpeed
2

因爲你似乎是新的Java和還結識了最好的成語,我會的東西,是不是直接回答你的問題提出建議,但所以從更一般的意義上講。您的代碼

if(g1r == true) { 
    g1x += ghostSpeed;   
}  
if(g1r == false) {   
    g1x -= ghostSpeed; 
} 

可以改寫爲剛剛

g1x += ghostSpeed * (g1r? 1 : -1); 

的一般注意事項:從不比較布爾字面值。 b == trueb相同,b == false!b相同。

此代碼

if (g1x == 500 || g1x == 0) { 
    g1r = !g1r; 
} 

可能會導致在運行時的錯誤,你不擊劍,代碼在它前面:g1x可以輕鬆跨過自己的極限。你應該寫

if (g1x >= 500) { g1x = 500; g1r = false; } 
else if (g1x <= 0) { g1x = 0; g1r = true; } 
+0

感謝您的提示!第二個讓我困惑,而我在想,我寫的代碼工作,所以我沒有回頭看它..但這似乎更多的邏輯!會改變這種方式:) – Reshad