【发布时间】:2021-09-25 08:58:08
【问题描述】:
这里是 C++ 编程的初学者!
我正在编写一个两人玩井字游戏的项目。我的网格是一个向量大小为 3x3 的 2D 向量,开头用点填充。程序向用户询问 x 和 y 坐标,并将点替换为 X 或 0。
现在,我的任务是以两种方式增加网格大小,例如,当给定坐标 x 或 y 比游戏板的大小大 1 时,板将向右和向下扩展,或者如果给定坐标例如 x=2 和 y=0,棋盘应向左向上扩展。
这是我尝试处理这种情况的方法,我做了两个函数:
这里有我的向量的向量:
int grid_size = 3;
vector< vector<char>>grid(grid_size, vector<char>(grid_size, '.'));
第一个尝试处理向下和向右扩展:
void expand_grid_down_right(vector<vector<char>>&grid){
//Let's make some helpers
vector<char> grid_row;
vector<char> grid_col;
//Adds new row but not column
for(int i = 0; i < grid.size();i++){
grid_row.push_back('+');
}
vector<char> new_line(grid_row.size(), '+');
grid.push_back(new_line);
for(unsigned int i = 0; i < grid.size(); i++){
cout << (i+1)%10 << ' ';
}
cout << endl;
//Draws the grid with three rows of dots and one row of plus-signs
//Column numbered with four appears blank?
//If I try to touch this with at(i).at(j) it gives out of bounds error
for (auto &grid_row : grid) {
for (auto &cell : grid_row) {
cout << cell << ' ';
}
cout << endl;
}
//But this prints it as one column?
for(int i=0; i<grid.size();i++){
for(int j=0; j<grid[i].size(); j++){
cout << grid[i][j] << endl;
}
}
//I want to at to the new column the char = '.' but not sure what this does?
for(int i=0; i<grid.size();i++){
for(int j=0; j<grid[i].size(); j++){
grid.at(i).at(j) = '.';
}
}
}
第二个尝试处理向上和向左扩展:
void expand_grid_up_left(vector<vector<char>>&grid){
unsigned int dimension = grid.size();
vector<char> grid_col;
//Add new row of plus-signs to the top row but does not shift
//So from 3x3 to 4x3 but how to get it 4x4?
for (int i=0; i<dimension; i++){
grid_col.insert(grid_col.begin(),'+');
}
vector<char> line(grid_col.size(), '+');
grid.insert(grid.begin(), line);
for (auto &grid_col : grid) {
for (auto &cell : grid_col) {
cout << cell << ' ';
}
cout << endl;
}
}
但它们都没有按应有的方式工作。我正在使用加号来查看添加新行的位置。向下和向右扩展为行生成,它绘制了一个空列 4。如果我尝试通过索引循环访问它,它只会绘制一个包含所有点和加号的列。应该向左和向上扩展的只放一行,但不向左。
空列 4 是否存在,我如何使它们工作以使扩展从 3x3 变为 4x4 或更广泛意义上的 NxN?
【问题讨论】:
标签: c++ vector tic-tac-toe