2011-09-22 70 views
1

我正在製作一艘類似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]; 
} 
+1

爲什麼downvote? –

回答

2

您正試圖太硬,以保持船從準備離開側面。只要允許x_start和y_start到任何地方:

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

而且讓你在()函數返回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 
} 
+0

你的意思是'at()'應該在地圖邊看去時返回'false'嗎? –

+0

看起來你的at()函數在x,y處有一艘船時返回true。如果你假裝在船外的任何地方都有船,那麼爲了確保兩艘船不重疊,現有的代碼也會阻止它將船從船上卸下。 –

+0

我已經用我的'at()'函數實際上看起來像現在更新了我的問題,現在不工作。 –