移动多维数组中的元素

Move elements in a multidimensional array

本文关键字:元素 数组 移动      更新时间:2023-10-16

我通过使用多维数组(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到达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);
}

为什么不直接放一个"."就在把他移到新位置之前,在球员的位置上?