我正在制作一款类似战舰的游戏,需要将战舰对象随机放置到战斗地图数组中。除非我这么做,否则船只永远不会被放置在右下角象限中(但它们会被成功地放置在其他3个象限中),我不知道为什么。基本上,我得到一个介于0和地图长度和高度之间的随机整数,以及一个随机方向,然后检查船是否适合在那里,如果可以,就把它放在地图上。但它从不把它们放在右下角。
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];
}
你太用力了,不让船偏离船舷。只要允许x_start和y_start在任何地方:
x_start = rand()%size_x;
y_start = rand()%size_y;
并让你的at()函数返回true,如果它离开了一边:
bool BattleMap::at(int x,int y) const
{
if (x>=size_x || y>=size_y) return true;
// regular check for a ship at x,y here
}