我正在为一个类做游戏,游戏的一个元素正在显示一些存储在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);
}
}