我正在嘗試做一個簡單的戰鬥遊戲。我被困在試圖隨機將船放在我的板上。我有一種感覺,因爲我應該使用矢量而不是數組。但我不知道如何創建一個2D矢量。用隨機值填充我的數組C++
這是我到目前爲止有:
using namespace std;
void clearBoard(const int row, const int col)
{
int grid[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col;j++) {
grid[i][j] = 0;
cout << grid[i][j] << " ";
}
cout << endl;
}
}
void setShips(int max_ships1, int row, int col)
{
int ship_counter = 0;
while(ship_counter < max_ships1) {
int x = rand() % row;
int y = rand() % col;
int matrix[x][y]
if (matrix[x][y] != 1) {
ship_counter++;
matrix[x][y] = 1;
cout << matrix[x][y] << " ";
}
cout << endl;
}
}
int main(int argc, char* argv[])
{
int _row = atoi(argv[0]);
int _col = atoi(argv[2]);
int max_ships;
if (_row > _col) {
max_ships = _row;
}
else if (_col > _row) {
max_ships = _col;
}
else {
max_ships = _row;
}
cout << "enter the size of the board:";
cin >> _row >> _col;
clearBoard(_row, _col);
setShips(_row,_col,max_ships);
return 0;
}
如果用戶決定在3×3板,第一函數返回:
0 0 0
0 0 0
0 0 0
我希望能隨機產生1對代表戰列艦的位置。 這裏有一個3x3板爲例:
1 0 0
0 1 0
1 0 0
感謝。
'INT _row =的atoi(argv的[0]);'您的意思是'的argv [1]'? – AlexD
不要這樣想。我希望用戶輸入像「4 4」這樣的電路板尺寸,並在兩者之間留出空間。 – Jeremy78
這不是'argv'如何代表命令行參數。見例如http://stackoverflow.com/a/3024202。 – AlexD