我对编程还很陌生,并决定接受一个项目,在其中我在控制台中创建一个游戏。用户可以选择从 3x3 网格区域的中心向上、向下、向左或向右移动。x,y 位置之一被标记为“坏”方块,当用户的 x 和 y 等于坏方块的 x 和 y 时,游戏结束。坏方块的位置是x = 1和y = 3。
我遇到的问题是,当用户输入 Up 或 Left(因此用户 y 变为 3 或用户 x 变为 1)并且游戏结束时,即使其他轴值之一与坏方块不匹配。
这是我的代码:
public static void main (String[]args){
//scanner
Scanner userIn = new Scanner(System.in);
//string that will get users value
String movement;
//strings that are compared to users to determine direction
String up = "Up";
String down = "Down";
String left = "Left";
String right = "Right";
//starting coordinates of user
int x = 2;
int y = 2;
//coordinates of bad square
int badx = 1;
int bady = 3;
//message telling user options to move (not very specific yet)
System.out.println("Up, Down, Left, Right");
//do while loop that continues until
do {
movement = userIn.nextLine();
//checking user input and moving them accordingly
if (movement.equals(up)) {
y++;
} else if (movement.equals(down)) {
y--;
} else if (movement.equals(left)) {
x--;
} else if (movement.equals(right)) {
x++;
} else {
System.out.println("Unacceptable value");
}
//checking if user is out of bounds, if user tries to leave area, x or y is increased or decreased accordingly
if (x < 0 || y < 0 || x > 3 || y > 3) {
System.out.println("Out of bounds");
if (x < 0) {
x++;
} else if (y < 0) {
y++;
} else if (x > 3) {
x--;
} else if (y > 3) {
y--;
}
}
//message showing user x and y coordinates
System.out.println("x =" + x + " y =" + y);
} while (y != bady && x != badx); //what checks to see if user has come across the bad square
//ending message (game ends)
System.out.println("Bad Square. Game over.");
}
弑天下
摇曳的蔷薇
Helenr
相关分类