2010-12-12 38 views
0

我正在爲一個類做遊戲,遊戲的一個元素正在顯示一些存儲在ArrayList中的捲心菜。該ArrayList必須是固定數量的20,10個好白菜和10個壞白菜。創建具有循環的對象的ArrayList,檢查重疊的對象

隨着捲心菜的創建,我想確保它們在顯示時不會重疊。我遇到麻煩的地方是,當我發現一個重疊的白菜時,我不確定如何返回並在它的位置創建一個新白菜。到目前爲止,當代碼發現重疊時,它只是停止循環。我想我有麻煩,正在擺脫循環,並重新啓動在索引不足。

這就是我迄今爲止所做的。任何建議將不勝感激。

 // Initialize the elements of the ArrayList = cabbages 
    // (they should not overlap and be in the garden) .... 
    int minX = 170 ; 
    int maxX = 480; 
    int minY = 15; 
    int maxY = 480; 
    boolean r = false; 
    Cabbage cabbage; 
    for (int i = 0; i < N_GOOD_CABBAGES + N_BAD_CABBAGES; i++){ 
     if (i % 2 == 0){ 
     cabbage = new GoodCabbage((int)(Math.random()* (maxX-minX + 1))+ minX, 
       (int)(Math.random()*(maxY-minY + 1))+ minY,window); 
     } 
     else { 
      cabbage = new BadCabbage((int)(Math.random()* (maxX-minX + 1))+ minX, 
        (int)(Math.random()*(maxY-minY + 1))+ minY,window); 
      } 
     if (i >= cabbages.size()){ 
     // compares the distance between two cabbages 
      for (int j = 0; j < cabbages.size(); j++){ 
       Point c1 = cabbage.getLocation(); 
       Cabbage y = (Cabbage) cabbages.get(j); 
       Point c2 = y.getLocation(); 
       int distance = (int) Math.sqrt((Math.pow((c1.x - c2.x), 2) + Math.pow((c1.y - c2.y),2))); 
       if (distance <= (CABBAGE_RADIUS*2) && !(i == j)){ 
        r = true; 
       } 
      } 
     if (r){ 
      break; 
      } 
     cabbage.draw(); 
     cabbages.add(i, cabbage); 
     }  
    } 

回答

0

看起來您正在製作捲心菜對象,然後將它們扔掉,這是一種(微不足道的)浪費。

爲什麼不選擇隨機的X和Y,檢查在那個地方是否有空間,然後當你有一個好點的時候做捲心菜?你只需要通過數字來攪拌,而不是製作和丟棄整個對象。此外,您不必重複隨機的位置代碼,好的和壞的捲心菜。

INT X,Y 做{// 挑x和y }而(cabbageOverlaps(X,Y,列表)

//創建那個X,Y白菜,並將其添加到列表

boolean cabbageOverlaps(int x,int y,ArrayList existingCabbages)

1

最簡單的方法是添加另一個循環。

一個do ... while循環適用於您至少需要一次迭代的情況。例如:

boolean overlapped; 
    do { 
     // create your new cabbage here 

     overlapped = /* check whether it overlaps another cabbage here */; 
    } while (overlapped); 

    cabbage.draw(); 
    cabbages.add(i, cabbage);