Java Writing Maze Games _java

Source: Internet
Author: User
Tags abs gety

Origin:

Last year (junior last semester) more like to write small games, so want to try to write a maze try.

Program Effect:

Press the space to display the path:

Thinking Process:

The maze consists of a lattice that requires only one path from the entrance to the exit.

Think about a variety of data structures, it seems that the tree is more appropriate, from the root node to each child node has only one path. If the portal is a root node and the exit is a child node in the tree, then the path from the root node to the child node must be unique.

So if you can construct a tree to cover all the squares, you can make a maze.

It is also required that the parent and child nodes of the tree must be adjacent squares on the interface.

When the interface is displayed, the shared edges between the parent node and the child node are not drawn, and the other edges are drawn, and a maze can be drawn.

After that is to think about how to achieve such a tree.

The first two questions:

1, how does the tree say?

2, how to construct this tree?

1. What does the tree say?

Assuming that the tree is implemented like a two-fork tree, each tree node will store one coordinate (x,y) to represent a lattice, and four pointers to be stored. Some of the pointers are empty, some are not empty, the pointer is not empty to the child nodes, and the child nodes hold the coordinates of the neighbor grid. The biggest problem with this is the inability to determine whether all the squares are in the tree. You might also want to use a two-dimensional array as a marker array.

If a two-dimensional array is used to represent the lattice of the maze. Each array element stores a reference to the parent node, which can also form a virtual tree. A n*n two-dimensional array is used to represent the n*n lattice, and each array element (lattice) has a reference (father) to the parent node. In addition, in order to be able to easily obtain the coordinates of the grid, but also to save the coordinate information.

2. How to construct this tree?

First select a lattice as the root node. To make the shape of the maze random enough, I chose to randomly generate a coordinate as the root node. In fact, the choice of a certain coordinates can also be.

Then, how do you add nodes to this tree?

I've made a lot of detours here, starting off with an algorithm that looks like backtracking at the time (no backtracking algorithm was yet known). , but the time complexity is very high, probably when the maze is 64*64, the algorithm is not the result.

Then, a sweep depth search is also a backtracking method, each scan in the current tree to find a node, see if the neighborhood grid is in the tree, if it's not in the tree, add the neighbor grid to the tree, and if it's in the tree, look at the next neighbor grid, if all the neighborhood squares are in the tree, Just find the next node and continue the same operation. In addition, in order to allow the maze to generate random, the initial location of the scan is random. However, the method generated in the maze path is always not deep enough, without the twists and turns I want to deep effect. After all, is similar to breadth search method. Moreover, this is always like relying on brute force, the algorithm is not smart and concise.

Finally, I finally thought of using deep search. Probably because the data structure has been studied for a year, and did not practice, forget a lot, so never thought this should be the first thought of the method.

Randomly select a lattice as the root node, from it began to randomly depth search forward, open a road, until there is no way to go, return a step, change another road, and then go to no way to go, back one step, for another ... This cycle, until there is no way to go ... In fact, it is still backtracking.

The following procedure is in the program (see the Createmaze () function in the code):

Randomly select a lattice as the root node and press it into the stack.

Then perform the following loops when the stack is not empty:

Take out a lattice, set its intree flag to 1, and then press all its neighbor squares not in the tree into the stack (in random order), and let the neighbor's father point to the grid.

Solve these two problems, the rest of the painting maze, display path, small ball movement is relatively simple.

Code

Package maze;
Import Java.awt.Color;
Import Java.awt.Graphics;
Import Java.awt.event.KeyAdapter;
Import java.awt.event.KeyEvent;
Import Java.util.Random;
Import Java.util.Stack;
Import Javax.swing.JFrame;
Import Javax.swing.JOptionPane;
Import Javax.swing.JPanel;
  Class Lattice {static final int intree = 1;
  static final int notintree = 0;
  private int x =-1;
  private int y =-1;
  private int flag = Notintree;
  Private lattice father = null;
    public lattice (int xx, int yy) {x = xx;
  y = yy;
  public int GetX () {return x;
  public int GetY () {return y;
  public int Getflag () {return flag;
  Public lattice Getfather () {return father;
  public void Setfather (lattice f) {father = f;
  public void Setflag (int f) {flag = f;
  public string toString () {return new string ("+ x +", "+ y +") \ n ");
  } public class Maze extends JPanel {private static final long serialversionuid = -8300339045454852626l; Private int NUM, width, padding;//widths of each lattice and height of private lattice[][] maze;
  private int ballx, BallY;
  Private Boolean drawpath = false;
    Maze (int m, int wi, int p) {NUM = m;
    width = WI;
    padding = p;
    Maze = new Lattice[num][num];
    for (int i = 0; I <= NUM-1. i++) for (int j = 0; J <= NUM-1; j +) maze[i][j] = new Lattice (i, j);
    Createmaze ();
    Setkeylistener ();
  This.setfocusable (TRUE);
        } private void Init () {for (int i = 0; I <= NUM-1; i++) for (int j = 0; J <= NUM-1; j +) {
        Maze[i][j].setfather (NULL);
      Maze[i][j].setflag (Lattice.notintree);
    } ballx = 0;
    BallY = 0;
    DrawPath = false;
    Createmaze ();
    Setkeylistener ();
    This.setfocusable (TRUE);
  Repaint ();
  public int Getcenterx (int x) {return padding + x * width + width/2;
  public int getcentery (int y) {return padding + y * width + width/2;
   public int Getcenterx (lattice p) { return padding + p.gety () * width + width/2;
  public int getcentery (lattice p) {return padding + p.getx () * width + width/2; private void Checkiswin () {if (Ballx = = NUM-1 && BallY = = NUM-1) {Joptionpane.showmessagedialo g (NULL, "WIN!", "You're out of the maze."
      ", joptionpane.plain_message);
    Init ();
    } synchronized private void move (int c) {int tx = BALLX, ty = BallY;
    System.out.println (c);
        Switch (c) {case keyevent.vk_left:ty--;
      Break
        Case keyevent.vk_right:ty++;
      Break
        Case keyevent.vk_up:tx--;
      Break
        Case keyevent.vk_down:tx++;
      Break
        Case KeyEvent.VK_SPACE:if (DrawPath = = true) {DrawPath = false;
        else {DrawPath = true;
      } break;
      Default: if (!isoutofborder (TX, Ty) && (maze[tx][ty].getfather () = = maze[ballx][bally]      ||
      Maze[ballx][bally].getfather () = = Maze[tx][ty])) {ballx = TX;
    BallY = Ty; }} private void Setkeylistener () {This.addkeylistener (new Keyadapter () {public void keypressed (KeyEvent E
        {int c = E.getkeycode ();
        Move (c);
        Repaint ();

      Checkiswin ();
  }
    });
  Private Boolean Isoutofborder (lattice p) {return Isoutofborder (P.getx (), p.gety ()); Private Boolean Isoutofborder (int x, int y) {return (x > NUM-1 | | y > NUM-1 | | x < 0 | | y < 0)?
  True:false; 
      } private lattice[] Getneis (lattice p) {Final int[] adds = {1, 0, 1, 0, -1};//order is upper right left if (Isoutofborder (p)) {
    return null;
    } lattice[] ps = new lattice[4];//order for upper right lower left int xt;
    int YT;
      for (int i = 0; I <= 3; i++) {XT = P.getx () + adds[i];
      YT = p.gety () + adds[i + 1];
      if (Isoutofborder (XT, YT)) continue;
    Ps[i] = Maze[xt][yt];
  } return PS; } Private void Createmaze () {Random Random = new Random ();
    int rx = Math.Abs (Random.nextint ())% NUM;
    int ry = Math.Abs (Random.nextint ())% NUM;
    stack<lattice> s = new stack<lattice> ();
    Lattice p = Maze[rx][ry];
    Lattice neis[] = null;
    S.push (P);
      while (!s.isempty ()) {p = S.pop ();
      P.setflag (Lattice.intree);
      Neis = Getneis (p);
      int ran = Math.Abs (Random.nextint ())% 4;
        for (int a = 0; a <= 3; a++) {ran++;
        Ran%= 4;
        if (Neis[ran] = = NULL | | Neis[ran].getflag () = = Lattice.intree) continue;
        S.push (Neis[ran]);
      Neis[ran].setfather (P);
  }//Changefather (Maze[0][0],null);
      } private void Changefather (lattice p, lattice f) {if (p.getfather () = = null) {p.setfather (f);
    Return
    else {Changefather (P.getfather (), p); } private void Clearfence (int i, int j, int fx, int fy, Graphics g) {int sx = padding + (J > fy?) J:FY) * width), sy = padding + ((i > FX? i:fx) * width), dx = (i = = FX? Sx:sx + width),
    DY = (i = = FX? sy + width:sy);
      if (SX!= dx) {sx++;
    dx--;
      else {sy++;
    dy--;
  } g.drawline (SX, sy, DX, DY);
    } protected void Paintcomponent (Graphics g) {super.paintcomponent (g); for (int i = 0; I <= NUM; i++) {g.drawline (padding + i * width, padding, padding + i * width, padding
    + NUM * width);
          for (int j = 0; J <= NUM; j +) {g.drawline (padding, padding + j * Width, padding + NUM * width,
    padding + j * width);
    } g.setcolor (This.getbackground ()); for (int i = NUM-1 i >= 0; i--) {for (int j = NUM-1; J >= 0; j--) {Lattice F = MAZE[I][J].GETFA
        ther ();
          if (f!= null) {int FX = F.GETX (), FY = f.gety ();
        Clearfence (i, J, FX, FY, G); }} g.drawline (padding, padding + 1, padding, padding + width-1);
    int last = padding + NUM * width;
    G.drawline (last, Last-1, last, Last-width + 1);
    G.setcolor (color.red);
    G.filloval (Getcenterx (BallY)-WIDTH/3, Getcentery (BALLX)-WIDTH/3, WIDTH/2, WIDTH/2);
  if (DrawPath = = True) DrawPath (g);
    } private void DrawPath (Graphics g) {Color Path_color = color.orange, Both_path_color = Color.pink;
    if (DrawPath = = True) G.setcolor (Path_color);
    Else G.setcolor (This.getbackground ());
    Lattice p = maze[num-1][num-1];
      while (P.getfather ()!= null) {P.setflag (2);
    p = P.getfather ();
    G.filloval (Getcenterx (p)-WIDTH/3, Getcentery (p)-WIDTH/3, WIDTH/2, WIDTH/2);
    p = maze[0][0];
        while (P.getfather ()!= null) {if (P.getflag () = = 2) {P.setflag (3);
      G.setcolor (Both_path_color); G.drawline (Getcenterx (p), Getcentery (p), Getcenterx (P.getfather ()), Getcentery (P.getfather ()));
    p = P.getfather ();
    } g.setcolor (Path_color);
    p = maze[num-1][num-1];
      while (P.getfather ()!= null) {if (P.getflag () = = 3) break;
      G.drawline (Getcenterx (p), Getcentery (p), Getcenterx (P.getfather ()), Getcentery (P.getfather ()));
    p = P.getfather ();
    } public static void Main (string[] args) {final int n = =, Width = $, padding =, LX = =, LY = 100;
    JPanel p = new Maze (n, (width-padding-padding)/n, padding);
    JFrame frame = new JFrame ("MAZE (Show or hide path by spacebar)");
    Frame.getcontentpane (). Add (P);
    Frame.setdefaultcloseoperation (Jframe.exit_on_close);
    Frame.setsize (width + padding, width + padding + padding);
    Frame.setlocation (LX, LY);
  Frame.setvisible (TRUE); }
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.