如何使用struct在2D数组中移动播放器对象

时间:2019-04-30 16:39:04

标签: c++

我正在制作一个使用玩家结构并接受用户输入的迷宫游戏。该程序运行,但是当我输入命令来移动播放器时,什么都没有改变。关于出什么问题有什么建议吗?

// The function for user input
void getMove()
{

Player player1;

cout << "\n\nWhich direction would you like to go? ----- Treasure: " << numTreasure << "\n\n";
cout << "Up: 8\n";
cout << "Down: 2\n";
cout << "Left: 4\n";
cout << "Right: 6\n";

cin >> direction;


switch(direction)
{
    case 8 :
        if (currentBoard[player1.playerX - 1][player1.playerY] != '#'){
        player1.playerX--;
        }
        break;

    case 2 :
        if (currentBoard[player1.playerX + 1][player1.playerY] != '#'){
        player1.playerX++;
        break;
        }

    case 4 :
        if (currentBoard[player1.playerX][player1.playerY - 1] != '#'){
        player1.playerY--;
        break;
        }

    case 6 :
        if (currentBoard[player1.playerX][player1.playerY + 1] != '#'){
        player1.playerY++;
        break;
        }
}

switch(currentBoard[player1.playerX][player1.playerY]){
    case '*':
    cout << "You picked up a gold nugget!" << endl;
    board[player1.playerX][player1.playerY] = treasureSpace;
    numTreasure++;
    break;


  }
}

`

1 个答案:

答案 0 :(得分:0)

direction读入的cin >>变量的类型为char*。在切换情况下,您正在将此direction变量与整数进行比较,因此您将永远不会遇到任何这些情况,并且没有默认情况。我会将用户带来的direction切换为类型强制转换的int

`int_direction = (int)direction`

,然后更改切换用例以与int_direction

进行比较