I read two sets of data from my example file, targetGrid and InitialGrid (each of which has multiple cells with colours and numbers in them) and output them. Then, I copied the initialGrid to the currentGrid and performed a clockwise rotation operation on the currentGrid in the rotateLeft function and split the Grid into multiple Cells in the rotateGrid for processing. But! I noticed that my currentGrid became 0 when I passed it into the rotateGrid function, and my targetGrid also became 0. Why is this?
Grid Game::rotateGrid(Grid& grid)
{
int n = static_cast<int>(grid.size());
Grid rotatedGrid(n, vector<Cell>(n));
cout << "rotateGrid函数中:" << endl;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
int newRow = n - 1 - j;
int newCol = i;
if (newRow >= 0 && newRow < n && newCol >= 0 && newCol < n) // 确保新索引在范围内
{
rotatedGrid[newRow][newCol] = grid[i][j];
cout << "Original: " << grid[i][j].number << " " << static_cast<int>(grid[i][j].color) << endl;
cout << "Rotated: " << rotatedGrid[newRow][newCol].number << " " << static_cast<int>(rotatedGrid[newRow][newCol].color) << endl;
}
}
}
return rotatedGrid;
}
void Game::rotateLeft(Grid& currentgrid)//逆时针转
{
cout << "rotateLeft函数中:" << endl;
printGrid(currentgrid);//能打印
history.push(currentgrid);//先把当前图像放入栈内,再旋转
currentgrid=rotateGrid(currentgrid);
printGrid(currentgrid);//无法打印
}
void Game::displayAndChoose()
{
cout << "目标图像:" << endl;
printGrid(targetGrid);
cout << endl;
cout << "当前图像:" << endl;
printGrid(currentGrid);
cout << "A. 左转90° "<< " B. 右转90° " << " C. 加热 " << " D. 撤回 " <<" E.退出游戏 " << endl;
cout << "你选择:";
char choice;
cin >> choice;
switch (choice)// 根据用户选择调用相应函数
{
case 'A':
case 'a'://支持小写字母格式
cout << "displayAndChoose函数中:" << endl;
printGrid(currentGrid);//能打印
rotateLeft(currentGrid);
printGrid(currentGrid);//无法打印
break;
case 'B':
case 'b':
rotateRight(currentGrid);
break;
case 'C':
case 'c':
heat(currentGrid);
break;
case 'D':
case 'd':
undo(currentGrid);
break;
case 'E':
case 'e':
cout << "你已退出游戏。" << endl;
isGameOver = true;
return;
default:
cout << "无效的选择,请重新输入。" << endl;
break;
}
if (compareGrids(currentGrid, targetGrid))
{
cout << "恭喜你成功了!" << endl;
isGameOver = true;
}
else
{
cout << endl;
cout << "继续游戏..." << endl;
}
}
I’ve asked GPT many times, but there’s no way to fix this at all. I tried to make the return value of the rotateGrid function a Grid&, so that the targetGrid doesn’t become 0 after an operation, but I don’t know what the principle is.
yuntun is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.