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.
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:

Build a random maze in color and the maze constructed using Java's Stack() class and the...
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: Code a class encapsulating a stack of clothes using an array. A clothing item has the following attributes: names, color, and whether it can be washed at high temperature. Limit your stack to 20 clothing items. In addition to creating your push, pop, and peek methods; create two additional methods: a method that return all of the clothing items of a given color; a method that returns how many clothing items in the stack can be washed at high...
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...
- 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 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 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...
Having a rough time getting started with the constructors and the display function of this class, any advice/assitance is appreciated! Task You will write a class called Grid, and test it with a couple of programs. A Grid object will be made up of a grid of positions, numbered with rows and columns. Row and column numbering start at 0, at the top left corner of the grid. A grid object also has a "mover", which can move around to...
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 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 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...