一个简单的解决方法是将方法移出NewCol
和NewRow
移出,从而使它们的状态不依赖于方法调用。
更好的解决方案是创建一个包含数组和当前位置的新结构,例如:
struct GameBoard {
char **fields;
int col;
int row;
};
然后将 GameBoard 作为输入:
void DisplayBoard(Gameboard& board,int row,int col,char direction){
int prevCol = board.col, prevRow = board.row;
if(direction =='a')
{
board.col--;
}
if(direction =='s')
{
board.row++;
}
if(direction == 'd')
{
board.col++;
}
if(direction == 'w')
{
board.row--;
}
array[prevRow][prevCol] = EMPTY;
array[board.row][board.col] = MAN;
for(int i = 0;i < row ; i++){
for(int c = 0; c < col; c++){
cout << array[i][c]<<" ";
}
cout <<endl<<endl;
}
}
更新
正如 beta 提议的那样,可以将这些事情作为成员函数来代替。由于存在安全检查,我还将使用 std::vector 而不是二维数组。因此,我的最终解决方案是:
class GameBoard {
private:
std::vector< std::vector<char> > _fields;
int _col;
int _row;
public:
GameBoard(int ncol, int nrow, int startcol, int startrow)
: _col(startcol), _row(startrow), _fields(nrow) {
for(int i = 0; i < nrow; i++) {
for (int j = 0; j < ncol; j++) {
_fields[i].push_back(EMPTY);
}
}
_fields[_row][_col] = MAN;
}
void move_man(char direction) {
int prevCol = _col, prevRow = _row;
switch(direction) {
case 'a': _col--; break;
case 'd': _col++; break;
case 'w': _row--; break;
case 's': _row++; break;
}
_fields[prevRow][prevCol] = EMPTY;
_fields[_row][_col] = MAN;
}
void display_board() {
for (int i = 0; i < _fields.size(); i++) {
for (int j = 0; j < _fields[i].size(); j++) {
std::cout << _fields[i][j] << " ";
}
std::cout << std::endl;
}
}
};