2014-12-08 108 views
-2

我正在使用5x5二维数组进行简化的扫雷游戏。我的部分教学是制作这样的功能:创建扫雷游戏

该函数的取值介于1到25之间,并将该值转换为行列位置。您将需要使用参考参数来完成此操作。

我该如何做到这一点?

这是到目前为止我的代码:

int main() 
{ 
    int input; 
    char array[5][5]; 
    initBoard(array, 5); 
    populateBombs(array, 5); 
    cout << "Enter a value between 1 and 25 to check a space " << endl; 
    cin >> input; 
    printBoard(array, 5); 
    cout << endl; 
    return 0; 
} 

void initBoard(char ar[][5], int size) 
{ 
    for (int row = 0; row < 5; row++) 
    { 
     for (int col = 0; col < size; col++) 
     { 
      ar[row][col] = 'O'; 
     } 
    } 
} 

void printBoard(const char ar[][5], int size) 
{ 
    for (int row = 0; row < size; row++) 
    { 
     for (int col = 0; col < 5; col++) 
     { 
      cout << ar[row][col] << "\t"; 
     } 
     cout << endl; 
    } 
} 

问题的第二部分是创建一个“populateBomb”功能,我需要随机填充5位有炸弹。我必须用'*'字来表示炸弹。我可以利用任何技术来解决这些问题?

回答

0

您可以使用除法和模operators轻松地将索引转换为列和行。

// Take an index between 1 and 25 and return 0 based column and rows. 
// If you need 1 based column and rows add 1 to column and row 
void getPosition(int index, int& column, int& row) 
{ 
    row = (index - 1)/5; 
    column = (index - 1) % 5; 
} 

要选择一个随机的列和行使用std::rand

void getRandomPosition(int index, int& column, int& row) 
{ 
    getPosition(std::rand() % 25, column, row); 
} 
0

你说:

此功能需要1到25之间的值和值转换为行列位置。您将需要使用参考参数来完成此操作。

函数签名看起来应该像:

int foo(int in, int& row, int& col); 

这不是从描述清楚rowcol需求是否是504之间1之间。很明显,实施将基于预期产出的不同而有所不同。