2011-09-22 4 views
1

전함과 같은 게임을 만들고 전장 오브젝트를 무작위로 전투 맵 배열에 배치해야합니다. 내가 이것을 할 때를 제외하고, 배는 오른쪽 아래 사분면에 놓이지 않습니다 (그러나 그들은 다른 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]; 
} 
+1

왜 downvote? –

답변

2

.

x_start = rand()%size_x; 
y_start = rand()%size_y; 

을 그리고 측면 떨어져가는 경우에() 함수 반환 사실하자 : 그냥 x_start 및 y_start 어디서나 할 수

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 
} 
+0

'at()'이지도 측면을 볼 때'false'를 반환해야한다는 것을 의미합니까? –

+0

at() 함수는 x, y에 배가있을 때 true를 반환합니다. 보드 외부에 선박이있는 것처럼 가장하는 경우, 기존의 두 개의 선박이 겹치지 않도록 코드가 보드에서 배를 떨어 뜨리는 것을 방지합니다. –

+0

필자는'at()'함수가 실제로 어떻게 생겼는지에 대한 나의 질문을 업데이트했습니다. 지금은 작동하지 않습니다. –

관련 문제