Question

Build a random maze in color and the maze constructed using Java's Stack() class and the...

Build a random maze in color and the maze constructed using Java's Stack() class and the technique of backtracking. Make the maze 21 rows x 70 columns.

Language is Java.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

MainMenu.java


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;


public class MainMenu {

JFrame Menu = new JFrame("Maze");
JButton Start = new JButton("Play");
JButton Exit = new JButton("Exit");
JButton MapMaker = new JButton("Map Maker");
ImageIcon picture = new ImageIcon("res/Images/MazePicture.png");
JLabel imageLabel = new JLabel(picture);
ArrayList<String> mapList = new ArrayList<String>();
JComboBox<String> lvlList;
int menuWidth = 100; //Width of each button/item on display
int menuHeight = 30;//Height of each button/item on display
int menuY = 460; //Button/item location on display
int WIDTH = 490;
int HEIGHT = 530;
  
  
   public MainMenu() {
   //Load map list
   getMapList();
   lvlList = new JComboBox<String>(mapList.toArray(new String[mapList.size()]));
  
//Menu Variables
Menu.setResizable(false);
Menu.setSize(WIDTH, HEIGHT);
Menu.setLayout(null);
Menu.setLocationRelativeTo(null);
Menu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  
//Start Button Variables
Start.setSize(menuWidth,menuHeight);
Start.setLocation(10, menuY);
Menu.add(Start);
Start.addActionListener(new ActionListener(){

           @Override
           public void actionPerformed(ActionEvent arg0) {
               new Maze(lvlList.getSelectedItem().toString());
               Menu.setVisible(false);
           }
  
});  
  
//Map Maker Button Variables
MapMaker.setSize(menuWidth,menuHeight);
MapMaker.setLocation(120, menuY);
Menu.add(MapMaker);
MapMaker.addActionListener(new ActionListener(){

           @Override
           public void actionPerformed(ActionEvent e) {
               new MazeMapMaker();
               Menu.setVisible(false);
           }
  
});
  
//Level Selector
lvlList.setSize(menuWidth+35, menuHeight);
lvlList.setLocation(230, menuY);
Menu.add(lvlList);
  
//Exit Button Variables
Exit.setSize(menuWidth,menuHeight);
Exit.setLocation(375,menuY);
Menu.add(Exit);
Exit.addActionListener(new ActionListener(){

           @Override
           public void actionPerformed(ActionEvent e) {
   System.exit(0);
           }
});
  
//Display Picture
imageLabel.setBounds((WIDTH-412)/2, 25, 412, 412);
imageLabel.setVisible(true);
Menu.add(imageLabel);
Menu.setVisible(true);
}

static boolean levelsExistAlready = false;

public void getMapList(){
   for(int i = 0; i < 99; i++){
       File map = new File("./Level "+i+".map");
       if(map.exists()){
           System.out.println("Level "+i+" exists");
           mapList.add("Level "+i+".map");
           levelsExistAlready = true;
       }
   }
}
}

MapMakerTile.java


import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JPanel;

public class MapMakerTile extends JPanel{
int x, y;
  
public MapMakerTile(int x, int y){
this.x = x;
this.y = y;
  
addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e) {
   if(e.getButton() == MouseEvent.BUTTON1){
   setBackground(Color.WHITE);
   MazeMapMaker.map[x][y] = 1;
   }
   if(e.getButton() == MouseEvent.BUTTON3){
   setBackground(Color.GRAY);
   MazeMapMaker.map[x][y] = 0;
   }
}
});
}
}

Maze.java


import java.awt.Color;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.FileReader;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class Maze extends JFrame{
public static int rows = 20;
public static int columns = 20;
public static int panelSize = 25;
public static int map[][] = new int[columns][rows];
public static int endLevelLoc;
Player p;
  
public Maze(String str){
loadMap(str);
this.setResizable(false);
this.setSize((columns*panelSize)+50, (rows*panelSize)+70);
this.setTitle("Maze");
this.setLayout(null);
  
this.addKeyListener(new KeyListener(){

           @Override
           public void keyPressed(KeyEvent e) {
               int key = e.getKeyCode();
              
               revalidate();
               repaint();
              
               //Player movement
               if(key == KeyEvent.VK_W){
                   p.moveUp();
               }
               if(key == KeyEvent.VK_A){
                   p.moveLeft();
               }
               if(key == KeyEvent.VK_S){
                   p.moveDown();
               }
               if(key == KeyEvent.VK_D){
                   p.moveRight();
               }
              
               if(p.x == columns-1 && p.y == endLevelLoc){
                   JOptionPane.showMessageDialog(null, "Congratulations, you've beaten the level!", "End Game", JOptionPane.INFORMATION_MESSAGE);
                   dispose();
                   new MainMenu();
               }
           }

           @Override
           public void keyReleased(KeyEvent arg0) {
               // TODO Auto-generated method stub
              
           }

           @Override
           public void keyTyped(KeyEvent arg0) {
               // TODO Auto-generated method stub
              
           }
  
});
  
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
//System.out.println((columns*panelSize)+50+"-"+((rows*panelSize)+70));
System.exit(0);
}
});
  
this.setLocationRelativeTo(null);
  
//Create player
   p = new Player();
   p.setVisible(true);
   this.add(p);
  
//Color map
for(int y = 0; y < columns; y++){
for(int x = 0; x < rows; x++){
Tile tile = new Tile(x, y);
tile.setSize(panelSize, panelSize);
tile.setLocation((x*panelSize)+23, (y*panelSize)+25);
if(map[x][y] == 0){
tile.setBackground(Color.GRAY);
}else{
tile.setBackground(Color.WHITE);
tile.setWall(false);
if(x == 0){
   p.setLocation((x*panelSize)+23, (y*panelSize)+25);
   p.y = y;
}
if(x == columns-1){
   endLevelLoc = y;
}
}
  
tile.setVisible(true);
this.add(tile);
}
}
this.setVisible(true);
}
  
public static void main(String args[]){
   new MainMenu();
}
  
public void loadMap(String str){
try{
BufferedReader br = new BufferedReader(new FileReader(str));
StringBuilder sb = new StringBuilder();
String line = br.readLine();

while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String mapStr = sb.toString();
  
int counter = 0;
for(int y = 0; y < columns; y++){
for(int x = 0; x < rows; x++){
String mapChar = mapStr.substring(counter, counter+1);
if(!mapChar.equals("\r\n") && !mapChar.equals("\n")&& !mapChar.equals("\r")){//If it's a number
//System.out.print(mapChar);
map[x][y] = Integer.parseInt(mapChar);
}else{//If it is a line break
x--;
System.out.print(mapChar);
}
counter++;
}
}
}catch(Exception e){
System.out.println("Unable to load existing map(if exists), creating new map.");
}
}
}

MazeMapMaker.java


import java.awt.Color;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class MazeMapMaker extends JFrame{
   static int rows = 20;
static int columns = 20;
int panelSize = 25;
static int map[][] = new int[columns][rows];
ArrayList<String> mapList = new ArrayList<String>();
int level = 0;
boolean levelsExistAlready = false;
  
public MazeMapMaker(){
   getMapList();
   getLevelChoice();
   if(level != -1){
   loadMap();
   this.setResizable(false);
   this.setSize((columns*panelSize)+50, (rows*panelSize)+70);
   this.setTitle("Maze Map Maker");
   this.setLayout(null);
  
   this.addWindowListener(new WindowAdapter(){
   public void windowClosing(WindowEvent e) {
   saveMap();
   new MainMenu();
   }
   });
  
   this.setLocationRelativeTo(null);
  
   for(int y = 0; y < columns; y++){
   for(int x = 0; x < rows; x++){
       MapMakerTile tile = new MapMakerTile(x, y);
   tile.setSize(panelSize-1, panelSize-1);
   tile.setLocation((x*panelSize)+23, (y*panelSize)+25);
   if(map[x][y] == 0){
   tile.setBackground(Color.GRAY);
   }else{
   tile.setBackground(Color.WHITE);
   }
  
   tile.setVisible(true);
  
   this.add(tile);
   }
   }
   this.setVisible(true);
   }else{
       new MainMenu();
   }
}
  
public void getMapList(){
   for(int i = 0; i < 99; i++){
       File map = new File("./Level "+i+".map");
       if(map.exists()){
           System.out.println("Level "+i+" exists");
           mapList.add("Level "+i+".map");
           levelsExistAlready = true;
       }
   }
}
  
public void getLevelChoice(){
   if(levelsExistAlready){
       String maps[] = new String[99];
       mapList.toArray(maps);
       maps[mapList.size()] = "New level";
       String choice = (String)JOptionPane.showInputDialog(null, "Which level would you like to play?", "Maze Level Selector", JOptionPane.QUESTION_MESSAGE, null, maps, maps[0]);
       System.out.println(choice);
       if(choice != null && !choice.equals("New level")){
           level = Integer.parseInt((choice.replace("Level ", "").replace(".map", "")));
       }else if(choice == null){
           level = -1;
       }else{
           level = mapList.size();
       }
   }
}
  
public void saveMap(){
try{
PrintWriter writer = new PrintWriter("Level "+level+".map", "UTF-8");
for(int y = 0; y < columns; y++){
for(int x = 0; x < rows; x++){
writer.print(map[x][y]);
}
writer.print("\r\n");
}
writer.close();
}catch(Exception e){
e.printStackTrace();
}
}
  
public void loadMap(){
try{
BufferedReader br = new BufferedReader(new FileReader("Level "+level+".map"));
StringBuilder sb = new StringBuilder();
String line = br.readLine();

while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String mapStr = sb.toString();
  
int counter = 0;
for(int y = 0; y < columns; y++){
for(int x = 0; x < rows; x++){
String mapChar = mapStr.substring(counter, counter+1);
if(!mapChar.equals("\r\n") && !mapChar.equals("\n")&& !mapChar.equals("\r")){//If it's a number
//System.out.print(mapChar);
map[x][y] = Integer.parseInt(mapChar);
}else{//If it is a line break
x--;
//System.out.print(mapChar);
}
counter++;
}
}
}catch(Exception e){
System.out.println("Unable to load existing map(if exists), creating new map.");
for(int y = 0; y < columns; y++){
for(int x = 0; x < rows; x++){
map[x][y] = 0;
}
}
}
}
}

Player.java

import java.awt.Color;

import javax.swing.JPanel;


public class Player extends JPanel{
   int x, y;
  
public Player() {
   this.setBackground(Color.getHSBColor(0.3f, 0.3f, 1));
   this.setSize(Maze.panelSize, Maze.panelSize);
}

public void moveLeft() {
   if(x > 0 && Maze.map[x-1][y] == 1){
       this.setLocation(this.getX()-25, this.getY());
       x--;
   }
}

public void moveRight() {
   if(x < Maze.columns-1 && Maze.map[x+1][y] == 1){
       this.setLocation(this.getX()+25, this.getY());
       x++;
   }
}

public void moveUp() {
   if(y > 0 && Maze.map[x][y-1] == 1){
       this.setLocation(this.getX(), this.getY()-25);
       y--;
   }
}

public void moveDown() {
   if(y < Maze.rows-1 && Maze.map[x][y+1] == 1){
       this.setLocation(this.getX(), this.getY()+25);
       y++;
   }
}
}

Tile.java


import javax.swing.JPanel;

public class Tile extends JPanel{
int x, y;
boolean isWall = true;
  
public Tile(int x, int y){
this.x = x;
this.y = y;
}
  
public void setWall(boolean isWall){
this.isWall = isWall;
}
}

Output:

ப

Add a comment
Know the answer?
Add Answer to:
Build a random maze in color and the maze constructed using Java's Stack() class and the...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Java maze problem: Given a maze represented by a 2-dimensional array with 0’s (wall) and 1’s...

    Java maze problem: Given a maze represented by a 2-dimensional array with 0’s (wall) and 1’s (open path), the goal is to find the path from a given initial location (rowIni, colIni) to a final location (rown, coln) using recursive backtracking. A move can be made to a location only if there is 1 in the neighboring coordinate. A position that is part of path should be marked with the character +. When a path from initial location to final...

  • JAVA - Without using build in functions Implement a program that will use a stack structure...

    JAVA - Without using build in functions Implement a program that will use a stack structure to check for correct placement of parentheses in an algebraic expression. Allow the use of ( ) [ ] { } characters as grouping symbols. Make sure that an error is reported for an expression of a form (...]. In addition report other possible parentheses related errors (too many levels, too many right paren., too many left paren.). Make sure to use 'silent error...

  • In this part, you will complete the code to solve a maze.

    - Complete the code to solve a maze- Discuss related data structures topicsProgramming-----------In this part, you will complete the code to solve a maze.Begin with the "solveMaze.py" starter file.This file contains comment instructions that tell you where to add your code.Each maze resides in a text file (with a .txt extension).The following symbols are used in the mazes:BARRIER = '-' # barrierFINISH = 'F' # finish (goal)OPEN = 'O' # open stepSTART = 'S' # start stepVISITED = '#' #...

  • I NEED HELP IN MAZE PROBLEM. Re-write the following program using classes. The design is up...

    I NEED HELP IN MAZE PROBLEM. Re-write the following program using classes. The design is up to you, but at a minimum, you should have a Maze class with appropriate constructors and methods. You can add additional classes you may deem necessary. // This program fills in a maze with random positions and then runs the solver to solve it. // The moves are saved in two arrays, which store the X/Y coordinates we are moving to. // They are...

  • In this question, you will test, using a backtracking algorithm, if a mouse can escape from...

    In this question, you will test, using a backtracking algorithm, if a mouse can escape from a rectangular maze. To ensure consistency of design, start your solution with maze_start.c. The backtracking algorithm helps the mouse by systematically trying all the routes through the maze until it either finds the escape hatch or exhausts all possible routes (and concludes that the mouse is trapped in the maze). If the backtracking algorithm finds a dead end, it retraces its path until it...

  • Your job is to do the following: build a Monster class as your base class, along...

    Your job is to do the following: build a Monster class as your base class, along with two derived classes, Undead and Animal. All Monsters have names and origins. Undead monsters have the year their heart stopped beating. Animals have a species. Your Undead class should be extended to create a Zombie class and a Vampire class. Your Animal Class will extend to include a Werewolf class. Zombies have a favorite weapon, Vampires have a number of humans they have...

  • The game Battleship is played on a grid board. Each opponent has multiple ships that are placed on the grid where the o...

    The game Battleship is played on a grid board. Each opponent has multiple ships that are placed on the grid where the other opponent cannot see them. In order to attack, each player takes turns calling out coordinates on a grid. If the attacker calls out a coordinate that hits their opponent's ship, they must call out, "Hit." You are going to be developing a computer program to mimic this game. Use the Gridlayout that is six columns by six...

  • The game Battleship is played on a grid board. Each opponent has multiple ships that are...

    The game Battleship is played on a grid board. Each opponent has multiple ships that are placed on the grid where the other opponent cannot see them. In order to attack, each player takes turns calling out coordinates on a grid. If the attacker calls out a coordinate that hits their opponent's ship, they must call out, "Hit." You are going to be developing a computer program to mimic this game. Use the Gridlayout that is six columns by six...

  • Using Html 5: - You are to create a table consisting of 11 rows and 11...

    Using Html 5: - You are to create a table consisting of 11 rows and 11 columns. The table cells are to be 40 pixels wide, each row. The table is to also have a header row that spans across all columns and contains 'Multiplication Math' as the table name. - Alternating rows will have a different background color. - The table is to be centered in the HTML page. The top table row is to have the numbers 1-10...

  • *Using C++* You will create a program that uses a Critter class to move around a...

    *Using C++* You will create a program that uses a Critter class to move around a Grid, which is also a class. The Critter and the Grid classes will be in separate files. The Critter class will have a data member to count the number of moves made. It will also need data members to hold the current x and y coordinates. It will have a member function that randomly moves it one space in one of 4 directions. You...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT