我正在爲一個類做遊戲,遊戲的一個元素正在顯示一些存儲在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);
}
}