我目前的任务是为大学制作战舰游戏。所以,我已经设法让船只在网格范围内下降。我现在唯一的问题是验证船舶与其他船舶相撞的船舶布局。我已经阅读过,大概最好的做法是两遍连接组件算法,但我不完全确定我将如何实现它。
这是我目前在 PlaceShips 方法中拥有的内容:
public void placeShips(){
for(int iter = 0; iter < 5; iter++){
size = shipSizes[iter];
rotation = randNum.nextInt(2)+1;
while(!valid){
rows = randNum.nextInt(10)+1;
cols = randNum.nextInt(10)+1;
if(rotation ==1){
if (cols > mGame.getmColumns()- size){
valid = false;
}
else{
//assumed that the connected component algorithm needs to go here
valid = true;
}
}
else if(rotation == 2){
if (rows > mGame.getmRows() - size){
valid = false;
}
else{
//assumed that the connected component algorithm needs to go here
valid = true;
}
}
}
valid = false;
//Draw ships
for(int i = 0; i < size; i++){
if(rotation == 1){
gridPos[cols-1][rows-1] = 1;
cols = cols + 1;
}
else if(rotation == 2){
gridPos[cols-1][rows-1] = 1;
rows = rows + 1;
}
}
}
}
}