Batteries
Batteries

Reputation: 151

Java: Programming a simple maze game

I'm coding a simple maze game in java. The program reads in a text "map" from an input file for the layout of the maze. The rules are simple: navigate the maze (represented by a 2D array) through user input and avoid the cave-ins (represented by Xs), and get to the 'P' (player) the the spot marked 'T'. Right now, I've got most of the code written, it's just a matter of getting it to work properly. I've set up most of the game to run with a while loop, with the boolean "got treasure" set to false. Once this rings true, it should end the game.

However, I haven't coded the circumstance in which the player actually gets the treasure though, so I'm wondering why my code simply spits out "Congratulations! You've found the treasure!" and nothing else. If anyone could shed some light on this, I'd be very grateful. My code is somewhat of a mess of loops, as our teacher has just gotten to methods, constructors, and creating our own classes. Here is the code I have so far:

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();
        }

    }

And here is the sample input file:

Upvotes: 1

Views: 28546

Answers (4)

Andreas Thiessen
Andreas Thiessen

Reputation: 1

I refeactored your code, because there are a lot of bad programming-styles. Now the game should run as intended.

  1. I used a Construktor and a lot of methods, to divide your big method in small parts. -> easier to understand.
  2. I declared attributes (known in the whole class), so that the different methods can use this variables.
  3. You often checked for a condition like if(variable == false). Try to use if(!variable), the exclamation mark negates the value of the variable.
  4. Your update-Methode had a lot of redundandancies. By adding the following switch-case-Part, I could seperate the different directions:

General code for setting directions by a userinput:

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;
}

Afterwards I could calculate the new position by adding xdir to x and ydir to y. This comes handy, if you try to check if the new position is in the bounds of the array.

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

Here follows the whole class:

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();

    }

}

Upvotes: 0

BillToWin
BillToWin

Reputation: 126

You have a simple mistake in your while loop condition,

Instead of,

while (gotTreasure = false)

You should use,

while (gotTreasure == false)

In the first case, you are assigning false to gotTreasure and in the second you are evaluating if gotTreasure is false.

Upvotes: 2

PermGenError
PermGenError

Reputation: 46408

If this is a typo ignore this, if it isnt

        while (gotTreasure = false) is wrong.

you are not checking if gotTreasure is false, you are assigning it false.

to check if gotTreasure is false use == operator

       while(gotTreasure==false)

lemme know if this is a type, i ll delete the answer. :)

Upvotes: 2

arcy
arcy

Reputation: 13123

(sigh) one equals sign instead of two. You have "while (gotTreasure = false)", which assigns the value false to gotTreasure and does not enter the loop. Change it to "while (gotTreasure == false) and it enters the loop.

For future questions: please attempt to figure out on your own what is happening, and let others know what you have tried and what specific questions you have about it. It is arguable I should just have let this go, since it is essentially a request to debug your code for you. Learn to debug yourself. If trace statements aren't getting executed, it's most likely the code at that point isn't getting executed. If a loop isn't getting entered, it is almost certainly because the conditions for entering the loop don't exist.

Learn to use a debugger - eclipse (and, I am sure, lots of other development tools) has an excellent one. Find out what a breakpoint is, how to set it and examine variables when it is hit, and figure out from there what has gone wrong.

Upvotes: 5

Related Questions