전함과 같은 게임을 만들고 전장 오브젝트를 무작위로 전투 맵 배열에 배치해야합니다. 내가 이것을 할 때를 제외하고, 배는 오른쪽 아래 사분면에 놓이지 않습니다 (그러나 그들은 다른 3 사분면에 성공적으로 배치됩니다). 나는 왜 그런지 모르겠습니다. 기본적으로, 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? –