我通過使用多維數組來跟蹤角色在遊戲板上的位置(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);
}
你想在G的老廣場上做什麼?單個字符數組的問題是您無法將地形與字符或項目分開。 – 2014-10-08 20:42:09
我喜歡它是空白的,這將是'。'所以你說的是我需要多個數組? – 2014-10-08 20:44:22
@FelipeZC'我的問題是:如何在多維數組中移動一個元素(G)(board [10] [20])「你不應該把這個相當重要的信息作爲你設計的一部分,在你寫任何代碼之前? – PaulMcKenzie 2014-10-08 21:02:43