Java:编写一个简单的迷宫游戏

时间:2012-09-29 00:29:57

标签: java arrays string loops

我在java编写一个简单的迷宫游戏。该程序从输入文件中读取文本“地图”以用于迷宫的布局。规则很简单:通过用户输入导航迷宫(由2D数组表示)并避开塌陷(由X表示),并将标记为“T”的点移至'P'(玩家)。现在,我已经编写了大部分代码,这只是让它正常工作的问题。我已经将大部分游戏设置为使用while循环运行,并将布尔“got treasure”设置为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。
  • XXT ..
  • .. X ..

4 个答案:

答案 0 :(得分:5)

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

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

学习使用调试器 - eclipse(而且,我确信,许多其他开发工具)都非常出色。找出断点是什么,如何设置它并在命中时检查变量,并从那里找出出错的地方。

答案 1 :(得分:2)

如果这是一个拼写错误,请忽略它,如果它不是

        while (gotTreasure = false) is wrong.

你没有检查gotTreasure是否为假,你指的是假的。

检查gotTreasure是否为false use == operator

       while(gotTreasure==false)

知道这是一个类型,我会删除答案。 :)

答案 2 :(得分:2)

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

而不是,

while (gotTreasure = false)

你应该使用,

while (gotTreasure == false)

在第一种情况下,你要为gotTreasure指定false,而在第二种情况下,你正在评估gotTreasure是否为false。

答案 3 :(得分: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();

    }

}