2010-12-12 62 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);