我正在製作一艘類似Battleship的遊戲,需要隨機將戰列艦物體放入戰地圖陣列中。除非我這樣做,否則船舶不會放在右下象限中(但它們已成功放置在其他三個象限中),我不知道爲什麼。基本上,我得到一個從0到地圖長度和高度以及隨機方向的隨機整數,然後檢查船是否適合,如果可以的話,將它放在地圖上。但它絕不會將它們放在右下角。C++:在2D數組中隨機放置一個數組
void BattleMap::placeRandomly(BattleShip& ship) {
bool correct = true;
int x_start,y_start,dir;
// size_x, size_y denote the length and height of the array respectively
int length = ship.getLength();
do{
correct = true;
x_start = abs(rand()%(size_x-length));
if(x_start+length > size_x) x_start -= length;
y_start = abs(rand()%(size_y-length));
if(y_start+length > size_y) y_start -= length;
dir = rand()%2; // 0 for vertical, 1 for horizontal;
for (int i = 0; i < length;i++) {
switch(dir){ // Check if there is already a ship in the candidate squares
case 0:
if(this->at(x_start,y_start+i)){
correct = false;
}
break;
case 1:
if(this->at(x_start+i,y_start)){
correct = false;
}
break;
}
}
}while(!correct);
// Place the ships into the array
....
}
的at()
功能是這樣的:
BattleShip*& BattleMap::at(int x, int y){
if(x > size_x || y > size_y)return 0;
// error: invalid initialization of non-const reference of type 'BattleShip*&' from a temporary of type 'int'
return board[x*size_y +y];
}
爲什麼downvote? –