2014-10-08 37 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