我为基于文本的游戏编写了一个代码,该游戏在每个回合开始时接受用户输入,并且应该根据输入执行不同的操作。例如,“up”应该将玩家向上移动网格上的1个空格,“look”应该显示该空间的指定场景。任何未指定为有效输入的内容都会导致系统输出错误消息“我不明白”。问题是:如果我输入类似“向上看向右看”的内容,它将按顺序执行每个命令,而不是显示错误消息。
string input = "";
while(input!="quit")
{
cin >> input;
if (input == "left") {
if (map[player1.y][player1.x - 1].isWall==true)
cout << map[player1.y][player1.x - 1].scene;
else if (player1.x > 0)
player1.x -= 1;
else
cout << "You walked off the face of the Earth, but grabbed the ledge just before it was too late. \n Somehow, you managed to gather enough strength to pull yourself back up. \n ...Maybe don't try that again." << endl;
}
else if (input == "right") {
if (map[player1.y][player1.x + 1].isWall==true)
cout << map[player1.y][player1.x + 1].scene << endl;
else if (player1.x < cols-1)
player1.x += 1;
else
cout << "You walked off the face of the Earth, but grabbed the ledge just before it was too late. \n Somehow, you managed to gather enough strength to pull yourself back up. \n ...Maybe don't try that again." << endl;
}
else if (input == "up") {
if (map[player1.y - 1][player1.x].isWall==true)
cout << map[player1.y - 1][player1.x].scene;
else if (player1.y > 0)
player1.y -= 1;
else
cout << "You walked off the face of the Earth, but grabbed the ledge just before it was too late. \n Somehow, you managed to gather enough strength to pull yourself back up. \n ...Maybe don't try that again." << endl;
}
else if (input == "down") {
if (map[player1.y + 1][player1.x].isWall==true)
cout << map[player1.y + 1][player1.x].scene;
else if (player1.y < rows-1)
player1.y += 1;
else
cout << "You walked off the face of the Earth, but grabbed the ledge just before it was too late. \n Somehow, you managed to gather enough strength to pull yourself back up. \n ...Maybe don't try that again." << endl;
}
else if (input == "look")
map[player1.y][player1.x].look();
else if (input == "take")
player1.pickupCons(map[player1.y][player1.x].potions[0]);
else
{
cout << "I don't understand... type something else!" << endl;
continue;
}
答案 0 :(得分:1)
您正在使用&#39;格式化的&#39;输入运算符>>
。基本上,格式化的输入操作将在看到空格字符时停止并返回。因此,如果您的输入向上看向右看&#39;,您的while循环实际上会对输入中的每个命令执行六次。
如果你不知道一行中的多个命令,请改用std::getline
:
while(getline(cin, input)) {
if (input == "quit") break;
if (input == "up") ...
}