我运行此代码但是当我到达屏幕边缘时,它不允许我输入新的行进方向而不是控制台关闭..需要帮助解决这个问题
class weapon
{
public:
weapon();
weapon(int x, int y);
int xPos;
int yPos;
};
weapon::weapon()
{
xPos = 0;
yPos = 0;
}
weapon::weapon(int x, int y)
{
xPos = x;
yPos = y;
}
struct Game
{
weapon Bow;
weapon Sword;
};
int main()
{
weapon * Bow = new weapon(4, 6); // how to add cout to this to show you have the weapon?
int xPos = 1;
int yPos = 1;
char input = '#';
while (xPos >= 1 && xPos <= 20 && yPos >= 1 && yPos <= 20)
{
cout << "Current x-coord = " << xPos << " Current y-coord = " << yPos << endl;
cout << "Which direction would you like to travel? Enter N, E, S or W" << endl;
cin >> input;
switch (input)
{
case 'E': case 'e':
++xPos;
break;
case 'W': case 'w':
--xPos;
break;
case 'N': case 'n':
++yPos;
break;
case 'S': case 's':
--yPos;
break;
}
if (xPos <= 0 || xPos >= 21 || yPos <= 0 || yPos >= 21)
{
cout << "There is a wall in the way!" << endl; //how do i make it continue the game after hitting a wall
cout << "Which direction would you like to travel? Enter N, E, S or W" << endl;
//cin >> input; // this whole section needs some fixing
}
}
return 0;
}
正确的解决方案应该返回到while循环,允许用户为旅行输入新的输入方向。
答案 0 :(得分:0)
到达墙后,while
- 条件为false,循环退出。
我会修改条件而不是先修改然后检查它是否有效:
while (xPos >= 1 && xPos <= 20 && yPos >= 1 && yPos <= 20)
{
cout << "Current x-coord = " << xPos << " Current y-coord = " << yPos << endl;
cout << "Which direction would you like to travel? Enter N, E, S or W" << endl;
cin >> input;
switch (std::toupper(input))
{
case 'E':
if (xPos < 20)
++xPos;
else
cout << "There is a wall to the east!" << endl;
break;
case 'W':
if (xPos > 1)
--xPos;
else
cout << "There is a wall to the west!" << endl;
break;
// and the other two cases...
}