我通过使用多维数组(board[10][20]
)跟踪角色在游戏板上的位置。为了允许用户移动,我创建了一个方法movePlayer()
,它修改了'G'所在位置索引的值。
每当我这样做时,角色'G'确实移动,但是'G'的先前位置仍然在游戏牌上,所以有两个'G'。我的问题是:如何在多维数组中移动元素(G)?
主要功能:
char userInput;
int main()
{
Game obj1;
cout << "New Game (y/n)" << endl;
cin >> userInput;
if(userInput == 'y')
{
obj1.gameBoard();
obj2.movePlayer();
}
}
游戏(类)的.cpp:
Game::Game()
{
for(int x = 0; x < 10 ; x++)
{
for(int y = 0; y < 20 ; y++)
{
board[x][y]= '.';
}
}
player = 'G';
treasure = 'X';
srand(time(0));
p_Pos1X = rand()%10;
p_Pos1Y = rand()%20;
t_Pos1X = rand()%10;
t_Pos1Y = rand()%20;
endSwitch = 0;
}
void Game::gameBoard()
{
printBoard(p_Pos1X,p_Pos1Y);
}
void Game::printBoard(int px, int py)
{
for(int x = 0; x < 10; x++)
{
for(int y = 0; y < 20 ; y++)
{
board[px][py] = player;
board[t_Pos1X][t_Pos1Y] = treasure;
cout << board[x][y] ;
}
cout << endl;
}
}
void Game:: movePlayer()
{
cin >> playerM;
switch(playerM)
{
case 'W':
case 'w':
movePlayerUp(p_Pos1X);
}
}
void Game::movePlayerUp(int m)
{
m = m - 1;
printBoard(m,p_Pos1Y);
}
答案 0 :(得分:0)
如果项目的目标不是点阵矩阵和G达到X你不需要存储矩阵,当然按照你的方法,下面的代码我希望成为printBoard中的变化的解决方案功能
Game::Game()
{
for(int x = 0; x < 10 ; x++)
{
for(int y = 0; y < 20 ; y++)
{
board[x][y]= '.';
}
}
player = 'G';
treasure = 'X';
srand(time(0));
p_Pos1X = rand()%10;
p_Pos1Y = rand()%20;
t_Pos1X = rand()%10;
t_Pos1Y = rand()%20;
endSwitch = 0;
}
void Game::gameBoard()
{
printBoard(p_Pos1X,p_Pos1Y);
}
void Game::printBoard(int px, int py)
{
for(int x = 0; x < 10; x++)
{
for(int y = 0; y < 20 ; y++)
{
if(x==px && y==py)
{
cout << player ;
}else if(x== t_Pos1X && y== t_Pos1Y ){
cout << treasure;
}else{
cout << board[x][y] ;
}
}
cout << endl;
}
}
void Game:: movePlayer()
{
cin >> playerM;
switch(playerM)
{
case 'W':
case 'w':
movePlayerUp(p_Pos1X);
}
}
void Game::movePlayerUp(int m)
{
m = m - 1;
printBoard(m,p_Pos1Y);
}
答案 1 :(得分:-2)
为什么不放一个'。'在将球员移到新球员之前的位置?