A.init(ROWS, COLS, life); while (true) { A.display(ROWS, COLS, life); string input; loop: cout << "Type 's' to save, 'l' to load, 'c' to change,'s' to stop, 'r' to rollback, or any other key to continue: "; cin >> input; if (input == "s") { string fileName; cout << "Enter file name: "; cin >> fileName; A.saveBoard(life, fileName, ROWS, COLS); } else if (input == "r") { A.display(ROWS, COLS, oldlife); } else if (input == "l") { string fileName; cout << "Enter file name: "; cin >> fileName; A.loadBoard(life, fileName, ROWS, COLS); } else if (input == "c") { int x, y; cin >> x >> y; if (x >= 0 && x < ROWS && y >= 0 && y < COLS) { life[x][y] = ~life[x][y]; A.display(ROWS, COLS, life); goto loop; } else { cout << "Invalid position!" << endl; } } else if (input == "s") { break; } A.run(ROWS, COLS, life, newLife); generation++; ;该代码无法返回上一代
时间: 2024-03-10 19:50:05 浏览: 13
您又发现了一个问题,这个代码确实没有实现返回上一代的功能。在代码中添加一个变量 `generation` 来记录当前的代数,然后在回滚时将代数减1,就可以回到上一代。可以按照以下方式修改代码:
```c++
int generation = 0; // 添加一个变量来记录当前的代数
A.init(ROWS, COLS, life);
while (true) {
A.display(ROWS, COLS, life);
string input;
loop:
cout << "Type 's' to save, 'l' to load, 'c' to change,'s' to stop, 'r' to rollback, or any other key to continue: ";
cin >> input;
if (input == "s") {
string fileName;
cout << "Enter file name: ";
cin >> fileName;
A.saveBoard(life, fileName, ROWS, COLS);
}
else if (input == "r") {
if (generation == 0) {
cout << "Cannot rollback anymore!" << endl;
}
else {
generation--;
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
life[i][j] = oldlife[i][j];
}
}
A.display(ROWS, COLS, life);
}
}
else if (input == "l") {
string fileName;
cout << "Enter file name: ";
cin >> fileName;
A.loadBoard(life, fileName, ROWS, COLS);
}
else if (input == "c") {
int x, y;
cin >> x >> y;
if (x >= 0 && x < ROWS && y >= 0 && y < COLS) {
life[x][y] = ~life[x][y];
A.display(ROWS, COLS, life);
goto loop;
}
else {
cout << "Invalid position!" << endl;
}
}
else if (input == "s") {
break;
}
A.run(ROWS, COLS, life, newLife);
generation++; // 更新当前的代数
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
oldlife[i][j] = life[i][j];
}
}
}
```
这样,当用户输入"r"时,如果当前的代数为0,代码会输出一个提示信息;否则,代码会将代数减1,并将oldlife的值复制到life中,然后再显示出来,实现了返回上一代的功能。