我认为问题出在我的构造函数中。它开始运行并且发射炸弹"进入2d阵列(网格),但它停在中间。 (有时它会全程运行......
SweeperGrid::SweeperGrid(const int initialRows, const int initialCols, const int density){
if ((initialRows<5 || initialCols<5) || (density<25 || density>75)) {
throw out_of_range("Grid not large enough (number of rows or columns cannot be fewer than 5) or density is too low or high (must be between 25% and 75%)");
}
numRows = initialRows;
numColumns = initialCols;
numBombs = 0;
grid = new SweeperCell*[numRows];
for(int i=0; i <numRows; i++){
grid[i] = new SweeperCell[numColumns];
}
srand(time(0));
for(int i=0; i<numRows; i++){
for (int j=0; j<numColumns; j++){
if(rand()%100+1<=density){
PlaceBomb(i, j);
}
}
}
}
这是PlaceBomb功能:
void SweeperGrid::PlaceBomb(int row, int col){
cout<<row<<", "<<col<<endl;
if ((row<0||row>=numRows)||(col<0||col>=numColumns)){
throw out_of_range("Out of bounds (PlaceBomb)");
}
At(row, col).PlaceBomb();
numBombs++;
//add if statements so it doesn't go out of bounds
if (row==0) {
At(row+1, col).IncrementNumAdjacent();
At(row, col-1).IncrementNumAdjacent();
At(row, col+1).IncrementNumAdjacent();
At(row+1, col+1).IncrementNumAdjacent();
At(row+1, col-1).IncrementNumAdjacent();
}
if (row==0&&col==0) {
At(row+1, col).IncrementNumAdjacent();
At(row, col+1).IncrementNumAdjacent();
At(row+1, col+1).IncrementNumAdjacent();
}
if (col==0) {
At(row-1, col).IncrementNumAdjacent();
At(row+1, col).IncrementNumAdjacent();
At(row, col+1).IncrementNumAdjacent();
At(row+1, col+1).IncrementNumAdjacent();
At(row-1, col+1).IncrementNumAdjacent();
}
if (row==numRows-1) {
At(row-1, col).IncrementNumAdjacent();
At(row, col-1).IncrementNumAdjacent();
At(row, col+1).IncrementNumAdjacent();
At(row-1, col-1).IncrementNumAdjacent();
At(row-1, col+1).IncrementNumAdjacent();
}
if (row==numRows-1&&col==numColumns-1) {
At(row-1, col).IncrementNumAdjacent();
At(row, col-1).IncrementNumAdjacent();
At(row-1, col-1).IncrementNumAdjacent();
}
if (col==numColumns-1) {
At(row-1, col).IncrementNumAdjacent();
At(row+1, col).IncrementNumAdjacent();
At(row, col-1).IncrementNumAdjacent();
At(row-1, col-1).IncrementNumAdjacent();
At(row+1, col-1).IncrementNumAdjacent();
}
if (row==0&&col==numColumns-1) {
At(row+1, col).IncrementNumAdjacent();
At(row, col-1).IncrementNumAdjacent();
At(row+1, col-1).IncrementNumAdjacent();
}
if (row==numRows-1&&col==0) {
At(row-1, col).IncrementNumAdjacent();
At(row, col+1).IncrementNumAdjacent();
At(row-1, col+1).IncrementNumAdjacent();
}
** IncrementNumAdjacent在另一个文件中,我确定它有效。
答案 0 :(得分:0)
您有太多IncrementNumAdjacent
次来电,其中一些可能超出范围。
例如:
if (row==0) {
At(row+1, col).IncrementNumAdjacent();
At(row, col-1).IncrementNumAdjacent();
如果col
此时为0,会发生什么?
在safeIncrementNumAdjacent(int row, int col)
类中使用SweeperGrid
方法可能更容易忽略超出范围的项目。类似的东西:
void SweeperGrid::safeIncrementNumAdjacent(int row, int col) {
if (row >= 0 && row < numRows && col >= 0 & col < numCols)
At(row, col).IncrementNumAdjacent();
}
然后只调用当前点周围的8个位置。