【发布时间】: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