2011-09-22 107 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()'函数实际上看起来像现在更新了我的问题,现在不工作。 –