【问题标题】:Creating an ArrayList of objects with a loop, checking for overlapping objects使用循环创建对象的 ArrayList,检查重叠对象
【发布时间】:2011-05-24 09:49:01
【问题描述】:

我正在为一个班级制作游戏,游戏的一个元素是显示许多卷心菜,这些卷心菜存储在一个 ArrayList 中。这个ArrayList必须是固定的20个,Good Cabbage 10个,Bad Cabbage 10个。

创建卷心菜时,我想确保它们在展示时不会重叠。我遇到麻烦的地方是,当我发现一个重叠的卷心菜时,我不知道如何回去并在它的位置创建一个新的卷心菜。到目前为止,当代码发现重叠时,它只是停止循环。我想我无法正确跳出循环并在未填充的索引处重新启动。

这是我到目前为止所拥有的。任何建议将不胜感激。

        // 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);
        }       
    }

【问题讨论】:

    标签: java loops arraylist duplicates


    【解决方案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);
    

    【讨论】:

      【解决方案2】:

      看起来你正在制作卷心菜对象然后将它们扔掉,这是一种(微不足道的)浪费。

      为什么不随机选择X和Y,检查那个位置是否有空间,然后在你有好的位置时制作卷心菜?您将只是搅动数字,而不是制作和丢弃整个对象。此外,您不必为好卷心菜和坏卷心菜重复随机位置代码。

      int x, y 做 { // 选择 x 和 y } while (cabbageOverlaps(x,y,list)

      // 在 x,y 处创建一个卷心菜,并将其添加到列表中

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-03-29
        • 1970-01-01
        • 2012-11-29
        • 2015-02-23
        • 2016-11-11
        • 1970-01-01
        • 2011-04-28
        相关资源
        最近更新 更多