1

我正在用java编写一个简单的迷宫游戏。该程序从输入文件中读取文本“地图”以用于迷宫布局。规则很简单:通过用户输入导航迷宫(由 2D 数组表示)并避免塌陷(由 Xs 表示),然后到达标记为“T”的位置的“P”(玩家)。现在,我已经编写了大部分代码,只是让它正常工作的问题。我已经将大部分游戏设置为使用 while 循环运行,布尔值“得到宝藏”设置为 false。一旦这成为现实,它应该结束游戏。

但是,我没有编写玩家实际获得宝藏的情况,所以我想知道为什么我的代码只是吐出“恭喜!你找到了宝藏!” 没有别的了。如果有人能对此有所了解,我将不胜感激。我的代码有点混乱,因为我们的老师刚刚开始学习方法、构造函数和创建我们自己的类。这是我到目前为止的代码:

import java.util.*;
import java.io.File;
public class MazeGame {

public static void main(String[] args) throws Exception {
    Scanner scan = new Scanner(new File("maze.txt"));
    Scanner user = new Scanner(System.in);
    int rows = scan.nextInt();
    int columns = scan.nextInt();
    int px = 0;
    int py = 0;
    String [][] maze = new String[rows][columns];
    String junk = scan.nextLine();

    for (int i = 0; i < rows; i++){
        String temp = scan.nextLine();
        String[] arrayPasser = temp.split("");
        for (int j = 0; j < columns; j++){
            maze[i][j] = arrayPasser[i];
        }
    }

    boolean gotTreasure = false;

    while (gotTreasure = false){
        for (int i = 0; i < rows; i++){
            for (int j = 0; j < columns; j++){
                System.out.print(maze[i][j]);
                System.out.print(" ");
        }
            System.out.print("\n");
      }


        System.out.printf("\n");
        System.out.println("You may:");
        System.out.println("1) Move up");
        System.out.println("2) Move down");
        System.out.println("3) Move left");
        System.out.println("4) Move right");
        System.out.println("0) Quit");
        int choice = user.nextInt();
        int i = 0;

        if (choice == 1 && i >= 0 && i < columns){
            for (int k = 0; k < rows; k++){
                for (int l = 0; l < columns; l++){
                    if (maze[k][l].equals(maze[px][py]) && maze[px][py-1].equals("X") == false){
                        maze[px][py] = ".";
                        maze[k][l-1] = "P";
                        maze[px][py] = maze[k][l-1];
                    }else if (maze[px][py-1] == "X"){
                        System.out.println("Cannot move into a cave-in! Try something else.");
                    }else {
                    continue;}


                    }
                }
            }
        else if (choice == 2 && i >= 0 && i < columns){
            for (int k = 0; k < rows; k++){
                for (int l = 0; l < columns; l++){
                    if (maze[k][l].equals(maze[px][py]) && maze[px][py+1].equals("X") == false){
                        maze[px][py] = ".";
                        maze[k][l+1] = "P";
                        maze[px][py] = maze[k][l+1];
                    }else if (maze[px][py+1] == "X"){
                        System.out.println("Cannot move into a cave-in! Try something else.");
                    }else {
                    continue;}

               }
             }
            }
        else if (choice == 3 && i >= 0 && i < columns){
            for (int k = 0; k < rows; k++){
                for (int l = 0; l < columns; l++){
                    if (maze[k][l].equals(maze[px][py]) && maze[px-1][py].equals("X") == false){
                        maze[px][py] = ".";
                        maze[k-1][l] = "P";
                        maze[px][py] = maze[k-1][l];
                    }else if (maze[px-1][py] == "X"){
                        System.out.println("Cannot move into a cave-in! Try something else.");
                    }else {
                    continue;}
                }
            }
        }
        else if (choice == 4 && i >= 0 && i < columns){
            for (int k = 0; k < rows; k++){
                for (int l = 0; l < columns; l++){
                    if (maze[k][l].equals(maze[px][py]) && maze[px+1][py].equals("X") == false){
                        maze[px][py] = ".";
                        maze[k+1][l] = "P";
                        maze[px][py] = maze[k+1][l];
                    }else if (maze[px+1][py] == "X"){
                        System.out.println("Cannot move into a cave-in! Try something else.");
                    }else {
                    continue;}
                }
            }
        }
        else if (choice == 0){
            System.exit(0);
        }
    }

    System.out.println("Congratulations, you found the treasure!");

    scan.close();
    user.close();
        }

    }

这是示例输入文件:

  • 5 5
  • P.XX.
  • 。X...
  • ...X。
  • XXX..
  • ..X..
4

4 回答 4

5

(叹气)一等号而不是二。您有“while (gotTreasure = false)”,它将值 false 分配给 gotTreasure 并且不进入循环。将其更改为“while (gotTreasure == false) 并进入循环。

对于未来的问题:请尝试自己弄清楚发生了什么,并让其他人知道您尝试了什么以及您对此有什么具体问题。有争议的是,我应该放弃它,因为它本质上是一个为您调试代码的请求。学会调试自己。如果跟踪语句没有被执行,那么很可能此时的代码没有被执行。如果没有进入循环,几乎可以肯定是因为进入循环的条件不存在。

学习使用调试器——eclipse(我敢肯定,还有很多其他的开发工具)有一个很好的调试器。找出断点是什么,如何设置它并在命中时检查变量,并从那里找出问题所在。

于 2012-09-29T00:46:19.773 回答
2

如果这是一个错字忽略这个,如果它不是

        while (gotTreasure = false) is wrong.

您没有检查 gotTreasure 是否为假,而是将其分配为假。

检查 gotTreasure 是否为假,使用 == 运算符

       while(gotTreasure==false)

让我知道这是否是一种类型,我将删除答案。:)

于 2012-09-29T00:47:01.927 回答
2

您的 while 循环条件有一个简单的错误,

代替,

while (gotTreasure = false)

你应该使用,

while (gotTreasure == false)

在第一种情况下,您将 false 分配给 gotTreasure,而在第二种情况下,您正在评估 gotTreasure 是否为 false。

于 2012-09-29T00:48:36.360 回答
0

我重构了你的代码,因为有很多糟糕的编程风格。现在游戏应该按预期运行。

  1. 我使用了一个构造器和很多方法,将你的大方法分成小部分。-> 更容易理解。
  2. 我声明了属性(在整个类中都知道),以便不同的方法可以使用这个变量。
  3. 您经常检查 if(variable == false) 之类的条件。尝试使用 if(!variable),感叹号否定变量的值。
  4. 您的 update-Methode 有很多冗余。通过添加以下 switch-case-Part,我可以区分不同的方向:

通过用户输入设置方向的通用代码:

switch (choice){
    case 0: System.exit(0);
    case 1: xdir = 0; ydir = -1; break;
    case 2: xdir = 0; ydir =1; break;
    case 3: xdir = -1; ydir = 0; break;
    case 4: xdir = 1; ydir = 0; break;
}

之后我可以通过将 xdir 添加到 x 并将 ydir 添加到 y 来计算新位置。如果您尝试检查新位置是否在数组的范围内,这很方便。

//1. Check if the new position is in the array.
if (x+xdir >= 0 && x+xdir <columns && y+ydir >=0 && y+ydir < rows){

下面是整个班级:

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

public class MazeGame2 {
    Scanner scan;
    Scanner user;
    int rows;
    int columns;
    String [][] maze;

    int x; //Player x-Position 
    int y; //Player y-Position
    boolean gotTreasure;

    /**
     * Konstruktor for the class.
     */
    public MazeGame2(){
        init(); 
        game();
        scan.close();
        user.close();  
    }

    /**
     * Initialisation of the maze and all attributes.
     */
    public void init(){
        user = new Scanner(System.in); //Scanner for Userinput

        /********************************
         * Scanning the maze from a file. 
         */
        //1. Open the file. Has to be in a try-catch-Bracket, because the file might not be there.
        try{
            scan = new Scanner(new File("maze.txt"));
        }catch(FileNotFoundException e){
            e.printStackTrace();
        }

        //2. Scan the dimensions of the maze.
        rows = scan.nextInt();
        columns = scan.nextInt();
        scan.nextLine(); // So that the next Line can be scanned.

        maze = new String[rows][columns];//Create the maze-Array with the right dimensions.

        for (int i = 0; i < rows; i++){
            String temp = scan.nextLine(); //Scan one line.
            for (int j = 0; j < columns; j++){
                maze[i][j] = temp.substring(j, j+1);//Put every character in the maze
                if (maze[i][j].equals("P")){ //Look out for the Player-Position
                    x = j; 
                    y = i;
                }
            }
        }  
        gotTreasure = false;
    }

    /**
     * Prints the Input of the maze-Array. But only if the spots are visible by the player.
     */
    public void printMaze(){
        for (int i = 0; i < rows; i++){
            for (int j = 0; j < columns; j++){
                System.out.print(maze[i][j]);
                System.out.print(" ");
        }
        System.out.println();
      }  
    }

    /**
     * Prints the possebilities to move by the player.
     */
    public void printUserPossebilities(){
        System.out.println();
        System.out.println("You may:");
        System.out.println("1) Move up");
        System.out.println("2) Move down");
        System.out.println("3) Move left");
        System.out.println("4) Move right");
        System.out.println("0) Quit");      
    }

    /**
     * 
     */
    public void update(int choice){
        int xdir=0; 
        int ydir=0;
        // Update the direction based on the userChoice
        switch (choice){
            case 0: System.exit(0);
            case 1: xdir = 0; ydir = -1; break;
            case 2: xdir = 0; ydir =1; break;
            case 3: xdir = -1; ydir = 0; break;
            case 4: xdir = 1; ydir = 0; break;
        }

        /**
         * Update the situation based on the current direction and step.
         */
        //1. Check if the new position is in the array.
        if (x+xdir >= 0 && x+xdir <columns && y+ydir >=0 && y+ydir < rows){
            //2. Check if a step is possible
            if (maze[y+ydir][x+xdir].equals("X")){
                System.out.println("Cannot move into a cave-in! Try something else.");
            }else{
                //3. clear the P from the old Position
                maze[y][x] =".";
                //4. Check if the Player is over the treasure
                if (maze[y+ydir][x+xdir].equals("T")){
                    gotTreasure = true;
                }
                x = x+xdir; 
                y = y + ydir; 
                maze[y][x] = "P"; //Show the new position of the player.
            }
        }else{
            System.out.println("That's not a possible Move.");
        }   
    }

    /**
     * The game-Methode that includes the game-loop and 
     */
    public void game(){
        while (!gotTreasure){
            //System.out.print('\u000C');
            printMaze(); 
            printUserPossebilities();
            int userInput = user.nextInt(); //Wait for userinput
            update(userInput);
        }
        //System.out.print('\u000C');
        printMaze();            
        System.out.println("Congratulations, you found the treasure!");  
    }

    public static void main(String[] args){
        MazeGame2 m = new MazeGame2();

    }

}
于 2018-08-16T12:00:10.347 回答