2014-10-08 53 views
0

我通過使用多維數組來跟蹤角色在遊戲板上的位置(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

你想在G的老廣場上做什麼?單個字符數組的問題是您無法將地形與字符或項目分開。 – 2014-10-08 20:42:09

+0

我喜歡它是空白的,這將是'。'所以你說的是我需要多個數組? – 2014-10-08 20:44:22

+0

@FelipeZC'我的問題是:如何在多維數組中移動一個元素(G)(board [10] [20])「你不應該把這個相當重要的信息作爲你設計的一部分,在你寫任何代碼之前? – PaulMcKenzie 2014-10-08 21:02:43

回答

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); 

} 
-2

爲什麼不乾脆把 ''在將球員轉移到新球員之前,球員的位置?

+0

這不是一個答案。如果你願意,請給OP添加一條評論。不,我沒有倒下。 – 2014-10-08 20:49:44