java课设走迷宫(含代码)
一个关於迷宫算法的JAVA程序
一个关於迷宫算法的JAVA程序以下是一个关于迷宫算法的JAVA程序的示例,代码注释中解释了程序的工作原理和算法实现细节。
```javaimport java.util.ArrayDeque;import java.util.ArrayList;import java.util.Deque;import java.util.List;public class MazeSolverprivate int[][] maze;private int[][] solution;private int size;public MazeSolver(int[][] maze)this.maze = maze;this.size = maze.length;this.solution = new int[size][size];}//迷宫的通路为0,墙壁为1,已走过的路径为2//使用深度优先算法找到从起点到终点的路径public boolean solveMazboolean[][] visited = new boolean[size][size];return solveMazeHelper(0, 0, visited);}private boolean solveMazeHelper(int x, int y, boolean[][] visited)//检测是否到达终点if (x == size - 1 && y == size - 1)solution[x][y] = 1;return true;}//检查当前位置是否可行if (isSafe(x, y, visited))//标记当前位置为已访问visited[x][y] = true;//标记当前位置为路径的一部分solution[x][y] = 1;//递归探索当前位置的相邻位置if (solveMazeHelper(x + 1, y, visited)) // 向右移动return true;if (solveMazeHelper(x, y + 1, visited)) // 向下移动return true;if (solveMazeHelper(x - 1, y, visited)) // 向左移动return true;if (solveMazeHelper(x, y - 1, visited)) // 向上移动return true;//如果没有找到路径,取消当前位置的标记solution[x][y] = 0;}return false;}private boolean isSafe(int x, int y, boolean[][] visited) //检查坐标是否在合法范围内,且该位置没有被访问过return x >= 0 && y >= 0 && x < size && y < size &&maze[x][y] == 0 && !visited[x][y];}//使用BFS算法找到从起点到终点的最短路径public List<Integer> findShortestPatboolean[][] visited = new boolean[size][size];int[][] distance = new int[size][size];int[][] parent = new int[size][size];//初始化距离和父节点数组for (int i = 0; i < size; i++)for (int j = 0; j < size; j++)distance[i][j] = Integer.MAX_VALUE; // 初始距离为无穷大parent[i][j] = -1; // 初始父节点为无效值}}//使用BFS算法来设置距离和父节点数组Deque<int[]> queue = new ArrayDeque<>(;queue.offer(new int[]{0, 0}); // 起点入队列visited[0][0] = true;distance[0][0] = 0;int[][] directions = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; // 右下左上while (!queue.isEmpty()int[] current = queue.poll(;int x = current[0];int y = current[1];for (int[] direction : directions)int newX = x + direction[0];int newY = y + direction[1];if (isSafe(newX, newY, visited))visited[newX][newY] = true;queue.offer(new int[]{newX, newY});distance[newX][newY] = distance[x][y] + 1; // 更新距离parent[newX][newY] = x * size + y; // 更新父节点}}}//从终点回溯到起点,构造最短路径List<Integer> shortestPath = new ArrayList<>(;int currentX = size - 1;int currentY = size - 1;while (parent[currentX][currentY] != -1)shortestPath.add(0, currentX * size + currentY); // 将当前节点添加到路径首部int parentX = parent[currentX][currentY] / size;int parentY = parent[currentX][currentY] % size;currentX = parentX;currentY = parentY;}shortestPath.add(0, 0); // 添加起点到路径首部return shortestPath;}public void printSolutiofor (int[] row : solution)for (int cell : row)System.out.print(cell + " ");}System.out.println(;}}public static void main(String[] args)int[][] maze ={0,1,1,1,1},{0,0,1,0,1},{1,0,0,0,0},{1,1,0,1,1},{1,1,0,0,0}};MazeSolver solver = new MazeSolver(maze);solver.solveMaze(;System.out.println("Solution:");solver.printSolution(;List<Integer> shortestPath = solver.findShortestPath(;System.out.println("Shortest Path:" + shortestPath);}```此程序实现了解决迷宫问题的两种算法:深度优先和广度优先。
数据结构课程设计迷宫算法的实现java
数据结构课程设计走迷宫学号:200908204136姓名:熊军日期:6月16日一、题目说明.分别用以下算法实现。
并设计图形用户界面提供迷宫大小、入口及出口位置和初始状态等,演示走迷宫的过程和结果。
1.递归算法。
2.使用栈作为辅助结构。
3.使用队列作为辅助结构。
二、总体设计方案以及细节设计为实现上述程序功能,主要使用的JA V A AWT和JA V A SWING包import java.awt.*;import javax.swing.*;import hartech.ui.*;3. 本程序包含四个模块:1)主程序模块:package mg;import java.awt.*;import javax.swing.*;/*** <p>Title: maze Global class</p>** <p>Description: </p>** <p>Date: 2006-08-31 </p>*/public class Main {// _reset 变量用于reset时用static int rows = 12, cols = 14;static int speed_reset = 50, speed = speed_reset;static JToggleButton[][] buttons;static Walking walking;static boolean[][] brick, brick_reset = {{ true, true, true, true, true, false, true, true, true, true,true, true, true, true, },{ true, false, false, false, true, false, true, true, true, true,false, false, false, true, },{ true, false, true, false, true, false, false, false, false, true,true, false, true, true, },{ true, false, true, false, true, false, true, true, true, false,true, false, true, false, },{ true, true, true, false, false, false, true, false, true, false,true, false, true, true, },{ true, false, true, true, true, true, true, false, true, false,true, false, false, true, },{ true, false, true, true, true, true, true, false, true, false,true, false, true, true, },{ true, false, false, false, false, false, true, true, true, false,true, false, true, false, },{ true, false, true, true, true, false, false, false, false, false,true, false, true, true, },{ true, false, true, false, true, false, true, true, true, true,true, false, false, true, },{ true, false, true, false, true, false, true, false, false, false,false, false, true, true, },{ true, true, true, false, true, true, true, true, true, true,true, false, true, true, }};static JFrame jFrame;static UI ui;public static void main(String[] args) {//启动新线程,创建一个窗口javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() {//J.setLookAndFeel("Metal");jFrame = new JFrame("is there any way to go? Maze --- ");//建立一个Swing窗体jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//单击关闭图标后,程序退出并关闭// addMain.ui = new UI();jFrame.add(ui, BorderLayout.CENTER);jFrame.setSize(700, 400);//J.goCenter(jFrame);Main.drawButtons();Main.reset();jFrame.setVisible(true);}});}// 用于重置到软件开始public static void reset() {if (walking != null) {walking.timer.stop();}clean();brick = copyBoolean(brick_reset);speed = speed_reset;UI.jSlider.setValue(speed);setBricks();}// 用于清楚已标记上的数字public static void clean() {if (walking != null) {walking.timer.stop();}for (int i = 0; i < rows; i++) {for (int j = 0; j < cols; j++) {buttons[i][j].setText("");//清除按钮的数字,设置名字为空buttons[i][j].setForeground(null);}}UI.jLabel_state.setText(" Move now?");}// 去掉全部砖public static void blank() {if (walking != null) {walking.timer.stop();}for (int i = 0; i < rows; i++) {for (int j = 0; j < cols; j++) {buttons[i][j].setText("");buttons[i][j].setForeground(null);buttons[i][j].setSelected(true);}}UI.jLabel_state.setText(" Move now?");}// 重画按钮图,根据rows、colspublic static JPanel drawButtons() {buttons = new JToggleButton[rows][cols];UI.jPanel_map = new JPanel(new GridLayout(rows, cols));for (int i = 0; i < rows; i++) {for (int j = 0; j < cols; j++) {buttons[i][j] = new JToggleButton();UI.jPanel_map.add(buttons[i][j]);}}Main.ui.add(UI.jPanel_map, BorderLayout.CENTER);Main.ui.setVisible(true);return UI.jPanel_map;}// 根据brick[][]设置按钮障碍public static void setBricks() {for (int i = 0; i < rows; i++) {for (int j = 0; j < cols; j++) {buttons[i][j].setSelected(brick[i][j]);}}}// 根据现在按钮情况设置brick[][]数组,用于move()内前面public static void readBricks() {for (int i = 0; i < rows; i++) {for (int j = 0; j < cols; j++) {brick[i][j] = buttons[i][j].isSelected();}}}// 开始走public static void move() {if (walking != null) {walking.timer.stop();}clean();readBricks();//readToFile();walking = new Walking(brick);}/**// 用于把绘制好地图数据写入文件public static void readToFile() {String out = "";for (int i = 0; i < rows; i++) {out += "{";for (int j = 0; j < cols; j++) {if (brick[i][j]) {out += "true,";}else {out += "false,";}}out += "},\r\n";}hartech.JFile.stringToFile(out, "E:/dest.txt");}*/// 复制二维数组public static boolean[][] copyBoolean(boolean[][] in) { int row = in.length, col = in[0].length;boolean[][] out = new boolean[row][col];for (int i = 0; i < row; i++) {for (int j = 0; j < col; j++) {out[i][j] = in[i][j];}}return out;}}import java.awt.*;import javax.swing.*;import hartech.ui.*;/*** <p>Title: maze Global class</p>** <p>Description: </p>** <p>Date: 2006-08-31 </p>*/public class Main {// _reset 变量用于reset时用static int rows = 12, cols = 14;static int speed_reset = 50, speed = speed_reset;static JToggleButton[][] buttons;static Walking walking;static boolean[][] brick, brick_reset = {{ true, true, true, true, true, false, true, true, true, true,true, true, true, true, },{ true, false, false, false, true, false, true, true, true, true,false, false, false, true, },{ true, false, true, false, true, false, false, false, false, true,true, false, true, true, },{ true, false, true, false, true, false, true, true, true, false,true, false, true, false, },{ true, true, true, false, false, false, true, false, true, false,true, false, true, true, },{ true, false, true, true, true, true, true, false, true, false,true, false, false, true, },{ true, false, true, true, true, true, true, false, true, false,true, false, true, true, },{ true, false, false, false, false, false, true, true, true, false,true, false, true, false, },{ true, false, true, true, true, false, false, false, false, false,true, false, true, true, },{ true, false, true, false, true, false, true, true, true, true,true, false, false, true, },{ true, false, true, false, true, false, true, false, false, false,false, false, true, true, },{ true, true, true, false, true, true, true, true, true, true,true, false, true, true, }};static JFrame jFrame;static UI ui;public static void main(String[] args) {//启动新线程,创建一个窗口javax.swing.SwingUtilities.invokeLater(new Runnable() {public void run() {J.setLookAndFeel("Metal");jFrame = new JFrame("is there any way to go? Maze --- ");//建立一个Swing窗体jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//单击关闭图标后,程序退出并关闭// addMain.ui = new UI();jFrame.add(ui, BorderLayout.CENTER);jFrame.setSize(700, 400);J.goCenter(jFrame);Main.drawButtons();Main.reset();jFrame.setVisible(true);}});}// 用于重置到软件开始public static void reset() {if (walking != null) {walking.timer.stop();}clean();brick = copyBoolean(brick_reset);speed = speed_reset;UI.jSlider.setValue(speed);setBricks();}// 用于清楚已标记上的数字public static void clean() {if (walking != null) {walking.timer.stop();}for (int i = 0; i < rows; i++) {for (int j = 0; j < cols; j++) {buttons[i][j].setText("");//清除按钮的数字,设置名字为空buttons[i][j].setForeground(null);}}UI.jLabel_state.setText(" Move now?");}// 去掉全部砖public static void blank() {if (walking != null) {walking.timer.stop();}for (int i = 0; i < rows; i++) {for (int j = 0; j < cols; j++) {buttons[i][j].setText("");buttons[i][j].setForeground(null);buttons[i][j].setSelected(true);}}UI.jLabel_state.setText(" Move now?");}// 重画按钮图,根据rows、colspublic static JPanel drawButtons() {buttons = new JToggleButton[rows][cols];UI.jPanel_map = new JPanel(new GridLayout(rows, cols));for (int i = 0; i < rows; i++) {for (int j = 0; j < cols; j++) {buttons[i][j] = new JToggleButton();UI.jPanel_map.add(buttons[i][j]);}}Main.ui.add(UI.jPanel_map, BorderLayout.CENTER);Main.ui.setVisible(true);return UI.jPanel_map;}// 根据brick[][]设置按钮障碍public static void setBricks() {for (int i = 0; i < rows; i++) {for (int j = 0; j < cols; j++) {buttons[i][j].setSelected(brick[i][j]);}}}// 根据现在按钮情况设置brick[][]数组,用于move()内前面public static void readBricks() {for (int i = 0; i < rows; i++) {for (int j = 0; j < cols; j++) {brick[i][j] = buttons[i][j].isSelected();}}}// 开始走public static void move() {if (walking != null) {walking.timer.stop();}clean();readBricks();//readToFile();walking = new Walking(brick);}/**// 用于把绘制好地图数据写入文件public static void readToFile() {String out = "";for (int i = 0; i < rows; i++) {out += "{";for (int j = 0; j < cols; j++) {if (brick[i][j]) {out += "true,";}else {out += "false,";}}out += "},\r\n";}hartech.JFile.stringToFile(out, "E:/dest.txt");}*/// 复制二维数组public static boolean[][] copyBoolean(boolean[][] in) { int row = in.length, col = in[0].length;boolean[][] out = new boolean[row][col];for (int i = 0; i < row; i++) {for (int j = 0; j < col; j++) {out[i][j] = in[i][j];}}return out;}}2) UI模块——实现整个控制面板内组件的布局管理;3)Walking模块——实现走迷宫的算法;4)Applete模块——设置控制面板。
java迷宫小游戏源代码
帮朋友写的迷宫小游戏程序java//作者:LaoCooonimport java.awt.Graphics; import javax.swing.ImageIcon;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JPanel;import java.awt.event.*; import javax.swing.*; import java.awt.*;class mMaze extends Frame{ Color redColor;Random Random=new Random();int mapI=Random.getRandom();MapArray MapArray=new MapArray();int[] map = MapArray.getMapArray(mapI);static ImageIcon wall= new ImageIcon("wall.jpg");final ImageIcon tortoise= new ImageIcon("tortoise.gif");int xl=0,yl=1,speed=30;int x=0,y=1;public mMaze(){addKeyListener(new KeyAdapter(){public void keyPressed(KeyEvent e){if(e.getKeyCode()== KeyEvent.VK_UP){System.out.println("\n Go Up"); if(map[(yl-1)*29+xl]!=1) yl-=1; }else if(e.getKeyCode()== KeyEvent.VK_DOWN){ System.out.println("\n Go Down"); if(map[(yl+1)*29+xl]!=1) yl+=1; } else if(e.getKeyCode()== KeyEvent.VK_LEFT){ System.out.println("\n Go Left"); if(map[yl*29+(xl-1)]!=1) xl-=1; } else if(e.getKeyCode()== KeyEvent.VK_RIGHT){ System.out.println("\n Go Right"); if(map[yl*29+(xl+1)]!=1) xl+=1; } else System.out.println(e.getKeyChar());if(y==27&&x==28) System.out.println("\n You Win~!");repaint(); } } );setSize(890,910); setVisible(true); setLocation(400,200);addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ dispose(); System.exit(0); } } ); }public void paint(Graphics g){g.drawImage(tortoise.getImage(), xl*speed+8, yl*speed+30, null);int i=0,j=0;for ( i = 0; i < 29; i++)for(j=0;j<29;j++)if(map[i*29+j]==1) g.drawImage(wall.getImage(), j*30+8, i*30+30, null);}}public class Maze{public static void main(String[] args){ new mMaze(); }}回复•2楼•2013-05-16 10:34•删除 |••LaoCooon•class MapArray{public int[] getMapArray(int i){int[] map ={1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1, 1,1,1,0,1,0,1,1,1,0,1,0,1,0,1,1,1,0,1,0,1,1,1,0,1,0,1,0,1, 1,0,0,0,1,0,0,0,1,0,0,0,1,0,1,0,0,0,1,0,0,0,1,0,1,0,1,0,1, 1,0,1,1,1,1,1,0,1,1,1,1,1,0,1,0,1,1,1,1,1,0,1,0,1,0,1,0,1, 1,0,1,0,0,0,0,0,1,0,0,0,1,0,1,0,1,0,1,0,0,0,1,0,1,0,1,0,1, 1,0,1,0,1,1,1,1,1,0,1,0,1,0,1,0,1,0,1,0,1,1,1,0,1,0,1,0,1, 1,0,0,0,1,0,0,0,0,0,1,0,1,0,0,0,1,0,1,0,0,0,0,0,1,0,1,0,1, 1,0,1,1,1,0,1,1,1,1,1,0,1,1,1,0,1,0,1,1,1,1,1,1,1,0,1,0,1, 1,0,1,0,0,0,1,0,0,0,1,0,0,0,1,0,1,0,0,0,0,0,1,0,0,0,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0,0,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1, 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1, 1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1, 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,1, 1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1, 1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,1,0,1,0,0, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,};if(i<0&&i>4) i=1;switch(i){case 0:map=map;break;case 1:map=map1;break;case 2:map=map2;break;case 3:map=map3;break;case 4:map=map4;break;default: map=map;}return map;}}•••LaoCooon•import java.util.Date;import java.util.Calendar;class Random{public int getRandom(){Calendar c = Calendar.getInstance(); int second = c.get(Calendar.SECOND); //System.out.println(second%5); return second%5;}}回复•4楼•2013-05-16 10:37•删除 |•。
(完整word版)课程设计-走迷宫
《数据结构程序设计》课程设计报告(走迷宫)学院:班级:学号:姓名:指导教师:完成日期:目录1.设计任务 (3)2.程序的总体设计 (3)3.程序的实现 (8)4.主函数 (9)5.测试 (10)6.心得体会 (12)7.附件 (13)1.设计任务程序开始运行时显示一个迷宫地图,迷宫中央有一只老鼠,迷宫的右下方有一个粮仓。
游戏的任务是使老鼠走到粮仓处。
要求:1)迷宫的墙足够结实,老鼠不能穿墙而过;2)正确检测结果,若老鼠在能走到粮仓处,提示成功,否则提示失败;3)老鼠形象可辨认,可用键盘操纵老鼠上下左右移动;2.程序的总体设计首先,确定迷宫的存储结构,说明位置在迷宫中的行坐标和列坐标。
typedef int Status;typedef struct{int r,c;/*迷宫中位置的坐标*/}PosType;typedef struct{int m,n;char arr[RANGE][RANGE]; /*用二维数组表示迷宫*/}MazeType;第二,确定放入栈中的元素的存储结构,表明通道块在路径上的“序号”,通道块的坐标位置以及下一步要走的方向。
typedef int directiveType;typedef struct{int step;PosType seat;/*当前位置在迷宫中的坐标*/ directiveType di;/*从当前位置走到下一位置的方向*/ }ElemType;第三,确定栈的存储结构。
typedef struct NodeType{ElemType data;struct NodeType *next;}NodeType,*LinkType;typedef struct{LinkType top;/*链栈的顶点定义*/int size;}Stack;void InitStack(Stack &S)/*构建一个空栈*/{S。
top=NULL;S。
size=0;}Status MakeNode(LinkType &p,ElemType e){p=(NodeType *)malloc(sizeof(NodeType));if(!p)return FALSE;/*存储分配失败*/p—>data=e;p—〉next=NULL;return TRUE;}定义在什么情况下要入栈Status Push(Stack &S,ElemType e){LinkType p;if(MakeNode(p,e)){p->next=S。
java写的迷宫代码
java写的迷宫代码迷宫代码:截图如下:package com.zxl.maze;/** 抽象类表⽰选择不同的算法*/public abstract class AbstractMap{/** 得到数据*/public abstract boolean[][] getData(int m,int n);/** 重置*/public abstract void reset(int m,int n);}package com.zxl.maze;/**深度优先,⽣成迷宫*/import java.awt.Point;import java.util.Random;import java.util.Stack;public class DFSMap extends AbstractMap{private int m = 30, n = 30;private boolean a[][];private int currX, currY;private Stack<Point> stack;// 保存已⾛路径private int[] X_GO1 = { -2, 2, 0, 0 };private int[] Y_GO1 = { 0, 0, 2, -2 };private int[] X_GO2 = { -1, 1, 0, 0 };private int[] Y_GO2 = { 0, 0, 1, -1 };public DFSMap(){stack = new Stack<Point>();}@Overridepublic boolean[][] getData(int m,int n)// 得到数据{// TODO Auto-generated method stubreset(m, n);return a;}@Overridepublic void reset(int m, int n)// 重置{// TODO Auto-generated method stuba = new boolean[2 * m + 1][2 * n + 1];this.m = 2 * m + 1;this.n = 2 * n + 1;for (int i = 0; i < this.m; i++)for (int j = 0; j < this.n; j++)a[i][j] = false;currX = 1;currY = 1;stack.clear();stack.push(new Point(1, 1));a[1][0] = true;a[1][1] = true;start();}private boolean check()// 判断是否全部⾛过。
一个关於迷宫算法的JAVA程序
一个关於迷宫算法的JAVA程序以下是一个使用深度优先算法解决迷宫问题的JAVA程序:```javaimport java.util.*;public class MazeSolverprivate static int[][] maze; // 迷宫地图private static int width; // 迷宫宽度private static int height; // 迷宫高度private static int[][] visited; // 记录访问状态//初始化迷宫public static void initializeMaze(int[][] mazeData) width = mazeData[0].length;height = mazeData.length;maze = new int[height][width];visited = new int[height][width];for (int i = 0; i < height; i++)for (int j = 0; j < width; j++)maze[i][j] = mazeData[i][j];visited[i][j] = 0;}}}//深度优先算法public static boolean solveMaze(int x, int y)if (x < 0 , x >= width , y < 0 , y >= height) return false; // 超出边界if (maze[y][x] == 1)return false; // 遇到墙if (visited[y][x] == 1)return false; // 已经访问过visited[y][x] = 1; // 标记为已访问if (x == width - 1 && y == height - 1)return true; // 到达终点//上下左右四个方向if (solveMaze(x + 1, y)) // 向右走return true;if (solveMaze(x - 1, y)) // 向左走return true;if (solveMaze(x, y + 1)) // 向下走return true;if (solveMaze(x, y - 1)) // 向上走return true;return false; // 无法到达终点}public static void main(String[] args) int[][] mazeData ={0,1,1,1,1},{0,0,0,0,1},{1,1,1,0,0},{1,1,1,0,1},{1,1,1,0,1}};initializeMaze(mazeData);boolean solved = solveMaze(0, 0);if (solved)System.out.println("迷宫有解!");} elseSystem.out.println("迷宫无解!");}}```以上程序使用了深度优先算法来解决迷宫问题。
走迷宫游戏的JAVA实现86630
//MazeWindow.javaimport java.swing.*;import java.awt.*;import java.awt.event.*;import java.io.*;import javax.swing.filechooser.*;public class MazeWindow extends JFrame implements ActionListener{ Maze maze;JMenuBar bar;JMenu menuChoice,menuImage;JMenuItem wallImage,roadImage,defaultImage;File mazeFile,wallImageFile,roadImageFile;JButton renew;MazeWindow(){wallImageFile=new File("wall.jpg");roadImageFile=new File("road.jpg");bar=new JMenuBar();menuChoice=new JMenu("选择迷宫");File dir=new File(".");File file[]=dir.listFiles(new FilenameFilter(){public boolean accept(File dir,String name){return name.endsWith("maze");}})for(int i=0;i<file.length;i++){JMenuItem item=new JMenuItem(file[i].getName());item.addActionListener(this);menuChoice.add(item);}mazeFile=new File(file[0].getName());init();menuImage=new JMenu("选择墙和路的图像(JPG,GIF)"); wallImage=new JMenuItem("墙的图像");roadImage=new JMenuItem("路的图像");defaultImage=new JMenuItem("墙和路的默认图像"); menuImage.add(wallImage);menuImage.add(roadImage);menuImage.add(defaultImage);bar.add(menuChoice);bar.add(menuImage);setJMenuBar(bar);wallImage.addActionListener(this);roadImage.addActionListener(this);defaultImage.addActionListener(this);renew=new JButton("重新开始");renew.addActionListener(this);add(maze,BorderLayout.CENTER);add(renew,BorderLayout.SOUTH);setVisible(true);setBounds(60,60,510,480);validate();setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}public void init(){if(maze!=null){remove(maze);remove(maze.getHandleMove());}maze=new Maze();maze.setWallImage(wallImageFile);maze.setRoadImage(roadImageFile);maze.setMazeFile(mazeFile);add(maze,BorderLayout.CENTER);add(maze.getHandleMove(),BorderLayout.NORTH);validate();}public void actionPerformed(ActionEvent e){if(e.getSource()==roadImage){JFileChooser chooser=new JFileChooser();FileNameExtensionFilter filter=new FileNameExtensionFilter("JPG & GIF Images","jpg","gif");chooser.setFileFilter(filter);int state=chooser.showOpenDialog(null);File file=chooser.getSelectedFile();if(file!=null&&state==JFileChooser.APPROVE_OPTION){ roadImageFile=file;maze.setRoadImage(roadImageFile);}}else if(e.getSource()==wallImage){JFileChooser chooser=new JFileChooser();FileNameExtensionFilter filter=new FileNameExtensionFilter("JPG & GIF Images","jpg","gif");chooser.setFileFilter(filter);int state=chooser.showOpenDialog(null);File file=chooser.getSelectedFile();if(file!=null&&state==JFileChooser.APPROVE_OPTION){ wallImageFile=file;maze.setWallImage(wallImageFile);}}else if(e.getSource()==defaultImage){wallImageFile=new File("wall.jpg");roadImageFile=new File("road.jpg");maze.setWallImage(wallImageFile);maze.setRoadImage(roadImageFile);}else if(e.getSource()==renew){init();}else{ JMenuItem item=(JMenuItem)e.getSource();mazeFile=new File(item.getText());init();}}public static void main(String args[]){new MazeWindow();}}//Maze.javaimport java.awt.*;import java.awt.event.*;import javax.swing.*;import java.io.*;public class Maze extends JLayeredPane{File mazeFile;MazePoint[][] mazePoint;WallOrRoad[][] wallOrRoad;PersonInMaze person;HandleMove handleMove;File wallImage,roadImage;int distance=26,m=0,n=0;public Maze(){setLayout(null);wallImage=new File("wall.jpg");roadImage=new File("road.jpg");person=new PersonInMaze();handleMove=new HandleMove();handleMove.initSpendTime();person.addKeyListener(handleMove);setLayer(person,JLayeredPane.DRAG_LAYER);}public void setMazeFile(File f){mazeFile=f;char[][] a;RandomAccessFile in=null;String lineWord=null;try{in=new RandomAccessFile(mazeFile,"r");long length=in.length();long position=0;in.seek(position);while(position<length){String str=in.readLine().trim();if(str.length()>=n)n=str.length();position=in.getFilePointer();m++;}a=new char[m][n];position=0;in.seek(position);m=0;while(position<length){String str=in.readLine();a[m]=str.toCharArray();position=in.getFilePointer();m++;}in.close();wallOrRoad=new WallOrRoad[m][n];for(int i=0;i<m;i++){for(int j=0;j<n;j++){wallOrRoad[i][j]=new WallOrRoad();if(a[i][j]=='1'){wallOrRoad[i][j].setIsWall(true);wallOrRoad[i][j].setWallImage(wallImage);wallOrRoad[i][j].repaint();}else if(a[i][j]=='0'){wallOrRoad[i][j].setIsRoad(true);wallOrRoad[i][j].setRoadImage(roadImage);wallOrRoad[i][j].repaint();}else if(a[i][j]=='*'){wall0rRoad[i][j].setIsEnter(true);wall0rRoad[i][j].setIsRoad(true);wall0rRoad[i][j].repaint();}else if(a[i][j]=='#'){wallOrRoad[i][j].setIsOut(true);wallOrRoad[i][j].setIsRoad(true);wallOrRoad[i][j].repaint();}}}mazePoint=new MazePoint[m][n];int Hspace=distance,Vspace=distance;for(int i=0;i<m;i++){for(int j=0;j<m;j++){mazePoint[i][j]=new MazePoint(Hspace,Vspace);Hspace=Hspace+distance;}Hspace=distance;Vspace=Vspace+distance;}for(int i=0;i<m;i++){for(int j=0;j<n;j++){add(wallOrRoad[i][j]);wallOrRoad[i][j].setSize(distance,distance);wallOrRoad[i][j].setLocation(mazePoint[i][j].getX(),mazePoint[i][j].getY());wallOrRoad[i][j].setAtMazePoint(mazePoint[i][j]);mazePoint[i][j].setWallOrRoad(wallOrRoad[i][j]);mazePoint[i][j].setIsWallOrRoad(true);if(wallOrRoad[i][j].getIsEnter()){person.setAtMazePoint(mazePoint[i][j]);add(person);person.setSize(distance,distance);person.setLocation(mazePoint[i][j].getX(),mazePoint[i][j].getY());person.requestFocus();person.repaint();}}}handleMove.setMazePoint(mazePoint);}catch(IOException exp){JButton mess=new JButton("无效的迷宫文件");add(mess);mess.setBounds(30,30,100,100);mess.setFont(new Font("宋体",Font.BOLD,30));System.out.println(exp+"mess");}}public void setWallImage(File f){wallImage=f;for(int i=0;i<m;i++){for(int j=0;j<n;j++){if(wallOrRoad[i][j].getIsWall())wallOrRoad[i][j].setWallImage(wallImage);wallOrRoad[i][j].repaint();}}}public void setRoadImage(File f){roadImage=f;for(int i=0;i<m;i++){for(int j=0;j<n;j++){if(wallOrRoad[i][j].getIsRoad())wallOrRoad[i][j].setRoadImage(roadImage);wallOrRoad[i][j].repaint();}}}public HandleMove getHandleMove(){return handleMove;}}//WallOrRoad.javaimport javax.swing.*;import java.awt.*;import javax.swing.border.*;import java.io.*;public class WallOrRoad extends JPanel{boolean isRoad,isWall,isEnter,isOut;MazePoint point;File wallImage,roadImage;Toolkit tool;WallOrRoad(){tool=getToolkit();}public void setIsEnter(boolean boo){isEnter=boo;if(isEnter==true)add(new JLabel("入口"));}public boolean getIsEnter(){return isEnter;}public void setIsOut(boolean boo){isOut=boo;if(isOut==true)add(new JLabel("出口"));}public boolean getIsOut(){return isOut;}public void setIsRoad(boolean boo){isRoad=boo;if(isRoad==true){setBorder(null);}}public boolean getIsRoad(){return isRoad;}public void setIsWall(boolean boo){isWall=boo;if(isWall==true)setBorder(new SoftBevelBorder(BevelBorder.RAISED));}public boolean getIsWall(){return isWall;}public void setAtMazePoint(MazePoint p){point=p;}public MazePoint getAtMazePoint(){return point;}public void setWallImage(File f){wallImage=f;}public void setRoadImage(File f){roadImage=f;}public void paintComponent(Graphics g){super.paintComponent(g);int w=getBounds().width;int h=getBounds().height;try{if(isRoad==true){Image image=tool.getImage(roadImage.toURI().toURL());g.drawImage(image,0,0,w,h,this);}else if(isWall==true){Image image=tool.getImage(wallImage.toURI().toURL());g.drawImage(image,0,0,w,h,this);}}catch(Exception exp){}}}//MazePoint.javapublic class MazePoint{int x,y;boolean haveWallOrRoad;WallOrRoad wallOrRoad=null;public MazePoint(int x,int y){this.x=x;this.y=y;}public boolean isHaveWallOrRoad(){return haveWallOrRoad;}public void setIsWallOrRoad(boolean boo){haveWallOrRoad=boo;}public int getX(){return x;}public int getY(){return y;}public boolean equals(MazePoint p){if(p.getX()==this.getX()&&p.getY()==this.getY())return true;elsereturn false;}public void setWallOrRoad(WallOrRoad obj){wallOrRoad=obj;}public WallOrRoad getWallOrRoad(){return wallOrRoad;}}//PersonInMaze.javaimport javax.swing.*;import java.awt.*;public class PersonInMaze extends JTextField{MazePoint point;Toolkit tool;PersonInMaze(){tool=getToolkit();setEditable(false);setBorder(null);setOpaque(false);setToolTipText("单击我,然后按键盘方向键");}public void setAtMazePoint(MazePoint p){point=p;}public MazePoint getAtMazePoint(){return point;}public void paintComponent(Graphics g){super.paintComponent(g);int w=getBounds().width;int h=getBounds().height;Image image=tool.getImage("person.gif");g.drawImage(image,0,0,w,h,this);}}//HandleMove.javaimport java.awt.event.*;import java.awt.*;import javax.swing.*;public class HandleMove extends JPanel implements KeyListener,ActionListener{ MazePoint[][] p;int spendTime=0;javax.swing.Timer recordTime;JTextField showTime;Toolkit tool;HandleMove(){recordTime=new javax.swing.Timer(1000,this);showTime=new JTextField(16);tool=getToolkit();showTime.setEditable(false);showTime.setHorizontalAlignment(JTextField.CENTER);showTime.setFont(new Font("楷体_GB2312",Font.BOLD,16));JLabel hitMess=new JLabel("单击走迷宫者,按键盘方向键",JLabel.CENTER);hitMess.setFont(new Font("楷体_GB2312",Font.BOLD,18));add(hitMess);add(showTime);setBackground(Color.cyan);}public void setMazePoint(MazePoint[][] point){p=point;}public void initSpendTime(){recordTime.stop();spendTime=0;showTime.setText(null);}public void keyPressed(KeyEvent e){recordTime.start();PersonInMaze person=null;person=(PersonInMaze)e.getSource();int m=-1,n=-1;MazePoint startPoint=person.getAtMazePoint();for(int i=0;i<p.length;i++){for(int j=0;j<p[i].length;j++){if(startPoint.equals(p[i][j])){m=i;n=j;break;}}}if(e.getKeyCode()==KeyEvent.VK_UP){int k=Math.max(m-1,0);if(p[k][n].getWakkOrRoad().getIsRoad()){tool.beep();person.setAtMazePoint(p[k][n]);person.setLocation(p[k][n].getX(),p[k][n].getY());}}else if(e.getKeyCode()==KeyEvent.VK_DOWN){int k=Math.min(m+1,p.length-1);if(p[k][n].getWallOrRoad().getIsRoad()){tool.beep();person.setAtMazePoint(p[k][n]);person.setLocation(p[k][n].getX(),p[k][n].getY());}}else if(e.getKeyCode()==KeyEvent.VK_LEFT){int k=Math.max(n-1,0);if(p[m][k].getWallOrRoad().getIsRoad()){tool.beep();person.setAtMazePoint(p[m][k]);person.setLocation(p[m][k].getX(),p[m][k].getY());}}else if(e.getKeyCode()==keyEvent.VK_RIGHT){int k=Math.min(n+1,p[0].length-1);if(p[m][k].getWallOrRoad().getIsRoad()){tool.beep();person.setAtMazePoint(p[m][k]);person.setLocation(p[m][k].getX(),p[m][k].getY());}}}public void actionPerformed(ActionEvent e){spendTime++;showTime.setText("您的用时:"+spendTime+"秒");}public void keyReleased(KeyEvent e){PersonInMaze person=(PersonInMaze)e.getSource();int m=-1,n=-1;MazePoint endPoint=person.getAtMazePoint();if(endPoint.getWallOrRoad().getIsOut()){recordTime.stop();JOptionPane.showMessageDialog(this,"您成功了!","消息框",RMA TION_MESSAGE);}}public void keyTyped(KeyEvent e){}}。
Java课程设计走迷宫
课程设计总结: 通过走迷宫问题, 加深了对算法和 数据结构的理解, 提高了编程能力
感谢您的观看
汇报人:
启发式搜索:根据某种启发式信息 (如估价函数)来选择下一步要访 问的节点,以提高搜索效率。
添加标题
添加标题
添加标题
添加标题
广度优先搜索(BFS):从起点开 始,先访问与起点距离最近的节点, 然后访问与这些节点距离最近的节 点,以此类推。
遗传算法:通过模拟生物进化的过 程,利用选择、交叉、变异等操作, 从一组初始解中逐步演化出最优解。
题
实现方法:使用 队列存储待探索 的节点,每次从 队列中取出一个 节点进行探索, 并将与该节点相 邻且未被探索的
节点加入队列
A*算法
基本思想:使用启发式函数来估计从当前节点到目标节点的代价,选择代价最小的节 点进行扩展。
主要步骤:初始化、选择、扩展、更新。
优点:效率高,适用于大规模问题。
缺点:需要计算启发式函数,可能会导致局部最优解。
03 Java实现
迷宫表示方法
数组表示:使用二维数组表示迷宫,每个元素表示一个单元格
链表表示:使用链表表示迷宫,每个节点表示一个单元格
图表示:使用图来表示迷宫,每个节点表示一个单元格,每条边表示单元 格之间的连接 树表示:使用树来表示迷宫,每个节点表示一个单元格,每条边表示单元 格之间的连接
迷宫求解类设计
动态规划优化步 骤:建立状态转 移方程,计算最 优解,更新状态
动态规划优化效 果:降低时间复 杂度,提高求解 精度,增强程序 稳定性
回溯算法优化
剪枝优化:通过判断当前状态是否满足条件,减少不必要的搜索 记忆化搜索:将已经搜索过的状态记录下来,避免重复搜索 动态规划:将问题分解为更小的子问题,逐步求解 启发式搜索:根据问题的特点,选择合适的搜索策略,提高搜索效率
Java 迷宫主要代码
class Map{int size=10;boolean arrival=false; //判断是否到达出口int [][]sq=new int[size*size][3]; //队列boolean visit[][]=new boolean[size][size]; //标记点是否被访问过int head=0,tail=0;int map[][];void creatMap(){int i,j;map=new int[size][size];for(i=0;i<size;i++)for(j=0;j<size;j++){int ran=(int)(Math.random()*10)+1;if(ran%5==0){ map[i][j]=1;}else { map[i][j]=0;}}for ( i=0; i<size ; i++) //建迷宫{map[0][i] = 1; //左边界map[size-1][i] = 1; //右边界map[i][0] = 1; //上边界map[i][size-1] = 1;//下边界}//设置起点、终点map[0][1] = 2;map[size-1][size-2] = 2;for( i=0;i<size;i++)for( j=0;j<size;j++){if(map[i][j]==1){visit[i][j]=true;}else{ visit[i][j]=false;}}}void showMap(){int i,j;for(i=0;i<size;i++){for(j=0;j<size;j++){if (map[i][j] == 1)System.out.print('■');else if (map[i][j] == 0)System.out.print('◎');elseSystem.out.print('☆');//System.out.print(map[i][j]);}System.out.print('\n');}System.out.print('\n');}void search(){int [][]direct={{-1,0},{0,-1},{1,0},{0,1}}; //点的四个方向sq[0][0]=0;sq[0][1]=1; //将入口添加进队列sq[0][2]=0;while(tail>=head && arrival==false){int x=sq[head][0];int y=sq[head][1];int i=0;while(i<4 && arrival==false){int xx=x+direct[i][0];int yy=y+direct[i][1];if(xx>=0 && xx<size && yy>=0 && yy<size &&visit[xx][yy]==false && map[xx][yy]==0) //可走点{tail++;sq[tail][0]=xx;sq[tail][1]=yy; //加入队列visit[xx][yy]=true; //访问标记sq[tail][2]=head; //记住父节点位置}if(xx>=0 && xx<size && yy>=0 && yy<size &&(xx==size-1)&&(yy==size-2) && map[xx][yy]==2) //判断是否到出口{arrival=true;}else { i++;} //未到出口继续搜索下一个方向}if(arrival==false) head++; //当前节点的可走节点都已入队,继续向下搜索}if(arrival==true) showWay();else {System.out.println("没有可走路径!");}}void showWay(){int x,y,a;a=tail;while(a>0){x=sq[a][0];y=sq[a][1];map[x][y]=3;a=sq[a][2];}showMap();}}public class Start {public static void main(String[]args) {Map m1=new Map();m1.creatMap();m1.showMap();//m1.showWay();m1.search();}}。
java 随机迷宫游戏
随机迷宫游戏 (面向对象)1.实验要求• 设置一个迷宫(如:大小10×10、16×16等) • 迷宫固定一个入口,一个出口 • 设计算法来找出走出迷宫的路线 • 如果迷宫是死胡同,则提示并结束游戏2 设计及实现2.1 设计思想类图:2.2 核心算法public Location goUp() //向上走 { Location nextlocation; nextlocation =new Location();nextlocation.locationi=location.locationi-1; nextlocation.locationj=location.locationj; return nextlocation;}//向下走,向左走,向右走代码省略 public boolean findTheWay(int[][] maze){ Stack seekStack =new Stack(); //探查堆栈while(location.locationi!=9||location.locationj!=8&&0<=location.locationi&&location.locationi<=9&&0<=location.locationj&&location.locationj<=9) //当还没到达出口*/ {if(visted[location.locationi][location.locationj]==false){seekStack.push(location); //位置入栈visted[location.locationi][location.locationj]=true; //该位置已被访问}if(maze[location.locationi][location.locationj+1]==0&&visted[location.locationi][location.locationj+1]==false) //该位置向右可通{maze[location.locationi][location.locationj]=2; //用→表示该位置向右可通location=goRight();//移动到右侧下一位置}else if(maze[location.locationi+1][location.locationj]== 0&&visted[location.locationi+1][location.locationj]==false){maze[location.locationi][location.locationj]=3; //用↓表示该处向下可通location=goDown(); //移动到下一位置}else if(maze[location.locationi][location.locationj-1]== 0&&visted[location.locationi][location.locationj-1]==false) //表示改点可通且未被访问{maze[location.locationi][location.locationj]=4; //用←表示向左可通location=goLeft(); //向左移动到下一位置}else if (location.locationi!=0&&maze[location.locationi-1][location.locationj]== 0&&visted[location.locationi-1][location.locationj]==false) //向上可通并且未被访问{maze[location.locationi][location.locationj]=5; //用↑表示向上可通location=goUp(); //移动到上一个相邻的位置}else //该位置不通{Location die;die=(Location)seekStack.pop(); //将该位置从堆栈中退出maze[die.locationi][die.locationj]=0;if (seekStack.empty()==true){break;}location=(Location) seekStack.peek();}}if (location.locationi==9&&location.locationj==8){return true;}else{System.out.println("没有出路,游戏结束!");return false;}}3 心得及思考如果说第一个猜数游戏是初试面向对象思想编程的话,这个走迷宫小游戏就是对面向对象编程的进一步体会。
迷宫游戏实习报告(java)(参考资料)
2009-2010-2课程实验报告高级程序设计(JA V A)专业班级姓名学号实验名称:迷宫实验1 实验要求I.用面向对象的思想编写扩展的“猜数字”游戏。
II.走迷宫游戏:i设置一个迷宫(如:大小10×10、16×16等)ii迷宫固定一个入口,一个出口iii设计算法来找出走出迷宫的路线iv如果迷宫是死胡同,则提示并结束游戏2 设计及实现2.1设计思路类图:PlaceInt place[][];Int n;Place()makeplace()printplace()siteInt sitex;Int sitey;FindWaysite site;Point point;boolean visted[][]; Place pl=new Place(); FindWay() findTheWay(int[][] maze)Pointgoup()godown()goright()goleft()程序流程图:If input 3 if input 2YES NO2 or3 Have way ?Make the mapStartFind wayInput the numberOutput “设置迷宫大小”Input the style of maze Output“输入整数 2 显示迷宫答案; 输入整数 3 结束游戏 请选择操作序号:”output the way of the maze Output “没有出路” Output“用户终止了程序”End2.2 核心算法//向上走site goup(site s){s.sitex=s.sitex;s.sitey=s.sitey-1;return s;}//向下走site godown(site s){s.sitex=s.sitex;s.sitey=s.sitey+1;return s;}//向右走site goright(site s){s.sitex=s.sitex+1;s.sitey=s.sitey;return s;}//向左走site goleft(site s){s.sitex=s.sitex-1;s.sitey=s.sitey;return s;}//寻找迷宫路径boolean findTheWay(int[][] maze){Stack seekStack =new Stack(); //路径储存堆栈while(site.sitey!=pl.n-1||site.sitex!=pl.n-2&&0<=site.sitey&&site.sitey<pl.n&&0<=site.sitex&&site.sitex<pl.n) //还没有到达出口时{if(visted[site.sitey][site.sitex]==false){seekStack.push(site); //位置入栈visted[site.sitey][site.sitex]=true; //该位置已被访问}if(maze[site.sitey][site.sitex+1]== 0&&visted[site.sitey][site.sitex+1]==false)//该位置往右可通且未被访问{maze[site.sitey][site.sitex]=2; //用→表示该位置向右可通site=point.goright(site); //移动到右侧下一位置continue;}else if(maze[site.sitey+1][site.sitex]== 0&&visted[site.sitey+1][site.sitex]==false)//该位置往下可通且未被访问{maze[site.sitey][site.sitex]=3; //用↓表示该位置向下可通site=point.godown(site); //向下移动一位置continue;}else if(maze[site.sitey][site.sitex-1]== 0&&visted[site.sitey][site.sitex-1]==false) //该位置往左可通且未被访问{maze[site.sitey][site.sitex]=4; //用←表示该位置向左可通site=point.goleft(site); //向左移动一个位置continue;}elseif(site.sitey!=0&&maze[site.sitey-1][site.sitex]== 0&&visted[site.sitey-1][site.sitex]==false)//该位置往上可通且未被访问{maze[site.sitey][site.sitex]=5; // 用↑表示该位置向上可通。
迷宫小游戏java课程设计
迷宫小游戏java课程设计一、课程目标知识目标:1. 学生将掌握Java基本语法和编程结构,包括变量声明、数据类型、运算符、控制结构等。
2. 学生能够理解面向对象编程的基本概念,如类、对象、封装、继承和多态。
3. 学生将学习使用Java中的二维数组来创建和表示迷宫。
技能目标:1. 学生将培养问题解决能力,通过编写Java程序解决迷宫路径查找问题。
2. 学生将学会使用Java的图形用户界面(GUI)工具包来设计并实现迷宫游戏的用户界面。
3. 学生将掌握调试和测试Java程序的方法,确保迷宫游戏的正确性和稳定性。
情感态度价值观目标:1. 学生将增强逻辑思维和创新能力,通过编程解决实际问题,体会编程的乐趣和挑战。
2. 学生将培养团队协作精神,通过小组合作共同完成迷宫游戏的开发和优化。
3. 学生将树立正确的价值观,认识到编程在现实生活中的应用和重要性,激发对计算机科学的兴趣。
课程性质:本课程为实践性较强的学科项目,结合Java编程知识与游戏设计,提高学生的编程能力和创新思维。
学生特点:考虑到学生已具备一定的Java基础,课程将注重提升学生的编程实践能力和问题解决能力。
教学要求:课程需注重理论与实践相结合,强调学生的动手实践和团队合作,确保学生能够掌握Java编程的核心知识,并应用于实际项目开发。
通过具体的学习成果分解,教师可评估学生对知识技能的掌握情况,以及情感态度价值观的培育效果。
二、教学内容1. Java基本语法复习:变量声明、数据类型、运算符、控制结构(条件语句、循环语句)。
2. 面向对象编程基础:类与对象、构造方法、封装、继承和多态。
3. 二维数组:二维数组的声明与使用,迷宫地图的表示方法。
4. 图形用户界面(GUI):使用Java Swing库设计迷宫游戏界面,如窗口、按钮、面板等。
5. 迷宫路径查找算法:深度优先搜索(DFS)、广度优先搜索(BFS)等。
6. 程序调试与测试:使用调试工具,编写测试用例,保证程序的正确性。
java课设走迷宫(含代码)
目录1.设计目的1.1课程设计的目的2.总体设计2.1设计思路2.2设计方法3.关键技术4.程序流程5.主要源代码6. 运行结果及结论7.参考文献1.设计目的1.1课程设计的目的随着科技进步,时代发展,计算机走进了大家的生活。
计算机程序强大的功能为使用者提供服务,编程语言也变得越来越流行。
Java语言是当今流行的网络编程语言,它具有面向对象、跨平台、分布应用等特点。
面向对象的开发方法是当今世界最流行的开发方法,它不仅具有更贴近自然的语义,而且有利于软件的维护和继承。
为了进一步巩固课堂上所学到的知识,深刻把握Java语言的重要概念及其面向对象的特性,熟练应用面向对象的思想和设计方法解决实际问题的能力,也是为了增加同学们娱乐游戏选择而开发了一个适合学生的,能提升思考力的迷宫冒险游戏,这既锻炼了动手能力,还能进行消遣娱乐,可谓一举两得。
2.总体设计2.1设计思路根据对游戏系统进行的需求分析,本系统将分为6个模块:分别是迷宫主界面模块、记时设计模块、迷宫设计模块、道路和障碍设计模块、动漫冒险者设计模块、出入口设计模块。
实现的功能有:(1)迷宫的选择玩家可以根据自身需求来进行选择简单迷宫、中等迷宫、难度迷宫三类中选择一类迷宫进行游戏。
(2)选择道路和障碍的图像玩家可以根据个人喜好对迷宫中的道路和障碍的图片进行选择,但是图片的格式有规定,必须是“jpg”或“gif”格式的。
(3)游戏记时当玩家控制迷宫中的动漫人物进行游戏时,计时器就开始进行记时,直到动漫人物到达出口时,记时结束,并在屏幕上显示游戏用时。
(4)开始游戏玩家将鼠标移动至迷宫中的动漫冒险者,即可看到“单击我然后按键盘方向键”,单击后,游戏开始。
玩家即可通过键盘上的方向键进行游戏。
(5)游戏结束玩家控制动漫冒险者移动至迷宫地图的出口处时,游戏的计时器停止计时,并弹出信息框“恭喜您通关了”,游戏结束。
(6)冒险脚步声玩家单击动漫冒险者后,便可以用键盘方向键进行控制。
java课程设计走迷宫报告
java课程设计走迷宫报告一、教学目标本节课的教学目标是让学生掌握Java编程的基本语法和流程控制,学会使用Java编写简单的程序,培养学生的编程思维和解决问题的能力。
具体包括以下三个方面的目标:1.知识目标:使学生了解Java编程语言的基本语法、数据类型、变量、运算符、流程控制语句等基本概念。
2.技能目标:培养学生能够使用Java编写简单的程序,如计算器、猜数字游戏等,提高学生的编程实践能力。
3.情感态度价值观目标:培养学生对编程的兴趣,激发学生的创新意识,培养学生的团队合作精神和自主学习能力。
二、教学内容本节课的教学内容主要包括以下几个部分:1.Java编程语言的基本语法和数据类型。
2.变量的声明、赋值和类型转换。
3.运算符的使用和运算规则。
4.流程控制语句(条件语句、循环语句)的编写和运用。
5.实例分析:编写简单的Java程序,如计算器、猜数字游戏等。
三、教学方法为了达到本节课的教学目标,我们将采用以下几种教学方法:1.讲授法:讲解Java编程语言的基本语法、数据类型、变量、运算符、流程控制语句等概念。
2.案例分析法:分析实例程序,使学生了解如何使用Java编写简单的程序。
3.实验法:让学生动手编写Java程序,培养学生的编程实践能力。
4.讨论法:学生进行小组讨论,分享学习心得,提高学生的团队合作精神。
四、教学资源为了支持本节课的教学内容和教学方法的实施,我们将准备以下教学资源:1.教材:选用权威、实用的Java编程教材,为学生提供系统的学习资料。
2.参考书:提供相关的Java编程参考书籍,丰富学生的知识体系。
3.多媒体资料:制作精美的PPT,直观地展示Java编程的概念和实例。
4.实验设备:为学生提供电脑、编程环境等实验设备,方便学生进行编程实践。
五、教学评估本节课的教学评估将采用多元化的评估方式,以全面、客观、公正地评价学生的学习成果。
具体包括以下几个方面:1.平时表现:评估学生在课堂上的参与度、提问回答、小组讨论等,以考察学生的学习态度和积极性。
迷宫问题——数据结构课程设计迷宫问题完整版(含源代码)
*******************实践教学*******************兰州理工大学计算机与通信学院2012年春季学期算法与数据结构课程设计题目:迷宫问题专业班级:计算机科学与技术一班*名:***学号:********指导教师:**成绩:目录摘要 (3)前言 (4)正文 (5)一、采用c++语言定义相关的数据类型 (5)二、各模块的伪码算法 (6)三、函数的调用关系图 (10)四、调试分析 (11)五、测试结果 (12)1、开始界面 (12)2、自动生成迷宫运行情况 (12)3、键盘输入迷宫运行情况 (14)总结 (16)致谢 (17)参考文献 (18)附录 (19)源程序(带注释) (19)摘要本程序主要是对任意给定的迷宫,求出一条从入口到出口的通路,或得出没有通路的结论。
使我们基本掌握线性表及栈上基本运算的实现,进一步理解和熟练掌握课本中所学的各种数据结构,学会如何把学到的知识用于解决实际问题,培养我们的动手能力。
1、生成迷宫:根据提示输入数据,然后生成一个8行8列的迷宫。
2、探索迷宫路径:由输入的入口位置开始,对相邻的(上,下,左,右)四个方向的方块进行探索,若可通则“纳入路径”,否则顺着“来向”退到“前一通道块”,朝着“来向”之外的其它方向继续探索。
3、保存迷宫路径:若探索到出口则把探索到的路径压入另一个栈中,并最后弹出路径坐标,输出在屏幕上。
关键字:栈,栈的存储结构,出栈与入栈求迷宫中从入口到出口的所有路径是一个经典的程序设计问题。
由于计算机解迷宫时,通常用的是“穷举求解”的方法,即从入口出发,顺某一方向向前探索,若能走通,则继续往前走;否则沿原路退回,换一个方向再继续探索,直至所有可能的通路都探索到为止。
为了保证在任何位置上都能沿原路退回,显然需要用一个后进先出的结构来保存从入口到当前位置的路径。
因此,在求迷宫通路的算法中应用“栈”也就是自然而然的事。
迷宫问题要求,所求路径必须是简单路径,即在求得路径上不能同时重复出现同一通道。
Java迷宫代码,广度优先遍历,最短路径
Java迷宫代码,⼴度优先遍历,最短路径使⽤⼀个队列,采⽤层层扩张的⽅式,寻找迷宫最优的路径信息,再⽤⼀个迷宫节点数组记录⾏⾛信息⽅向常量定义:public interface Constant {// 右⽅向int RIGHT = 0;// 下⽅向int DOWN = 1;// 左⽅向int LEFT = 2;// 上⽅向int UP = 3;}所⽤到的链式队列定义(jdk⾃带的队列或集合也可以实现此功能)public class LinkQueue<T> {// 指向头节点(队头)private Entry<T> front;// 指向尾节点(队尾)private Entry<T> rear;// 记录队列节点的个数private int count;/*** 初始化,front和rear都指向头节点*/public LinkQueue(){this.front = this.rear = new Entry<>(null, null);}/*** ⼊队操作* @param val*/public void offer(T val){Entry<T> node = new Entry<>(val, null);this.rear.next = node;this.rear = node;this.count++;}/*** 出队操作* @return*/public T poll(){T val = null;if(this.front.next != null){val = this.front.next.data;this.front.next = this.front.next.next;// 删除队列最后⼀个元素,要把rear指向front,队列才能判空if(this.front.next == null){this.rear = this.front;}this.count--;}return val;}public T peek(){T val = null;if(this.front.next != null){val = this.front.next.data;}return val;}/*** 判断队列空* @return*/public boolean isEmpty(){return this.front == this.rear;/*** 返回队列元素的个数* @return*/public int size(){return this.count;}/*** 节点类型定义* @param <T>*/static class Entry<T>{T data;Entry<T> next;public Entry(T data, Entry<T> next) {this.data = data;this.next = next;}}}源代码/*** 描述: 定义迷宫节点类型*/private static class MazeNode {// 节点的值int val;// 节点的x和y坐标int x;int y;// 节点四个⽅向的⾏⾛状态,true表⽰可以⾛,false表⽰不能⾛boolean[] state;/*** 迷宫路径初始化* @param data* @param i* @param j*/public MazeNode(int data, int i, int j){this.state = new boolean[4];this.val = data;this.x = i;this.y = j;}}源代码/*** 描述: 迷宫的类型定义** @Author shilei* @Date 2019/5/18*/public class Maze {// 迷宫所有的路径存储在⼆维数组当中private MazeNode[][] maze;// 存储迷宫路径节点的队列结构,采⽤层层扩张的⽅式,寻找迷宫最优的路径信息private LinkQueue<MazeNode> queue;// 记录迷宫路径节点的⾏⾛信息private MazeNode[] pathrecord;// 迷宫的⾏数private int row;// 迷宫的列数private int col;/*** 迷宫初始化* @param row* @param col*/public Maze(int row, int col) {this.row = row;this.col = col;this.maze = new MazeNode[row][col];this.queue=new LinkQueue<>();this.pathrecord = new MazeNode[row*col];/*** 初始化指定位置的迷宫节点* @param data* @param i* @param j*/public void initMazeNode(int data, int i, int j) {this.maze[i][j] = new MazeNode(data, i, j);}/*** 修改迷宫所有节点四个⽅向的⾏⾛状态信息*/public void initMazeNodePathState() {for (int i=0;i<row;i++){for (int j=0;j<col;j++){if(j+1<col&&maze[i][j+1].val==0){maze[i][j].state[Constant.RIGHT]=true; }if(i+1<row&&maze[i+1][j].val==0){maze[i][j].state[Constant.DOWN]=true; }if(j>0&&maze[i][j-1].val==0){maze[i][j].state[Constant.LEFT]=true;}if(i>0&&maze[i-1][j].val==0){maze[i][j].state[Constant.UP]=true;}}}}/*** 寻找迷宫路径*/public void findMazePath() {if (maze[0][0].val != 0) {return;}queue.offer(maze[0][0]);while(!queue.isEmpty()){MazeNode top = queue.peek();int x = top.x;int y = top.y;if(x == row-1 && y == col-1){return;}// 往右⽅向⾛if(maze[x][y].state[Constant.RIGHT]){maze[x][y].state[Constant.RIGHT] = false; maze[x][y+1].state[Constant.LEFT] = false; queue.offer(maze[x][y+1]);pathrecord[x*col+y+1] = maze[x][y];}// 往下⽅向⾛if(maze[x][y].state[Constant.DOWN]){maze[x][y].state[Constant.DOWN] = false; maze[x+1][y].state[Constant.UP] = false; queue.offer(maze[x+1][y]);pathrecord[(x+1)*col+y] = maze[x][y];}// 往左⽅向⾛if(maze[x][y].state[Constant.LEFT]){maze[x][y].state[Constant.LEFT] = false;maze[x][y-1].state[Constant.RIGHT] = false; queue.offer(maze[x][y-1]);pathrecord[x*col+y-1] = maze[x][y];}// 往上⽅向⾛if(maze[x][y].state[Constant.UP]){maze[x][y].state[Constant.UP] = false;maze[x-1][y].state[Constant.DOWN] = false; queue.offer(maze[x-1][y]);pathrecord[(x-1)*col+y] = maze[x][y];}queue.poll();}/*** 打印迷宫路径搜索的结果*/public void showMazePath(){if(pathrecord[row*col-1] == null){System.out.println("迷宫不存在有效路径");} else {int x = row-1;int y = col-1;for(;;){maze[x][y].val = '*';MazeNode node = pathrecord[x*col+y];if(node == null){break;}x = node.x;y = node.y;}for (int i = 0; i < row; i++) {for (int j = 0; j < col; j++) {if(maze[i][j].val == '*'){System.out.print('*' + " ");} else {System.out.print(maze[i][j].val + " ");}}System.out.println();}}}/*** 描述: 定义迷宫节点类型*/private static class MazeNode {// 节点的值int val;// 节点的x和y坐标int x;int y;// 节点四个⽅向的⾏⾛状态,true表⽰可以⾛,false表⽰不能⾛boolean[] state;/*** 迷宫路径初始化* @param data* @param i* @param j*/public MazeNode(int data, int i, int j){this.state = new boolean[4];this.val = data;this.x = i;this.y = j;}}}View Code测试类public class Main {public static void main(String[] args) {Scanner in = new Scanner(System.in);System.out.print("请输⼊迷宫的⾏列数:");int row, col, data;row = in.nextInt();col = in.nextInt();Maze maze = new Maze(row, col);System.out.println("请输⼊迷宫路径");for (int i = 0; i < row; i++) {for (int j = 0; j < col; j++) {data = in.nextInt();maze.initMazeNode(data, i, j);}}maze.initMazeNodePathState();// 寻找迷宫路径maze.findMazePath();// 打印迷宫路径搜索的结果maze.showMazePath();}}结果:请输⼊迷宫的⾏列数:4 5请输⼊迷宫路径0 1 0 0 00 0 0 1 01 0 1 1 00 0 0 0 0* 1 0 0 0* * 0 1 01 * 1 1 00 * * * *。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
目录1.设计目的课程设计的目的2.总体设计设计思路设计方法3.关键技术4.程序流程5.主要源代码6. 运行结果及结论7. 参考文献1.设计目的课程设计的目的随着科技进步,时代发展,计算机走进了大家的生活。
计算机程序强大的功能为使用者提供服务,编程语言也变得越来越流行。
Java 语言是当今流行的网络编程语言,它具有面向对象、跨平台、分布应用等特点。
面向对象的开发方法是当今世界最流行的开发方法,它不仅具有更贴近自然的语义,而且有利于软件的维护和继承。
为了进一步巩固课堂上所学到的知识,深刻把握 Java 语言的重要概念及其面向对象的特性,熟练应用面向对象的思想和设计方法解决实际问题的能力,也是为了增加同学们娱乐游戏选择而开发了一个适合学生的,能提升思考力的迷宫冒险游戏,这既锻炼了动手能力,还能进行消遣娱乐,可谓一举两得。
2.总体设计设计思路根据对游戏系统进行的需求分析,本系统将分为 6 个模块:分别是迷宫主界面模块、记时设计模块、迷宫设计模块、道路和障碍设计模块、动漫冒险者设计模块、出入口设计模块。
实现的功能有:(1)迷宫的选择玩家可以根据自身需求来进行选择简单迷宫、中等迷宫、难度迷宫三类中选择一类迷宫进行游戏。
(2)选择道路和障碍的图像玩家可以根据个人喜好对迷宫中的道路和障碍的图片进行选择,但是图片的格式有规定,必须是“ jpg ”或“ gif ”格式的。
(3)游戏记时当玩家控制迷宫中的动漫人物进行游戏时,计时器就开始进行记时,直到动漫人物到达出口时,记时结束,并在屏幕上显示游戏用时。
(4)开始游戏玩家将鼠标移动至迷宫中的动漫冒险者,即可看到“单击我然后按键盘方向键”,单击后,游戏开始。
玩家即可通过键盘上的方向键进行游戏。
(5)游戏结束玩家控制动漫冒险者移动至迷宫地图的出口处时,游戏的计时器停止计时,并弹出信息框“恭喜您通关了” ,游戏结束(6)冒险脚步声玩家单击动漫冒险者后,便可以用键盘方向键进行控制。
动漫冒险者每移动一步便会发出一声“嘟”的响声。
(7)重新开始玩家可以根据个人对自己通关时间长短的满意程度选择再次挑战,单击“重新开始”即可。
(8)计时界面位置利用边界式布局管理器BorderLayout将计时界面置于上方。
(9)再次挑战界面位置利用边界式布局管理器BorderLayout将再次挑战界面置于下方。
图J迷宫冒险系统6大模块图设计方法(1)迷宫冒险系统主界面模块迷宫冒险系统主界面模块包括和两个文件。
MazeWi ndow是迷宫冒险系统的主运行类,其中有运行整个程序的main方法,该文件生成了 Maze类的一个实例,从而生成了迷宫冒险系统的界面。
MazeWindoW^继承自JFrame 类,以ActionListener 为接口实现了事件侦听的接口,它有一个不带参数的构造方法MazeWindow (),用来生成MazeWindoW勺实例。
MazeWindow类将所有的功能集中到菜单栏中,并通过调用其他模块来实现迷宫冒险系统的各个功能。
(2)记时设计模块记时设计模块主要由共1个文件组成。
HandleMove类继承自JPanel类,以ActionListener 为接口实现事件的侦听的接口。
该模块利用了一个2维数组来进行实现,并对计时显示的字体、背景色、显示位置进行设计。
该模块定义了一个无参返回值的变量 SpendTime利用SpendTime这个变量来对记时的开始触发源和记时的结束触发源。
动漫冒险—记时开始动漫冒险记时结束图计时流程图(3)迷宫设计模块迷宫设计模块主要由 2个2维数组组成,它们组成了主界面中“选择迷宫”菜单的内容,其中包括简单迷宫、中等迷宫、难度迷宫三大类。
该模块的类继承自JLayeredPane 类,主要通过 2 个 2 维数组来实现。
并且对迷宫中的道路和障碍的插入图片格式进行了要求。
该模块使用 try 和 catch 来捕获和处理异常。
当迷宫地图不可用时则弹出对话框“无效的迷宫文件” 。
(4)道路和障碍设计模块系统道路和障碍设计模块主要由这个文件组成,这个文件组成了主界面中的迷宫地图中的道路和障碍的内容。
(5)动漫冒险者设计模块动漫冒险者设计模块主要是对迷宫地图中处于入口处的动漫冒险玩家进行设计。
该模块利用语句使鼠标箭头移动到动漫冒险者上时显示文字“单击我, 然后按键盘方向键” ,并为冒险者的图片格式、长度、宽带、初始位置等等进行进一步的设计,让动漫冒险者更加生动。
(6)出入口设计模块出入口设计模块主要是定义了出口与入口以及当动漫冒险者处于这两个位置时的状态和事件的链接。
3.关键技术在设计走迷宫小游戏时,编写了 6个JAVA源文件:、、、、4.程序流程图迷宫游戏流程图5.主要源代码import .*;import .*;import .*;import class MazeWindow extends JFrame ActionListener{implements Maze maze;JMenuBar bar;JMenu menuChoice,menuImage;JMenuItem wallImage,roadImage,defaultImage;File mazeFile,wallImageFile,roadImageFile;JButton renew;MazeWindow(){wallImageFile=new File("");roadImageFile=new File("");bar=new JMenuBar();menuChoice=new JMenu(" 选择迷宫 "); File dir=new File(".");File file[]=(new FilenameFilter(){publicaccept(File dir,String name){return ("maze");}});for(int i=0;i< ;i++){ JMenuItemJMenuItem(file[i].getName());(this);(item);}mazeFile=new File(file[0].getName());init();boolean item=newmenuImage=new JMenu(" 选择墙和路的图像 (JPG,GIF)");wallImage=new JMenuItem("roadImage=new JMenuItem("defaultImage=new JMenuItem("(wallImage);(roadImage);(defaultImage);(menuChoice);(menuImage); setJMenuBar(bar);(this);(this); (this);renew=new JButton("重新开始 ");(this);墙的图像 "); 路的图像 ");墙和路的默认图像 ");add(renew,;setVisible(true); setBounds(60,60,510,480); validate();setDefaultCloseOperation;}public void init(){if(maze!=null){remove(maze); remove());}maze=new Maze();(wallImageFile);(roadImageFile);add(maze,;add(),;validate();}public void actionPerformed(ActionEvent e){if()==roadImage){JFileChooser chooser=new JFileChooser();FileNameExtensionFilter filternew FileNameExtensionFilter("JPG & GIF Images", "jpg", "gif");(filter);int state=(null);File file=();if(file!=null&&state=={roadImageFile=file;} }(roadImageFile); }}else if()==wallImage){JFileChooser chooser=new JFileChooser();FileNameExtensionFilter filterFileNameExtensionFilter("JPG & GIF Images", "jpg", "gif");(filter);int state=(null);File file=();if(file!=null&&state=={wallImageFile=file;(wallImageFile);newelse if()==defaultImage){ wallImageFile=new File(""); roadImageFile=new File(""); (wallImageFile); (roadImageFile);}else if()==renew){init();}else{JMenuItem item=(JMenuItem)();mazeFile=new File());init();}}public static void main(String args[]){new MazeWindow();}}6. 运行结果及结论在开发环境为 JCreator 的电脑上编写 java 程序,利用 java 程序实现迷宫冒险的运作。
程序包含、、、、、六个java源文件。
其中MazeWindow为程序的主类,贯穿始终,通过调用其他模块功能来实现整个迷宫冒险小游戏的全部功能,是游戏安全运行。
程序进过检查修改无误后运行得到如下运行结果。
运行结果示意图7.参考文献 1】董小园Java面向对象程序设计清华大学出版社,2011年6月第1版2】刘升华Java从入门到实践[M].北京:清华大学出版社20093】陈国君Java2设计基础[M].北京:清华大学出版社2009 4】朱喜福Java程序设计[M].北京:人民邮电出版社20055】饶一梅Java语言程序设计[M].北京:人民邮电出版社2009成绩评定表语组长签字:成绩课程设计任务书实践教学要求与任务。