/* * Maze * Creates a grid of rooms, hallways between the rooms * Then, hallways are picked at random with their adjoining doors * opened up as specified in the lab. *
* Author: Ron Cytron
* Course: CS101
*/
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
public class Maze {
public static boolean debug=false;
private int
rows, // The number of rows and columns in this maze
cols;
private Room[][] rooms;
private RoomViz[][] vrooms;
private JFrame frame;
private ArrayList halls;
public Maze(int rows, int cols) {
this.rows = rows;
this.cols = cols;
halls = new ArrayList();
frame = new JFrame("Maze");
frame.setSize(800,600);
frame.show();
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
frame.dispose();
System.exit(0);
}
});
for (int i=0; i < 50; ++i) {
initMaze(rows, cols);
workMaze();
Lab.sleep(2000);
}
}
private void initMaze(int rows, int cols) {
halls = new ArrayList();
frame.getContentPane().removeAll();
placeRooms(frame.getContentPane(), rows, cols);
}
private void workMaze() {
shuffle(halls);
System.out.println(halls);
new Thread() {
public void run() {
for (Iterator i = halls.iterator(); i.hasNext();) {
Hall h = (Hall) i.next();
h.doit();
}
}
}.run();
for (Iterator i = halls.iterator(); i.hasNext();) {
Hall h = (Hall) i.next();
try { h.getThread().join(); } catch (Throwable t) { }
}
System.out.println("I am done");
}
private void placeRooms(Container p, int rows, int cols) {
rooms = new Room[rows][cols];
vrooms = new RoomViz[rows][cols];
p.setLayout(new GridLayout(rows, cols));
for (int r=0; r < rows; ++r) {
for (int c=0; c < cols; ++c) {
rooms[r][c] = new Room();
vrooms[r][c] = new RoomViz(rooms[r][c]);
p.add(vrooms[r][c]);
if (c > 0) halls.add(horzHall(vrooms[r][c-1], vrooms[r][c]));
if (r > 0) halls.add(vertHall(vrooms[r-1][c], vrooms[r][c]));
}
}
validate();
}
private Hall horzHall(RoomViz r1, RoomViz r2) {
Hall ans = new HorizHall(r1.getRoom(), r2.getRoom());
return ans;
}
private Hall vertHall(RoomViz r1, RoomViz r2) {
Hall ans = new VertHall(r1.getRoom(), r2.getRoom());
return ans;
}
/*
* Generate the rooms and halls of the maze
*/
public void validate() {
frame.validate();
frame.repaint();
}
public static void shuffle(ArrayList s) {
int size = s.size();
for (int i=size; i > 0; --i) {
int at = (int)(size*Math.random());
Object move = s.get(i-1);
Object old = s.get(at);
s.set(at, move);
s.set(i-1, old);
}
}
/**
* Reset the maze to its initial state -- each room in its own set
*/
/** Returns the number of rows **/
public int getRows() { return rows; }
/** Returns the number of columns **/
public int getCols() { return cols; }
public static void sleep(int ms) {
try {
Thread.sleep(ms);
} catch(Throwable t) { }
}
}