我正在编写一个迷宫程序。用户用字符'P'表示,我需要能够找到该字符以便为我的移动命令分配值。我很困惑如何在迷宫中找到'P'。
public static void main(String[] args) throws Exception{
//Display the maze
char treasureMaze[][] = {{'P','.','X','X','.'},{'.','X','.','.','.'},{'.','.','.','X','.'},{'X','X','T','.','.'},{'.','.','X','.','.'}};
display(treasureMaze);
//Give Move Options
options();
//Get Users Decision
Scanner moveChoice = new Scanner(System.in);
int choice = moveChoice.nextInt();
if(choice == 1){
System.out.println("You chose to Move up");
}
else if(choice == 2){
System.out.println("You chose to Move down");
}
else if(choice == 3){
System.out.println("You chose to Move left");
}
else if(choice == 4){
System.out.println("you chose to Move right");
}
else{
return;
}
//Move the Player
//Move Up
if(choice == 1){
if(treasureMaze[0-1][0] == '.'){
treasureMaze[0-1][0] = 'P';
treasureMaze[0-1][0] = '.';
}
else if(treasureMaze[0-1][0] == 'T'){
System.out.println("Congratulations you won!");
}
else{
System.out.println("Cannot move there! Try something else");
}
}
//Move Down
else if(choice == 2){
if(treasureMaze[0+1][0] == '.'){
treasureMaze[0+1][0] = 'P';
treasureMaze[0][0] = '.';
}
else if(treasureMaze[0+1][0] == 'T'){
System.out.println("Congratulations you won!");
}
else{
System.out.println("Cannot move there! Try something else");
}
}
//Move Left
else if(choice == 3){
if(treasureMaze[0][0-1] == '.'){
treasureMaze[0][0-1] = 'P';
treasureMaze[0][0] = '.';
}
else if(treasureMaze[0][0-1] == 'T'){
System.out.println("Congratulations you won!");
}
else{
System.out.println("Cannot move there! Try something else");
}
}
//Move Right
else if(choice == 4){
if(treasureMaze[0][0+1] == '.'){
treasureMaze[0][0+1] = 'P';
treasureMaze[0][0] = '.';
}
else if(treasureMaze[0][0+1] == 'T'){
System.out.println("Congratulations you won!");
}
else{
System.out.println("Cannot move there! Try something else");
}
}
else{
return;
}
display(treasureMaze);
options();
}
//Display Object: prints out the maze for the user
public static void display(char x[][]){
for(int row = 0; row < x.length; row++){
for(int column = 0; column < x[row].length; column++){
System.out.print(x[row][column] + "\t");
}
System.out.println();
}
}
//Options Object: gives the options menu to the user
static void options(){
System.out.println("You may:");
System.out.println("\t1) Move up");
System.out.println("\t2) Move down");
System.out.println("\t3) Move left");
System.out.println("\t4) Move right");
System.out.println("\t0) Quit");
}
我已将其设置为从其起始位置移动“P”,但不知道如何在下次运行时找到它。有什么想法吗?
答案 0 :(得分:3)
我建议跟踪当前位置,这样您就不必找到它。为玩家的水平和垂直位置声明两个变量。设置电路板时初始化它们(看起来应该是(0,0))并在播放器移动时更新它们。
答案 1 :(得分:1)
Ted的回答可能最适合您当前设置的程序。
作为替代方案,您可以用树替换2D数组。这种方法的另一个好处是你不必担心数组索引越界。每个房间都会引用其连接的其他房间,无效的指示可能只是null
,您可以在玩家的当前房间周围留下参考。