MazeGen.java

From Yggenyk
Jump to navigation Jump to search

<source lang="java"> /******************************************************************************************

  MazeGen.java - Random Maze generator
  Version 1.0
  www.mazeworks.com
  
  Copyright (c) 2002 Robert Kirkland
  All Rights Reserved.
  Permission is hereby granted, free of charge, to any person obtaining a copy 
  of this software and associated documentation files (the "Software"), to
  deal in the Software without restriction, including without limitation the
  rights to use, copy, modify, merge, publish, distribute, and/or sell copies
  of the Software, and to permit persons to whom the Software is furnished to
  do so, provided that the above copyright notice and this permission notice
  appear in all copies of the Software and that both the above copyright
  notice and this permission notice appear in supporting documentation.
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS.
  IN NO EVENT SHALL THE COPYRIGHT HOLDER INCLUDED IN THIS NOTICE BE LIABLE FOR
  ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES
  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
  OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  Except as contained in this notice, the name of the copyright holder shall
  not be used in advertising or otherwise to promote the sale, use or other
  dealings in this Software without prior written authorization of the
  copyright holder.
                                                                                                                                                                                    • /

import java.applet.* ; import java.awt.* ; import java.util.* ;

/******** MAZEGEN ********

  main class; initializes applet panel, controls 
  execution thread, handles UI events 
  • /

public class MazeGen extends Applet implements Runnable {

  public String getAppletInfo() { 
     return "MazeGen 1.0 - Copyright (c) 2002 Robert Kirkland"; }
  static final Color wallColor=Color.white, 
                     pathColor=Color.yellow,
                     backColor=Color.lightGray, 
                     startColor=Color.green,
                     endColor=Color.red,
                     frameColor=Color.gray,
                     bkgrndColor=Color.darkGray,
                     panelColor=Color.lightGray,
                     appletColor=Color.white ;
  static final int mcWidth=410, mcHeight=310 ;
  private boolean isCycle, isGen, isSolve ;
  private Maze mz ;
  private MazeCanvas mc ;
  private ControlPanel cp ;
  private Thread mazeThread ;
  
  // initialize applet layout
  public void init() {
     Panel p = new Panel() ;
     p.setBackground(panelColor) ;
     setBackground(appletColor) ;
     mc = new MazeCanvas(mcWidth,mcHeight) ;
     mc.resize(mcWidth,mcHeight) ;
     cp = new ControlPanel(this,mc) ;
     p.add(cp) ;
     add(mc) ;
     add(p) ;
     validate() ;
     isCycle = true ;
  }
  // start thread
  public void start() {
     if (mazeThread == null) {
        mazeThread = new Thread(this) ;
        mazeThread.start() ;
     }
  }
  // kill thread
  public void stop() {
     if (mazeThread != null) {
        mazeThread.stop() ;
        mazeThread = null ;
     }
  }
  // run thread
  public void run() { 
     if (isGen) { 
        generate() ;
        cp.setGenEnable(true) ;
        cp.setSolveEnable(true) ;
        isGen = false ;
     } else if (isSolve) { 
        mz.solveMaze() ;
        isSolve = false ;
     } else
        while(isCycle) {
           generate() ;
           sleep(2000) ;
           mz.solveMaze() ;
           sleep(3000) ;
        }
     System.gc() ;
  }
  void generate() {
     switch(cp.getAlgorithm()) {
        case 0: mz = new MazeDFS(cp.getDim(),mc,cp,this) ; break ;
        case 1: mz = new MazePrim(cp.getDim(),mc,cp,this) ; break ;
        case 2: mz = new MazeKruskal(cp.getDim(),mc,cp,this) ; break ;
     } 
  }
  // UI event handlers
  void startGen() {
     stop() ;
     isGen = true ;
     cp.setGenEnable(false) ;
     cp.setSolveEnable(false) ;
     start() ;
  }
  void startSolve() {
     stop() ;
     isSolve = true ;
     cp.setSolveEnable(false) ;
     start() ;
  }
  void startCycle() {
     stop() ;
     isCycle = true ;
     cp.setCycleLabel("STOP CYCLE") ;
     cp.setGenEnable(false) ;
     cp.setSolveEnable(false) ;
     start() ;
  }
  void stopCycle() { 
     isCycle = false ;
     cp.setCycleLabel("CYCLE") ;
     cp.setGenEnable(true) ;
     stop() ;
  }
  void sleep(int ms) {
     try { Thread.currentThread().sleep(ms) ; } 
     catch (InterruptedException e) {}
  }

}

/******** MAZE ********

  base class; initializes maze cells
  • /

abstract class Maze {

  static final int 
     NORTH=0, N_WALL=0x01, N_BORDER=0x10, N_PATH=0x100, CN_PATH=0x1100, 
     EAST =1, E_WALL=0x02, E_BORDER=0x20, E_PATH=0x200, CE_PATH=0x1200, 
     SOUTH=2, S_WALL=0x04, S_BORDER=0x40, S_PATH=0x400, CS_PATH=0x1400, 
     WEST =3, W_WALL=0x08, W_BORDER=0x80, W_PATH=0x800, CW_PATH=0x1800,
              ALL_WALLS=0x0F,             C_PATH=0x1000,
     N_BACK=0x10000, CN_BACK=0x110000,
     E_BACK=0x20000, CE_BACK=0x120000,
     S_BACK=0x40000, CS_BACK=0x140000,
     W_BACK=0x80000, CW_BACK=0x180000,
     C_BACK=0x100000 ;
     
  protected Point startPt, endPt ;
  protected int m[][], stack[], stackPtr, cols, rows, totalCells ;
  MazeCanvas mc ;
  ControlPanel cp ;
  MazeGen mg ;
  // constructor
  Maze(Dimension d,MazeCanvas mc,ControlPanel cp,MazeGen mg) {
     this.mc = mc ; this.cp = cp ; this.mg = mg ;
     cols = d.width ; rows = d.height ;
     totalCells = cols * rows ;
     stack = new int[totalCells] ;
     // initialize maze array - all walls up, set borders
     m = new int[cols][rows] ;
     for (int i=0; i<cols; i++) {
        for (int j=0; j<rows; j++) {
           m[i][j] |= ALL_WALLS ;
           if (j==0) m[i][0] |= N_BORDER ;
           if (i==(cols-1)) m[i][j] |= E_BORDER ;
           if (j==(rows-1)) m[i][j] |= S_BORDER ;
           if (i==0) m[0][j] |= W_BORDER ;
        }
     }
     // draw the grid
     if (cp.isShowGen()) {
        mc.drawGrid(this) ;
        mg.sleep(500) ;
     }
  }
  void setStartEnd() {
     // start and end points in opposite corners
     switch (randomInt(4)) {
        case 0: startPt = new Point(0,0) ; 
                endPt = new Point(cols-1,rows-1) ; 
                break ;
        case 1: startPt = new Point(cols-1,0) ;
                endPt = new Point(0,rows-1) ; 
                break ;
        case 2: startPt = new Point(cols-1,rows-1) ;
                endPt = new Point(0,0) ; 
                break ;
        case 3: startPt = new Point(0,rows-1) ;
                endPt = new Point(cols-1,0) ; 
                break ;
     }
  }
  void solveMaze() {
     int direction[]=new int[4], candidates=0, choice=0 ;
     int x=startPt.x, y=startPt.y ;
     stackPtr = 0 ;
     m[x][y] |= C_PATH ;
     while ((x!=endPt.x)||(y!=endPt.y)) {
        candidates = 0 ;
        // first check for walls, then see if we've been here before
        if ( ((m[x][y]&N_WALL)==0)&&((m[x][y-1]&C_PATH)==0)&&
           ((m[x][y-1]&C_BACK)==0) ) direction[candidates++] = NORTH ;
        if ( ((m[x][y]&E_WALL)==0)&&((m[x+1][y]&C_PATH)==0)&&
           ((m[x+1][y]&C_BACK)==0) ) direction[candidates++] = EAST ;
        if ( ((m[x][y]&S_WALL)==0)&&((m[x][y+1]&C_PATH)==0)&&
           ((m[x][y+1]&C_BACK)==0) ) direction[candidates++] = SOUTH ;
        if ( ((m[x][y]&W_WALL)==0)&&((m[x-1][y]&C_PATH)==0)&&
           ((m[x-1][y]&C_BACK)==0) ) direction[candidates++] = WEST ;
        if (candidates != 0) {
           // choose a direction at random
           choice = direction[randomInt(candidates)] ;
           stack[stackPtr++] = choice ;
           switch (choice) {
              // set path, change current cell
              case NORTH: m[x][y--] |= N_PATH ;
                          m[x][y] |= CS_PATH ;
                          break ;
              case EAST:  m[x++][y] |= E_PATH ;
                          m[x][y] |= CW_PATH ;
                          break ;
              case SOUTH: m[x][y++] |= S_PATH ;
                          m[x][y] |= CN_PATH ;
                          break ;
              case WEST:  m[x--][y] |= W_PATH ;
                          m[x][y] |= CE_PATH ;
                          break ;
           }         
           // draw path into new cell
           if (cp.isShowSolve()) {
              mc.drawSolve(x,y,choice,mg.pathColor,this) ;
              mg.sleep(cp.getSolveDelay()) ;
           }         
        }
        else {
           // nowhere to go, back up and draw backtrack
           choice = stack[--stackPtr] ;
           if (cp.isShowSolve()) {
              mc.drawSolve(x,y,choice,
                 cp.isShowBack()?mg.backColor:mg.bkgrndColor,this) ;
              mg.sleep(cp.getSolveDelay()) ;
           }         
           switch (choice) {
              // switch off path, set backpath, change current cell
              case NORTH: m[x][y] &= ~CS_PATH ;
                          m[x][y] |= CS_BACK ;
                          m[x][++y] &= ~N_PATH ; 
                          m[x][y] |= N_BACK ;
                          break ;
              case EAST:  m[x][y] &= ~CW_PATH ;
                          m[x][y] |= CW_BACK ;
                          m[--x][y] &= ~E_PATH ;
                          m[x][y] |= E_BACK ;
                          break ;
              case SOUTH: m[x][y] &= ~CN_PATH ;
                          m[x][y] |= CN_BACK ;
                          m[x][--y] &= ~S_PATH ;
                          m[x][y] |= S_BACK ;
                          break ;
              case WEST:  m[x][y] &= ~CE_PATH ;
                          m[x][y] |= CE_BACK ;
                          m[++x][y] &= ~W_PATH ;
                          m[x][y] |= W_BACK ;
                          break ;
           }
        }
        // redraw squares if we're near the start
        if ((stackPtr==1)&&cp.isShowSolve()) mc.drawStartEnd(startPt,endPt) ;
     }
     // if we've been updating the screen, just redraw the squares
     // again to make sure they look nice. Otherwise it's time to
     // draw the solution path we just calculated
     if (cp.isShowSolve()) mc.drawStartEnd(startPt,endPt) ;
     else mc.drawPath(cp.isShowBack(),this) ;
     
  }
  int getCols() { return cols ; }
  int getRows() { return rows ; }
  int getCell(int i,int j) { return m[i][j] ; }
  Point getStart() { return startPt ; }
  Point getEnd() { return endPt ; }
  int randomInt(int n) { return (int)(n*Math.random()) ; }
  abstract void setWalls() ;

}

/******** MAZE DFS ********

  creates maze using Depth-First Search algorithm
  • /

final class MazeDFS extends Maze {

  // constructor
  MazeDFS(Dimension d,MazeCanvas mc,ControlPanel cp,MazeGen mg) {
     super(d,mc,cp,mg) ;
     // run the algorithm, set start/end
     setWalls() ;
     setStartEnd() ;
     // draw the new maze if we haven't yet
     if (!cp.isShowGen()) mc.drawMaze(this) ;
     // or just the start/end squares
     else mc.drawStartEnd(startPt,endPt) ;
  }
  void setWalls() {
     int direction[]=new int[4], visited=0, candidates=0, choice=0 ;
     // random starting point
     int x=randomInt(cols), y=randomInt(rows) ;
     stackPtr = 0 ;
     visited = 1 ;
     while(visited < totalCells) {
        candidates = 0;
        // find all possible directions for next cell
        // first look for a border, then see if all walls intact
        if (((m[x][y]&N_BORDER)==0)&&((m[x][y-1]&ALL_WALLS)==ALL_WALLS))
           direction[candidates++] = NORTH ;
        if (((m[x][y]&E_BORDER)==0)&&((m[x+1][y]&ALL_WALLS)==ALL_WALLS))
           direction[candidates++] = EAST ;
        if (((m[x][y]&S_BORDER)==0)&&((m[x][y+1]&ALL_WALLS)==ALL_WALLS))
           direction[candidates++] = SOUTH ;
        if (((m[x][y]&W_BORDER)==0)&&((m[x-1][y]&ALL_WALLS)==ALL_WALLS))
           direction[candidates++] = WEST ;
     
        if (candidates != 0) {
           // save current cell, choose a direction at random
           choice = direction[randomInt(candidates)] ;
           stack[stackPtr++] = choice ;
           // erase wall in selected direction from maze drawing
           if (cp.isShowGen()) {
              mc.drawGen(x,y,choice,this) ;
              mg.sleep(cp.getGenDelay()) ;
           }         
           switch (choice) {
              // knock down walls and make new cell the current cell
              case NORTH: m[x][y] &= ~N_WALL ;
                          m[x][--y] &= ~S_WALL ;
                          break ;
              case EAST:  m[x][y] &= ~E_WALL ;
                          m[++x][y] &= ~W_WALL ;
                          break ;
              case SOUTH: m[x][y] &= ~S_WALL ;
                          m[x][++y] &= ~N_WALL ;
                          break ;
              case WEST:  m[x][y] &= ~W_WALL ;
                          m[--x][y] &= ~E_WALL ;
                          break ;
           }         
           visited++ ;
        }
        else {
           // nowhere to go, back up to previous cell
           switch (stack[--stackPtr]) {
              // change current cell
              case NORTH: y++ ; break ;
              case EAST:  x-- ; break ;
              case SOUTH: y-- ; break ;
              case WEST:  x++ ; break ;
           }         
        }
     }               
  }

} /******** MAZE PRIM ********

  creates maze using Prim's algorithm
  • /

final class MazePrim extends Maze {

  // constructor
  MazePrim(Dimension d,MazeCanvas mc,ControlPanel cp,MazeGen mg) {
     super(d,mc,cp,mg) ;
     // run the algorithm, set start/end
     setWalls() ;
     setStartEnd() ;
     // draw the new maze if we haven't yet
     if (!cp.isShowGen()) mc.drawMaze(this) ;
     // or just the start/end squares
     else mc.drawStartEnd(startPt,endPt) ;
  }
  void setWalls() {
     Vector out=new Vector(totalCells) ;
     Vector frontier=new Vector(totalCells) ;
     Vector in=new Vector(totalCells) ;
     Point cell=null, nCell=new Point(0,0), eCell=new Point(0,0), 
                      sCell=new Point(0,0), wCell=new Point(0,0) ;
     int[] direction=new int[4] ;
     int index=0, candidates=0, choice=0 ;
     // initialize - all cells in Out
     for (int i=0; i<cols; i++)
        for (int j=0; j<rows; j++) out.addElement(new Point(i,j)) ;
     // choose starting cell at random, move to In
     index = randomInt(totalCells) ;
     cell = (Point)out.elementAt(index) ;
     moveCell(out,in,index) ;
     // move starting cell's neighbors to Frontier
     if (cell.x>0) 
        moveCell(out,frontier,out.indexOf(new Point(cell.x-1,cell.y))) ;
     if (cell.y>0) 
        moveCell(out,frontier,out.indexOf(new Point(cell.x,cell.y-1))) ;
     if (cell.x<(cols-1))
        moveCell(out,frontier,out.indexOf(new Point(cell.x+1,cell.y))) ;
     if (cell.y<(rows-1))
        moveCell(out,frontier,out.indexOf(new Point(cell.x,cell.y+1))) ;
        
     // the loop
     while (!frontier.isEmpty()) {
        // move random cell from Frontier to In
        index = randomInt(frontier.size()) ;
        cell = (Point)frontier.elementAt(index) ;
        moveCell(frontier,in,index) ;
        // move cell's neighbors from Out to Frontier                  
        if (cell.x>0) {
           wCell.x = cell.x - 1 ; wCell.y = cell.y ;
           moveCell(out,frontier,out.indexOf(wCell)) ;
        }
        if (cell.y>0) {
           nCell.x = cell.x ; nCell.y = cell.y - 1 ;
           moveCell(out,frontier,out.indexOf(nCell)) ;
        }
        if (cell.x<(cols-1)) {
           eCell.x = cell.x + 1 ; eCell.y = cell.y ;
           moveCell(out,frontier,out.indexOf(eCell)) ;
        }
        if (cell.y<(rows-1)) {
           sCell.x = cell.x ; sCell.y = cell.y + 1 ;
           moveCell(out,frontier,out.indexOf(sCell)) ;
        }
        // find all neighbors of cell in In
        candidates = 0 ;
        if (cell.x>0)
           if (in.indexOf(wCell)>=0) direction[candidates++] = WEST ;
        if (cell.y>0)
           if (in.indexOf(nCell)>=0) direction[candidates++] = NORTH ;
        if (cell.x<(cols-1))
           if (in.indexOf(eCell)>=0) direction[candidates++] = EAST ;
        if (cell.y<(rows-1))
           if (in.indexOf(sCell)>=0) direction[candidates++] = SOUTH ;
        // choose one at random
        choice = direction[randomInt(candidates)] ;
        // erase wall between the cells from maze drawing
        if (cp.isShowGen()) {
           mc.drawGen(cell.x,cell.y,choice,this) ;
           mg.sleep(cp.getGenDelay()) ;
        }         
        switch (choice) {
           // knock down the wall
           case NORTH: m[cell.x][cell.y] &= ~N_WALL ;
                       m[cell.x][cell.y-1] &= ~S_WALL ;
                       break ;
           case EAST:  m[cell.x][cell.y] &= ~E_WALL ;
                       m[cell.x+1][cell.y] &= ~W_WALL ;
                       break ;
           case SOUTH: m[cell.x][cell.y] &= ~S_WALL ;
                       m[cell.x][cell.y+1] &= ~N_WALL ;
                       break ;
           case WEST:  m[cell.x][cell.y] &= ~W_WALL ;
                       m[cell.x-1][cell.y] &= ~E_WALL ;
                       break ;
        }         
     }
  }
  void moveCell(Vector from, Vector to, int index) {
     if (index!=-1) {
        to.addElement((Point)from.elementAt(index)) ;
        from.removeElementAt(index) ;
     }
  }

} /******** MAZE KRUSKAL ********

  creates maze using Kruskal's algorithm
  • /

final class MazeKruskal extends Maze {

  // 1D array of cells' equivalence classes for union-find
  private int uf[]=new int[totalCells] ;   
  // constructor
  MazeKruskal(Dimension d,MazeCanvas mc,ControlPanel cp,MazeGen mg) {
     super(d,mc,cp,mg) ;
     // run the algorithm, set start/end
     setWalls() ;
     setStartEnd() ;
     // draw the new maze if we haven't yet
     if (!cp.isShowGen()) mc.drawMaze(this) ;
     // or just the start/end squares
     else mc.drawStartEnd(startPt,endPt) ;
  }
  void setWalls() {
     // for the walls, first two ints are the cell, third is direction
     int walls[][]=new int[(totalCells*2)-cols-rows][3], wallsPtr=0 ;
     int index=0, visited=1, direction=0, root1=0, root2=0 ;   
     int x1=0, y1=0, x2=0, y2=0 ;
  
     for (int i=0; i<cols; i++) {
        for (int j=0; j<rows; j++) {
           // all cells in their own equivalence class
           uf[(j*cols)+i] = -1 ;
           // add all interior walls (only need N and W for each cell)
           if (i!=0) {
              walls[wallsPtr][0] = i ;
              walls[wallsPtr][1] = j ;
              walls[wallsPtr++][2] = WEST ;
           }
           if (j!=0) {
              walls[wallsPtr][0] = i ;
              walls[wallsPtr][1] = j ;
              walls[wallsPtr++][2] = NORTH ;
           }
        }
     }
     while (visited < totalCells) {
        // choose cell wall at random
        index = randomInt(wallsPtr--) ;
        x1 = walls[index][0] ;
        y1 = walls[index][1] ;
        direction = walls[index][2] ;
        // remove wall from array
        if (index!=wallsPtr)
           for (int i=0; i<3; i++) walls[index][i] = walls[wallsPtr][i] ;
        // find cell on other side of the wall
        if (direction==NORTH) { x2 = x1 ; y2 = y1 - 1 ; }
        else { x2 = x1 - 1 ; y2 = y1 ; }
        // find roots, converting to 1D array
        root1 = find(x1+(y1*cols)) ;
        root2 = find(x2+(y2*cols)) ;
        // are the cells in the same class?
        if (root1 != root2) {
           // no - connect the two trees, bump the counter
           union(root1,root2) ;
           visited++ ;
           // and knock down the wall
           if (direction == NORTH) {
              m[x1][y1] &= ~N_WALL ;
              m[x2][y2] &= ~S_WALL ;
           }
           else {
              m[x1][y1] &= ~W_WALL ;
              m[x2][y2] &= ~E_WALL ;
           }
           // erase wall from maze drawing
           if (cp.isShowGen()) {
              mc.drawGen(x1,y1,direction,this) ;
              mg.sleep(cp.getGenDelay()) ;
           }         
        }
     }
  }
  int find(int n) {
     // recursive find with path compression
     if (uf[n]<0) return n ; // at root
     return uf[n]=find(uf[n]) ;
  }
  void union(int r1,int r2) {
     // union-by-size
     if (uf[r1]<=uf[r2]) {
        uf[r1] += uf[r2] ;   // add size of r2 to r1
        uf[r2] = r1 ;         // r2 points to r1
     }
     else {
        uf[r2] += uf[r1] ;
        uf[r1] = r2 ;
     }
  }

} /******** MAZE CANVAS ********

  draws the maze using double buffer
  • /

final class MazeCanvas extends Canvas {

  static final int BORDER=10, MAX_CELL_SIZE=20 ;
  private int width, height, mzWidth, mzHeight, cellSize,
              wOffset, hOffset, rows, cols, pathSize,
              nwPathOffset, sePathOffset ;
  Image bufferImage ;
  Graphics buffer ;
  MazeGen mg ;
  
  MazeCanvas(int mcw,int mch) { 
     width = mcw ; height = mch ;
  }
  private void drawInit(Maze mz) {
     cols = mz.getCols() ; rows = mz.getRows() ;
     cellSize = (int)Math.min(MAX_CELL_SIZE,
                 Math.min((width-BORDER)/cols,(height-BORDER)/rows)) ;
     mzWidth = cellSize * cols ;
     mzHeight = cellSize * rows ;
     wOffset = (int)((width-mzWidth)/2) ;
     hOffset = (int)((height-mzHeight)/2) ;
     pathSize = (int)(cellSize/2)-1 ;
     nwPathOffset = (int)((cellSize-pathSize)/2) ;
     sePathOffset = cellSize - pathSize - nwPathOffset ;
     if (buffer==null) {
        bufferImage = createImage(width,height) ;
        buffer = bufferImage.getGraphics() ;
     }
     // draw background
     buffer.setColor(mg.appletColor);
     buffer.fillRect(0,0,width,height) ;
     buffer.setColor(mg.bkgrndColor);
     buffer.fillRect(wOffset,hOffset,mzWidth,mzHeight) ;
     // draw outer maze frame
     buffer.setColor(mg.frameColor);
     buffer.draw3DRect(wOffset-2, hOffset-2, mzWidth+4, mzHeight+4, true) ;
     buffer.drawRect(wOffset-1, hOffset-1, mzWidth+2, mzHeight+2) ;
  }
  // draw full generated maze with start and end points
  // called if Show Gen off
  void drawMaze(Maze mz) {
     drawInit(mz) ;
     buffer.setColor(mg.wallColor);
     for (int i=0; i<cols; i++) {
        for (int j=0; j<rows; j++) {
           // only drawing North and West walls
           if ( (j!=0)&&((mz.getCell(i,j)&0x01)!=0) ) {
              buffer.drawLine((wOffset+(i*cellSize)), 
                              (hOffset+(j*cellSize)),
                              (wOffset+((i+1)*cellSize)),
                              (hOffset+(j*cellSize))) ;
           }
           if ( (i!=0)&&((mz.getCell(i,j)&0x08)!=0) ) {
              buffer.drawLine((wOffset+(i*cellSize)), 
                              (hOffset+(j*cellSize)),
                              (wOffset+(i*cellSize)),
                              (hOffset+((j+1)*cellSize))) ;
           }
        }
     }
     // draw inner frame
     buffer.setColor(mg.frameColor);
     buffer.draw3DRect(wOffset, hOffset, mzWidth, mzHeight, false) ;
     // draw start and end points
     drawStartEnd(mz.getStart(),mz.getEnd()) ;
  }
  // draw grid for generating maze
  // called if Show Gen on
  void drawGrid(Maze mz) {
     drawInit(mz) ;
     buffer.setColor(mg.wallColor);
     for (int i=0; i<cols-1; i++) {
        buffer.drawLine((wOffset+((i+1)*cellSize)),hOffset,
                        (wOffset+((i+1)*cellSize)),
                        (hOffset+(rows*cellSize))) ;
     }
     for (int j=0; j<rows-1; j++) {
        buffer.drawLine(wOffset,(hOffset+((j+1)*cellSize)),
                       (wOffset+(cols*cellSize)),
                       (hOffset+((j+1)*cellSize))) ;
     }
     // draw inner frame
     buffer.setColor(mg.frameColor);
     buffer.draw3DRect(wOffset, hOffset, mzWidth, mzHeight, false) ;
     repaint() ;
  }
  // knock down a single wall in our maze drawing
  // called if Show Gen on
  void drawGen(int x,int y,int direction,Maze mz) {
     buffer.setColor(mg.bkgrndColor);
     switch(direction) {
        case mz.NORTH: buffer.drawLine(
                       wOffset+((x*cellSize)+1),hOffset+(y*cellSize),
                       wOffset+((x+1)*cellSize)-1,hOffset+(y*cellSize) ) ;
                       break ;
        case mz.EAST:  buffer.drawLine(
                       wOffset+((x+1)*cellSize),hOffset+(y*cellSize)+1,
                       wOffset+((x+1)*cellSize),hOffset+((y+1)*cellSize)-1 ) ;
                       break ;
        case mz.SOUTH: buffer.drawLine(
                       wOffset+(x*cellSize)+1,hOffset+((y+1)*cellSize),
                       wOffset+((x+1)*cellSize)-1,hOffset+((y+1)*cellSize) ) ;
                       break ;
        case mz.WEST:  buffer.drawLine(
                       wOffset+(x*cellSize),hOffset+(y*cellSize)+1,
                       wOffset+(x*cellSize),hOffset+((y+1)*cellSize)-1 ) ;
                       break ;
     }
     repaint() ;
  }
  // draw the colorful start and end squares
  void drawStartEnd(Point startPt,Point endPt) {
     buffer.setColor(mg.startColor) ;
     buffer.fillRect((wOffset+(startPt.x*cellSize)+1),
                     (hOffset+(startPt.y*cellSize)+1),
                     (cellSize-2),(cellSize-2)) ;
     buffer.setColor(mg.endColor) ;
     buffer.fillRect((wOffset+(endPt.x*cellSize)+1),
                     (hOffset+(endPt.y*cellSize)+1),
                     (cellSize-2),(cellSize-2)) ;
     repaint() ;
  }
  // draw full solution path with or without backtracks
  // called if Show Solve off
  void drawPath(boolean showBack,Maze mz) {
     int cell = 0 ;
     
     for (int i=0; i<cols; i++) {
        for (int j=0; j<rows; j++) {
           cell = mz.getCell(i,j) ;
           // check for path first, only Center, N and W needed
           // since we'll draw N and W paths into the next cell
           buffer.setColor(mg.pathColor) ;
           if ((cell&mz.C_PATH)!=0) {
              buffer.fillRect(
                 (wOffset+(i*cellSize)+nwPathOffset),
                 (hOffset+(j*cellSize)+nwPathOffset),
                 pathSize,pathSize) ;
           }
           if ((cell&mz.N_PATH)!=0) {
              buffer.fillRect(
                 (wOffset+(i*cellSize)+nwPathOffset),
                 (hOffset+(j*cellSize)-sePathOffset),
                 pathSize,sePathOffset+nwPathOffset) ;
           }
           if ((cell&mz.W_PATH)!=0) {
              buffer.fillRect(
                 (wOffset+(i*cellSize)-sePathOffset),
                 (hOffset+(j*cellSize)+nwPathOffset),
                 sePathOffset+nwPathOffset,pathSize) ;
           }
           if (showBack) { 
              // same deal for backtracks
              buffer.setColor(mg.backColor) ;
              if ((cell&mz.C_BACK)!=0) {
                 buffer.fillRect(
                    (wOffset+(i*cellSize)+nwPathOffset),
                    (hOffset+(j*cellSize)+nwPathOffset),
                    pathSize,pathSize) ;
              }
              if ((cell&mz.N_BACK)!=0) {
                 buffer.fillRect(
                    (wOffset+(i*cellSize)+nwPathOffset),
                    (hOffset+(j*cellSize)-sePathOffset),
                    pathSize,sePathOffset+nwPathOffset) ;
              }
              if ((cell&mz.W_BACK)!=0) {
                 buffer.fillRect(
                    (wOffset+(i*cellSize)-sePathOffset),
                    (hOffset+(j*cellSize)+nwPathOffset),
                    sePathOffset+nwPathOffset,pathSize) ;
              }
           }
        }
     }
     // redraw start and end points
     drawStartEnd(mz.getStart(),mz.getEnd()) ;
  }
  // draw next cell (or backtrack cell) of solution path
  // called if Show Solve on
  void drawSolve(int x,int y,int direction,Color c,Maze mz) {
     buffer.setColor(c) ;
     // draw center 
     buffer.fillRect((wOffset+(x*cellSize)+nwPathOffset),
                    (hOffset+(y*cellSize)+nwPathOffset),
                    pathSize,pathSize) ;
     switch(direction) {
        case mz.NORTH: buffer.fillRect(
                       (wOffset+(x*cellSize)+nwPathOffset),
                       (hOffset+(y*cellSize)+nwPathOffset+pathSize),
                       pathSize,sePathOffset+nwPathOffset) ;
                       break ;
        case mz.EAST:  buffer.fillRect(
                       (wOffset+(x*cellSize)-sePathOffset),
                       (hOffset+(y*cellSize)+nwPathOffset),
                       sePathOffset+nwPathOffset,pathSize) ;
                       break ;
        case mz.SOUTH: buffer.fillRect(
                       (wOffset+(x*cellSize)+nwPathOffset),
                       (hOffset+(y*cellSize)-sePathOffset),
                       pathSize,sePathOffset+nwPathOffset) ;
                       break ;
        case mz.WEST:  buffer.fillRect(
                       (wOffset+(x*cellSize)+nwPathOffset+pathSize),
                       (hOffset+(y*cellSize)+nwPathOffset),
                       sePathOffset+nwPathOffset,pathSize) ;
                       break ;
     }
     repaint() ;
  }
  public void paint(Graphics g) { update(g) ; }
  public void update(Graphics g) { 
     if (bufferImage!=null) g.drawImage(bufferImage,0,0,this) ;
  }

}

/******** CONTROL PANEL ********

  the UI components
  • /

final class ControlPanel extends Panel {

  static final int MIN_CELLS=3, MAX_W_CELLS=50, MAX_H_CELLS=50, 
                   MAX_DELAY=500, MIN_DELAY=5 ;
  private int rows=25, cols=25, genDelay=50, solveDelay=50 ;
  private Button bGen, bSolve, bCycle ;
  private Button bRowsPlus, bRowsMinus, bColsPlus, bColsMinus ;
  private TextField tfRows, tfCols ;
  private Checkbox cbShowGen, cbShowSolve, cbShowBack ;
  private Choice cAlgorithm ;
  private Scrollbar sbGenSpeed, sbSolveSpeed ;
  private Font monoFont = new Font("Courier", Font.BOLD, 12) ;
  private Font textFont = new Font("Helvetica", Font.PLAIN, 12) ;
  private Font boldFont = new Font("Helvetica", Font.BOLD, 12) ;
  private Panel rowsPanel, colsPanel, rowsBtnPanel, colsBtnPanel ;
  private MazeGen mg ;
  private MazeCanvas mc ;
  private Panel p = new Panel() ;
  ControlPanel(MazeGen mg,MazeCanvas mc) {
     this.mg = mg ; this.mc = mc ;
     setLayout(new GridLayout(11,1,0,3)) ;
     setFont(textFont) ;
     // first set up the dimension controls
     rowsBtnPanel = new Panel() ;
     rowsBtnPanel.setForeground(mg.appletColor) ;
     colsBtnPanel = new Panel() ;
     colsBtnPanel.setForeground(mg.appletColor) ;
     rowsBtnPanel.setLayout(new GridLayout(1,2)) ;
     colsBtnPanel.setLayout(new GridLayout(1,2)) ;
     rowsBtnPanel.add(bRowsMinus = new Button("-")) ;
     rowsBtnPanel.add(bRowsPlus = new Button("+")) ;
     rowsBtnPanel.validate() ;
     colsBtnPanel.add(bColsMinus = new Button("-")) ;
     colsBtnPanel.add(bColsPlus = new Button("+")) ;
     colsBtnPanel.validate() ;
     rowsPanel = new Panel() ;
     rowsPanel.setFont(monoFont) ;
     rowsPanel.setLayout(new BorderLayout(2,0)) ;
     rowsPanel.add("West",new Label("H")) ;
     rowsPanel.add("Center",tfRows = new TextField(3)) ;
     rowsPanel.add("East",rowsBtnPanel) ;
     rowsPanel.validate() ;
     colsPanel = new Panel() ;
     colsPanel.setFont(monoFont) ;
     colsPanel.setLayout(new BorderLayout(2,0)) ;
     colsPanel.add("West",new Label("W")) ;
     colsPanel.add("Center",tfCols = new TextField(3)) ;
     colsPanel.add("East",colsBtnPanel) ;
     colsPanel.validate() ;
     tfRows.setEditable(false) ;
     tfCols.setEditable(false) ;
     // then the scrollbars
     sbGenSpeed = new Scrollbar(Scrollbar.HORIZONTAL,
                 (MAX_DELAY-genDelay),0,MIN_DELAY,MAX_DELAY) ;
     sbGenSpeed.setBackground(mg.panelColor) ;
     sbGenSpeed.setPageIncrement((int)(MAX_DELAY/10)) ;
     sbGenSpeed.setLineIncrement((int)(MAX_DELAY/100)) ;
     sbSolveSpeed = new Scrollbar(Scrollbar.HORIZONTAL,
                   (MAX_DELAY-solveDelay),0,MIN_DELAY,MAX_DELAY) ;
     sbSolveSpeed.setBackground(mg.panelColor) ;
     sbSolveSpeed.setPageIncrement((int)(MAX_DELAY/10)) ;
     sbSolveSpeed.setLineIncrement((int)(MAX_DELAY/100)) ;
     // now add everything
     add(bGen = new Button("GENERATE")) ;
     bGen.setFont(boldFont) ;
     add(rowsPanel) ;
     add(colsPanel) ;
     add(cAlgorithm = new Choice()) ;
     cAlgorithm.addItem("DFS");
     cAlgorithm.addItem("Prim");
     cAlgorithm.addItem("Kruskal");
     add(cbShowGen = new Checkbox("Show Gen")) ;
     add(sbGenSpeed) ;
     add(bSolve = new Button("SOLVE")) ;
     bSolve.setFont(boldFont) ;
     add(cbShowBack = new Checkbox("Backtracks")) ;
     add(cbShowSolve = new Checkbox("Show Solve")) ;
     add(sbSolveSpeed) ;
     add(bCycle = new Button("STOP CYCLE")) ;
     bCycle.setFont(boldFont) ;
     validate() ;
     // finally set controls to defaults
     tfRows.setText(Integer.toString(rows)) ;
     tfCols.setText(Integer.toString(cols)) ;
     cbShowGen.setState(true) ;
     cbShowBack.setState(true) ;
     cbShowSolve.setState(true) ;
     bGen.enable(false) ;
     bSolve.enable(false) ;
  }
  boolean isShowGen() { return cbShowGen.getState() ; }
  boolean isShowBack() { return cbShowBack.getState() ; }
  boolean isShowSolve() { return cbShowSolve.getState() ; }
  Dimension getDim() {return new Dimension(cols,rows);}
  int getAlgorithm() { return cAlgorithm.getSelectedIndex() ; }
  int getGenDelay() { return genDelay ; } 
  int getSolveDelay() { return solveDelay ; } 
  void setPlusMinusEnable() { 
     bRowsPlus.enable(rows<MAX_H_CELLS) ;
     bRowsMinus.enable(rows>MIN_CELLS) ;
     bColsPlus.enable(cols<MAX_W_CELLS) ;
     bColsMinus.enable(cols>MIN_CELLS) ;
  }   
  void setGenEnable(boolean b) { bGen.enable(b) ; }
  void setSolveEnable(boolean b) { bSolve.enable(b) ; }
  void setCycleEnable(boolean b) { bCycle.enable(b) ; }
  void setCycleLabel(String s) { bCycle.setLabel(s) ; }
  void setRows(int i) { 
     String s = Integer.toString(i) ;
     if (s.length()==1) s = " " + s ;
     tfRows.setText(s) ;
  } 
  void setCols(int i) { 
     String s = Integer.toString(i) ;
     if (s.length()==1) s = " " + s ;
     tfCols.setText(s) ;
  } 
  public boolean action(Event e,Object o) { 
     if ("GENERATE".equals(o)) { mg.startGen() ; }
     else if ("SOLVE".equals(o)) { mg.startSolve() ; }
     else if ("CYCLE".equals(o)) { mg.startCycle() ; } 
     else if ("STOP CYCLE".equals(o)) { mg.stopCycle() ; }
     else {
        if (e.target==cbShowGen) sbGenSpeed.enable(cbShowGen.getState()) ; 
        else if (e.target==cbShowSolve) sbSolveSpeed.enable(cbShowSolve.getState()) ; 
        if (e.target==bRowsPlus) setRows(++rows) ; 
        else if (e.target==bRowsMinus) setRows(--rows) ;
        else if (e.target==bColsPlus) setCols(++cols) ;
        else if (e.target==bColsMinus) setCols(--cols) ;
        setPlusMinusEnable() ;
     }
     mc.requestFocus() ;
     return true ;
  }
  public boolean handleEvent(Event e) {
     if (e.target==sbGenSpeed) {
        genDelay = MAX_DELAY - sbGenSpeed.getValue() ;
        return true ;
     }
     else if (e.target==sbSolveSpeed) {
        solveDelay = MAX_DELAY - sbSolveSpeed.getValue() ;
        return true ;
     }
     else return super.handleEvent(e) ;
  }

} </source>

id=siteTree