java - 在文字冒险游戏中移动
问题描述
我正在做一个简单的文本冒险项目。当我运行代码时,当我尝试输入右/左/向前/向后两次时,它将不起作用。它重置到游戏的开始。
此外,当我输入任何不符合这些 if 语句顺序的输入时,例如向前然后向左,程序会进入我的故障安全状态。我之前问过这个问题,有人回答说我应该在我的代码中使用 if else。我可以为这个项目使用哪些其他替代方案?
故障保险也不起作用。我按批准的方向键入,但故障保护无限期地继续。
Scanner key = new Scanner(System.in);
int x, y;
x = 0;
y = 0;
String gameStart = "c";
String direction = "c";
System.out.print("Welcome to my text adventure game!\nIf you want to play, type in 'Start'");
gameStart = key.next();
while(!"Start".equals(gameStart))
{
System.out.print("Incorrect input. Type in 'Start' to begin: ");
gameStart = key.next();
}
while(gameStart.equals("Start"))
{
direction = "";
x = 0;
y = 0;
System.out.println("");
System.out.print("You wake up in an extremly small room. You estimate it to be a perfectly sized 3x3 room. Based on your estimation, your in the center of the room. Dispite that there is a bed directly behind you, you wake up on a circular rug. Weird, but, the door's right in front of you. Time to escape!\nYou can move forward, backwards, left and right.");
direction = key.next();
if(direction.equals("right") || direction.equals("Right"))
{
x++;
System.out.print("You walk to the right.");
direction = key.next();
}
else if (direction.equals("left") || direction.equals("Left"))
{
x--;
System.out.print("You walk to the left.");
direction = key.next();
}
else if (direction.equals("forward") || direction.equals("Forward"))
{
y++;
System.out.print("You walk Forward.");
direction = key.next();
}
else if (direction.equals("backwards") || direction.equals("Backwards"))
{
y--;
System.out.print("You walk backwards.");
direction = key.next();
}
else
{
do
{
System.out.print("Sorry, you can't do that. Try again:");
direction = key.next();
}
while(!direction.equals("right")|| !direction.equals("Right") || !direction.equals("left") || !direction.equals("Left") || !direction.equals("forward") || !direction.equals("Forward") || !direction.equals("backwards") || !direction.equals("Backwards"));
}
while(gameStart.equals("Start"))
{
if (x<-2 || x>2 || y<-2 || y>2)
{
System.out.println("ERROR: OUT OF BOUNDS");
System.exit(0);
}
if (x==-2 || x==2)
{
System.out.println("You try to walk further, however, you run right into a wall.");
x--;
}
if (y==-3 || y==3)
{
System.out.println("You try to walk further, however, you run right into a wall.");
y--;
}
}
}
解决方案
在你的 while 循环后面有一个分号,这使它立即结束。
while(gameStart.equals("Start"));
此外,这段代码中有很多不好的做法,比如:
- 与文字字符串而不是常量进行比较
- 将变量初始化为某个随机值,只需将它们保留为空值
- 将你的 gameStart 逻辑存储为一个字符串,当它是一个布尔值更有意义时
- 当您可以使用 .ToLower() 或大小写激励 Equals() 时,您有两个相等检查
还有很多要批评的东西,但我想你才刚刚开始:)