java迷宫小游戏源代码

合集下载

一个关於迷宫算法的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创建迷宫游戏

使用Java创建迷宫游戏

使用Java创建迷宫游戏-一个实战教程迷宫游戏是一种有趣的小型游戏,玩家需要在迷宫中找到通往终点的路径。

在这个实战博客中,我们将创建一个简单的Java迷宫游戏,演示如何构建一个基本的游戏应用。

我们将使用Java编程语言和一些基本的图形库来完成这个项目。

以下是本实战博客的主要内容:项目概述准备工作创建游戏窗口生成迷宫游戏逻辑绘制迷宫和角色用户输入和游戏循环运行和测试游戏总结让我们开始吧!1. 项目概述在本项目中,我们将创建一个简单的Java迷宫游戏,它包括以下主要功能:随机生成一个迷宫地图。

在地图上绘制一个玩家角色,玩家可以通过键盘控制角色移动。

玩家的目标是找到迷宫的出口。

游戏会提供胜利和失败的反馈。

我们将使用Java编程语言和以下开发库来构建迷宫游戏:Java标准库:用于基本的Java编程。

Swing:用于创建图形用户界面(GUI)的Java库。

AWT(抽象窗口工具集):用于创建游戏窗口和绘制图形。

2. 准备工作在开始之前,确保您的开发环境已设置好。

我们将使用Java标准库、Swing和AWT来创建游戏,不需要额外的库或工具。

3. 创建游戏窗口首先,我们需要创建游戏的窗口。

我们将使用Swing库来创建一个简单的窗口,用于显示游戏画面。

javaCopy codeimport javax.swing.*;import java.awt.*;public class MazeGame extends JFrame {private static final int WIDTH = 800;private static final int HEIGHT = 600;public MazeGame() {setTitle("迷宫游戏");setSize(WIDTH, HEIGHT);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setLocationRelativeTo(null);setResizable(false);MazePanel mazePanel = new MazePanel();add(mazePanel);setVisible(true);}public static void main(String[] args) {SwingUtilities.invokeLater(() -> new MazeGame());}}在上述代码中,我们创建了一个MazeGame类,继承自JFrame,用于创建游戏窗口。

java迷宫小游戏源代码

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,1,0,1, 1,0,1,0,1,1,1,0,1,0,1,1,1,0,1,0,1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,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•删除 |•。

java小游戏源代码

java小游戏源代码

j a v a小游戏源代码 Document number:NOCG-YUNOO-BUYTT-UU986-1986UTJava小游戏第一个Java文件:import class GameA_B {public static void main(String[] args) {Scanner reader=new Scanner;int area;"Game Start…………Please enter the area:(1-9)" +'\n'+"1,2,3 means easy"+'\n'+"4,5,6 means middle"+'\n'+"7,8,9 means hard"+'\n'+"Please choose:");area=();switch((area-1)/3){case 0:"You choose easy! ");break;case 1:"You choose middle! ");break;case 2:"You choose hard! ");break;}"Good Luck!");GameProcess game1=new GameProcess(area);();}}第二个Java文件:import class GameProcess {int area,i,arrcount,right,midright,t;int base[]=new int[arrcount],userNum[]=newint[area],sysNum[]=new int[area];Random random=new Random();Scanner reader=new Scanner;GameProcess(int a){area=a;arrcount=10;right=0;midright=0;t=0;base=new int[arrcount];userNum=new int[area];sysNum=new int[area];for(int i=0;i<arrcount;i++){base[i]=i;// }}void process(){rand();while(right!=area){scanf();compare();print();check();}}void rand(){for(i=0;i<area;i++){t=(arrcount);//sysNum[i]=base[t];delarr(t);}}void delarr(int t){for(int j=t;j<arrcount-1;j++)base[j]=base[j+1];arrcount--;}void scanf(){"The system number has created!"+"\n"+"Please enter "+area+" Numbers");for(int i=0;i<area;i++){userNum[i]=();}}void check(){if(right==area)"You win…………!");}boolean check(int i){return true;}void compare(){int i=0,j=0;right=midright=0;for(i=0;i<area;i++){for(j=0;j<area;j++){if(userNum[i]==sysNum[j]){if(i==j)right++;elsemidright++;}}}}void print(){" A "+right+" B "+midright);}}。

求解迷宫全部路径的Java源程序

求解迷宫全部路径的Java源程序
fd.setVisible(true);
String fpath=fd.getDirectory();
String fname=fd.getFile();
String si=fpath+fname;
f.dispose();
try{
RandomAccessFile rwFile=new RandomAccessFile(si,"rw");
{
System.out.print("("+r+","+c+","+di+")"+" ");
}
}//end class StackLink
////////////////////////////////////
class SingleLinkListForStack
{
public StackLink first;
*/
int a[][]={{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,1,1,0,0,1,0},
{0,0,0,1,0,0,0,0},
m=4;n=9;startrow=1;startcol=1;endrow=4;endcol=9;
*/
Frame f=new Frame("FileDialog");
f.setSize(600,500);
FileDialog fd=new FileDialog(f,"File Dialog For Save",FileDialog.SAVE);

用Java编写动物迷宫游戏

用Java编写动物迷宫游戏

用Java编写动物迷宫游戏分第一部分:游戏简介邮递员小白兔需要走迷宫送四封信选一幅迷宫图在这幅迷宫上有五个小房子,小兔子要把信送到五个小房子中另外还需要一个控制小兔子方向的遥控器,小兔子可以向东西南北四个方向移动算法:1、首先在迷宫上画出方格,在游戏中用变量fangge表示用方向箭头控制小白兔从一个方格移动到另一个方格上,一直到送完信为止其中每个方格可在游戏中画一个矩形框,可显示小白兔的位置,移动位置后先擦去原来画的矩形,然后画一个新的矩形,在每个方格上可显示出可以移动的方向,点示图中的方向键,可以移动到下一个方格的位置,现在我们要在每个方格里放一种动物,而且我们还要把这个迷宫的图片去掉,注意:我们用Java编写游戏,不是用VB编写游戏,我们这个游戏中没有任何图片,这是一个文字游戏。

方格编号动物名称可以移动的方向1 小熊猫1号向东走可到2号方格2 大象2号向东=7;向西=1;向南=33 鳄鱼东南西北4 大熊猫西南北5 梅花鹿南第一个送信的房子6 黑熊西北7 老虎东西8 狮子东9 花豹东西南10 骆驼东西南看到这么多的动物,很容易让人联想到动物园里的动物吧!游戏要求走完所有的方格,看完所有的动物就算打完这个游戏了!第二部分:编写动物迷宫游戏游戏变量(一共有三个全局变量):fangge设为整数值,代表以上表格中的方格编号还有四个枚举量,为东西南北,在代码中用NORTH SOUTH EAST WEST 表示Direction设为字符串,代表东西南北四个方向Exits(3) 代表一个数组,初始化为0,如果移动到一个新的方格,则Exits(Direction)的值为新的方格编号,如果值为零,则表示不可以朝这个方向移动这个游戏的名称为Migong,出现在代码public class中。

第三部分:游戏代码import java.util.Scanner;public class Migong {public static void main(String[] args) {Scanner in=new Scanner(System.in);System.out.println("-------动物迷宫游戏--------");System.out.println("请按方向行走 (1.东 2.西 3.南 4.北)");int person=in.nextInt();Int fangge=1int[] exits;exits=new int[4];exits[0]=0;exits[1]=0;exits[2]=0;exits[3]=0;int i;i=person-1;boolean a=exits[i]==0;boolean b=exits[i]!=0;if (a){System.out.println("你不能往这个方向走");}else{fangge=exits[i];}switch(fangge){case 1:exits[0]=2;exits[1]=0;exits[2]=0;exits[3]=0;System.out.println("你看到的是小熊猫,可以向东走");break;case 2:exits[0]=7;exits[1]=1;exits[2]=3;exits[3]=0;System.out.println("你看到的是大象,可以向东、向南、向西走"); break;case 3:exits[0]=4;exits[1]=8;exits[2]=2;exits[3]=10;System.out.println("你看到的是鳄鱼,可以向东、向西、向南、向北走");break;case 4:exits[0]=0;exits[1]=3;exits[2]=6;exits[3]=5;System.out.println("你看到的是大熊猫,可以向西、向南、向北走");break;case 5:exits[0]=0;exits[1]=0;exits[2]=4;exits[3]=0;System.out.println("你看到的是梅花鹿,可以向南走");break;case 6:exits[0]=0;exits[1]=9;exits[2]=0;exits[3]=4;System.out.println("你看到的是黑熊,可以向西、向北走");break;}}}注:本游戏代码只编写了前6个方格,为了简单一些,更容易看懂。

java解决迷宫问题,gui界面,非常实用

java解决迷宫问题,gui界面,非常实用

package com.mingrui.recursion;import java.awt.event.*;import java.awt.*;import javax.swing.*;public class Test19_8 extends JFrame{private Cell[][] board=new Cell[8][8];private JButton jbFindPath=new JButton("找到出路");private JButton jbClearPant=new JButton("清除路线");private JPanel jpUp,jpBut;Test19_8(){setSize(345,256);setResizable(false);setDefaultCloseOperation(3);setLocationRelativeTo(null);jpUp=new JPanel();jpBut=new JPanel();jpUp.setLayout(new GridLayout(8,8,2,2));for(int i=0;i<8;i++){for(int j=0;j<8;j++){board[i][j]=new Cell();jpUp.add(board[i][j]);}}add(jpUp,BorderLayout.CENTER);jpBut.add(jbFindPath);jpBut.add(jbClearPant);add(jpBut,BorderLayout.SOUTH);jbFindPath.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){findPath();}});jbClearPant.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){clearPath();}});setVisible(true);}public static void main(String [] args){new Test19_8();}public void findPath(){if(findPath(0,0)){//JOptionPane.showMessageDialog(null, "找到了,我找到了");System.out.println("找到路了");}else//JOptionPane.showMessageDialog(null,"没有了出路,人生就是悲哀");System.out.println("没有出路");}public boolean findPath(int row,int col){board[row][col].visit();if(row==7&&col==7){board[row][col].selectedCell();return true;}if((row>0)&&!board[row-1][col].blocked()&&!board[row-1][col].marked( )&&!board[row-1][col].visited()){block(row,col);if(findPath(row-1,col)){board[row][col].selectedCell();return true;}unblock(row,col);}if((row<7)&&!board[row+1][col].blocked()&&!board[row+1][col].marked( )&&!board[row+1][col].visited()){block(row,col);if(findPath(row+1,col)){board[row][col].selectedCell();return true;}unblock(row,col);}if((col>0)&&!board[row][col-1].blocked()&&!board[row][col-1].marked( )&&!board[row][col-1].visited()){block(row,col);if(findPath(row,col-1)){board[row][col].selectedCell();return true;}unblock(row,col);}if((col<7)&&!board[row][col+1].blocked()&&!board[row][col+1].marked( )&&!board[row][col+1].visited()){block(row,col);if(findPath(row,col+1)){board[row][col].selectedCell();return true;}unblock(row,col);}return false;}public void clearPath(){for(int i=0;i<8;i++){for(int j=0;j<8;j++){board[i][j].desSelectedCell();}}}public void block(int row,int col){if(row>0)board[row-1][col].block();if(row<7)board[row+1][col].block();if(col>0)board[row][col-1].block();if(col<7)board[row][col+1].block();}public void unblock(int row,int col){if(row>0)board[row-1][col].unblock();if(row<7)board[row+1][col].unblock();if(col>0)board[row][col-1].unblock();if(col<7)board[row][col+1].unblock();}}class Cell extends JPanel{private boolean visited=false;private boolean marked=false;private boolean cellSelected=false;private boolean blocked=false;Cell(){setBackground(Color.red);addMouseListener(new MouseAdapter(){public void mousePressed(MouseEvent e) {marked = !marked;repaint();}});}protected void paintComponent(Graphics g){super.paintComponent(g);if(marked){g.drawLine(0, 0, getSize().width, getSize().height);g.drawLine(getSize().width, 0, 0, getSize().height);}}public boolean visited(){return visited;}public void visit(){visited=true;}public boolean marked(){return marked;}public void block(){blocked=true;}public void unblock(){blocked=false;}public boolean blocked(){return blocked;}public void selectedCell(){setBackground(Color.green);repaint();}public void desSelectedCell(){ setBackground(Color.red);repaint();}}。

java迷宫

java迷宫

import javax.microedition.lcdui.Display;import javax.microedition.midlet.MIDlet;import javax.microedition.midlet.MIDletStateChangeException;public class MazeMIDlet extends MIDlet {static Display display = null;private MazeGameCanvas mazeGameCanvas = null;public MazeMIDlet() {mazeGameCanvas = new MazeGameCanvas();// TODO Auto-generated constructor stub}protected void destroyApp(boolean arg0) throws MIDletStateChangeException {// TODO Auto-generated method stub}protected void pauseApp() {// TODO Auto-generated method stub}protected void startApp() throws MIDletStateChangeException {display = Display.getDisplay(this);display.setCurrent(mazeGameCanvas);// TODO Auto-generated method stub}}******************************************************************************* import java.io.IOException;import javax.microedition.lcdui.Alert;import javax.microedition.lcdui.AlertType;import javax.microedition.lcdui.Graphics;import javax.microedition.lcdui.Image;import javax.microedition.lcdui.game.GameCanvas;import yerManager;import javax.microedition.lcdui.game.Sprite;import javax.microedition.lcdui.game.TiledLayer;public class MazeGameCanvas extends GameCanvas implements Runnable{ Sprite car;TiledLayer wall;TiledLayer grass;LayerManager layerManager;int[][] cells = {{2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2},{2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 2, 1, 2, 1, 1, 1, 2, 1, 2},{2, 1, 2, 2, 2, 1, 2, 1, 2, 2, 2, 1, 2, 1, 2, 1, 2, 2, 2, 1, 2},{2, 1, 1, 1, 2, 1, 2, 1, 1, 1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2},{2, 1, 2, 1, 2, 1, 2, 2, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2},{2, 1, 2, 1, 2, 1, 2, 1, 1, 1, 2, 1, 1, 1, 1, 1, 2, 1, 2, 1, 2},{2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 1, 2, 1, 2, 2, 2, 1, 2, 2, 2},{2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 2, 1, 2, 1, 1, 1, 2},{2, 1, 2, 1, 2, 1, 2, 1, 2, 2, 2, 1, 2, 2, 2, 1, 2, 1, 2, 2, 2},{2, 1, 2, 1, 1, 1, 2, 1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1, 2},{2, 1, 2, 2, 2, 1, 2, 2, 2, 1, 2, 2, 2, 1, 2, 2, 2, 2, 2, 1, 2},{2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 2},{2, 1, 2, 2, 2, 2, 2, 1, 2, 1, 2, 2, 2, 1, 2, 2, 2, 1, 2, 1, 2},{2, 1, 1, 1, 2, 1, 2, 1, 1, 1, 2, 1, 1, 1, 1, 1, 2, 1, 1, 1, 2},{2, 2, 2, 1, 2, 1, 2, 1, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 1, 2},{2, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 2, 1, 2},{2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2},{2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 2},{2, 1, 2, 1, 2, 1, 2, 2, 2, 2, 2, 1, 2, 1, 2, 2, 2, 1, 2, 1, 2},{2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 2, 1, 2, 1, 2},{2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2} };private int[] seq = {0, 1, 2};private int carX=1;private int carY=1;private int vwX=0;private int vwY=0;private int vwWidth;private int vwHeight;private static final int CELL_WIDTH = 24;private static final int CELL_HEIGHT = 24;static final byte GRASS = 1;static final byte WALL = 2;static final byte BORDER = 72;public MazeGameCanvas() {super(false);setFullScreenMode(true); //全屏模式下再取宽和长,不要在定义的时候初始化宽和长vwWidth = getWidth();vwHeight = getHeight();Image imageCar=null;Image imageBg=null;try {imageBg=Image.createImage("/bg.png");imageCar = Image.createImage("/car.png");} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}car=new Sprite(imageCar,CELL_WIDTH,CELL_HEIGHT);//宽高一样car.setFrameSequence(seq);car.setPosition(carX*CELL_WIDTH,carY*CELL_HEIGHT);grass=new TiledLayer(cells[0].length,cells.length,imageBg,CELL_WIDTH,CELL_HEIGHT);wall=new TiledLayer(cells[0].length,cells.length,imageBg,CELL_WIDTH,CELL_HEIGHT);for(int i=0;i<cells.length;i++){for(int j=0;j<cells[0].length;j++){grass.setCell(j,i,0);wall.setCell(j, i, 0);if(cells[i][j]==GRASS){grass.setCell(j, i, GRASS);}elsewall.setCell(j, i, WALL);}}layerManager=new LayerManager();layerManager.append(car);layerManager.append(wall);layerManager.append(grass);Graphics g=getGraphics();layerManager.paint(g, 0, 0);layerManager.setViewWindow(vwX, vwY, vwWidth, vwHeight);new Thread(this).start();}//下面写出将地图数组放到grass和wall两个层上//下面写出建立一个层管理器layerManager,并加上三个层car,wall,grass,并绘出layerManagerpublic void run() {Graphics g = getGraphics();int x,y;while (true) {int keyState = getKeyStates();if ((keyState & LEFT_PRESSED) != 0) {car.setTransform(Sprite.TRANS_NONE);x=carX-1;y=carY;movePosition(x,y);//佯动或者真动}else if ((keyState & RIGHT_PRESSED) != 0) {car.setTransform(Sprite.TRANS_MIRROR);x=carX+1;y=carY;movePosition(x,y);}else if ((keyState & UP_PRESSED) != 0) {car.setTransform(Sprite.TRANS_ROT90);x=carX;y=carY-1;movePosition(x,y);}else if ((keyState & DOWN_PRESSED) != 0) {car.setTransform(Sprite.TRANS_ROT270);x=carX;y=carY+1;movePosition(x,y);}car.nextFrame();layerManager.paint(g, 0, 0);//移动到下一帧要重新画flushGraphics();try {Thread.sleep(200);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}private void movePosition(int x, int y) {car.setPosition(x*CELL_HEIGHT, y*CELL_WIDTH);if (car.collidesWith(wall, false)) {car.setPosition(carX*CELL_HEIGHT, carY*CELL_WIDTH);return;}carX = x;carY = y;if (carY == cells.length-1 && carX == cells[0].length-2) {Alert alert = new Alert("congraulation");alert.setString("end");alert.setType();alert.setTimeout(Alert.FOREVER);MazeMIDlet.display.setCurrent(alert, this);}int cx = carX * CELL_WIDTH;int cy = carY * CELL_WIDTH;if (cx < vwX + BORDER && vwX>=CELL_WIDTH) {vwX -= CELL_WIDTH;layerManager.setViewWindow(vwX, vwY, vwWidth, vwHeight);} else if (cx > vwX + vwWidth - BORDER&& vwX + vwWidth<=grass.getWidth() - CELL_WIDTH) {vwX += CELL_WIDTH;layerManager.setViewWindow(vwX, vwY, vwWidth, vwHeight);}if (cy < this.vwY + BORDER && vwY>=CELL_HEIGHT) {vwY -= CELL_HEIGHT;layerManager.setViewWindow(vwX, vwY, vwWidth, vwHeight);} else if (cy > this.vwY + vwHeight - BORDER&& vwY + vwHeight<=grass.getHeight() - CELL_HEIGHT) { vwY += CELL_HEIGHT;layerManager.setViewWindow(vwX, vwY, vwWidth, vwHeight);}}}。

java写的迷宫代码

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程序以下是一个使用深度优先算法解决迷宫问题的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("迷宫无解!");}}```以上程序使用了深度优先算法来解决迷宫问题。

一个迷宫小游戏的代码

一个迷宫小游戏的代码

level = new Array();_root.attachMovie("starz", "starz", 1, {_x:-20, _y:-20});_root.createEmptyMovieClip("bricks", 2);level[0] = new Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0);level[1] = new Array(0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1);level[2] = new Array(1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1);level[3] = new Array(1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1);level[4] = new Array(1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);level[5] = new Array(1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1);level[6] = new Array(1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 1);level[7] = new Array(1, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1);level[8] = new Array(1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1);level[9] = new Array(1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1);level[10] = new Array(0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1);for (y=0; y<=10; y++) {for (x=0; x<=11; x++) {if (level[y][x] == 1) {place_brick = bricks.attachMovie("brick", "brick_"+bricks.getNextHighestDepth(), bricks.getNextHighestDepth(), {_x:x*80, _y:y*80});}}}_root.attachMovie("ball", "ball", _root.getNextHighestDepth(), {_x:240, _y:220});bricks._x = 240;bricks._y = 220;ball.texture.setMask(ball.ball_itself);power = 0.4;yspeed = 0;xspeed = 0;friction = 0.99;ball.onEnterFrame = function() {if (Key.isDown(Key.LEFT)) {xspeed -= power;}if (Key.isDown(Key.RIGHT)) {xspeed += power;}if (Key.isDown(Key.UP)) {yspeed -= power;}if (Key.isDown(Key.DOWN)) {yspeed += power;}xspeed *= friction;yspeed *= friction;bricks._y -= yspeed;bricks._x -= xspeed;starz._x = -20+((bricks._x-240)/10);starz._y = -20+((bricks._y-220)/10);this.texture._y += yspeed;this.texture._x += xspeed;if (this.texture._x>53) {this.texture._x -= 63;}if (this.texture._x<-53) {this.texture._x += 63;}if (this.texture._y>53) {this.texture._y -= 63;}if (this.texture._y<-53) {this.texture._y += 63;}brick_x = Math.floor((bricks._x-200)/80)*-1;brick_y = Math.floor((bricks._y-180)/80)*-1;if (level[brick_y][brick_x] != 1) {bricks._x = 240;bricks._y = 220;starz._x = -20;starz._y = -20;xspeed = 0;yspeed = 0;}};(选择好背景图片后,创建为元件。

走迷宫游戏的JAVA实现86630

走迷宫游戏的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 迷宫主要代码

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迷宫代码,广度优先遍历,最短路径

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 * * * *。

java 随机迷宫游戏

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课设走迷宫(含代码)

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编写迷宫⼩游戏缘起: 去年(⼤三上学期)⽐较喜欢写⼩游戏,于是想试着写个迷宫试⼀下。

程序效果:按下空格显⽰路径:思考过程: 迷宫由⼀个⼀个格⼦组成,要求从⼊⼝到出⼝只有⼀条路径. 想了⼀下各种数据结构,似乎树是⽐较合适的,从根节点到每⼀个⼦节点都只有⼀条路径。

假设⼊⼝是根节点,出⼝是树中某个⼦节点,那么,从根节点到该⼦节点的路径肯定是唯⼀的。

所以如果能构造⼀棵树把所有的格⼦都覆盖到,也就能够做出⼀个迷宫了。

另外还要求树的⽗节点和⼦节点必须是界⾯上相邻的格⼦。

在界⾯显⽰时,⽗节点和⼦节点之间共⽤的边不画,其他的边都画出来,就能画出⼀个迷宫。

之后就是想⼀下该怎么实现这样⼀棵树。

⾸要的两个问题: 1、树怎么表⽰? 2、怎么构造这棵树?1.树怎么表⽰? 假设像写⼆叉树⼀样实现这棵树,那么每个树节点⾥就要存储⼀个坐标(X,Y)表⽰⼀个格⼦,另外还要存储四个指针。

指针中有的为空,有的不为空,不为空的指针指向⼦节点,⼦节点保存邻居格⼦的坐标。

这样做最⼤的问题是⽆法判定是否所有的格⼦都在树中。

也许还要⽤⼀个⼆维数组作标志数组。

假如⽤⼆维数组表⽰迷宫的格⼦。

每个数组元素存储⼀个指向⽗节点的引⽤,这样也可以形成⼀个虚拟的树。

于是就⽤⼀个N*N的⼆维数组,表⽰N*N个格⼦,每个数组元素(Lattice)中有⼀个指向⽗节点的引⽤(father)。

另外,为了能⽅便的获取格⼦的坐标,还要保存坐标信息。

2.怎么构造这棵树? ⾸先选定⼀个格⼦作为根节点。

为了让迷宫的形状够随机,我选择随机⽣成⼀个坐标作为根节点。

其实,选择确定的⼀个坐标也可以。

然后,怎样往这棵树上增加节点呢? 在这⾥我⾛了不少弯路,⼀开始想的是⼀种现在看来类似回溯的算法(当时还不知道回溯算法。

),但是时间复杂度很⾼,⼤概当迷宫为64*64的时候,算法就不出结果了。

然后,⼜使⽤了⼀种扫深度搜索也是回溯描的⽅法,每次扫描在当前树中找⼀个节点,看它的邻居格⼦是否在树中,如果还没在树中,就将该邻居格⼦加⼊树中,如果已在树中,就看下⼀个邻居格⼦,如果该节点所有邻居格⼦都在树中了,就找下⼀个节点,继续同样的操作。

走迷宫游戏的JAVA实现

走迷宫游戏的JAVA实现

//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=getT oolkit();}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;T oolkit tool;HandleMove(){recordTime=new javax.swing.Timer(1000,this);showTime=new JTextField(16);tool=getT oolkit();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,"您成功了!","消息框",RMATION_MESSAGE);}}public void keyTyped(KeyEvent e){}}。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

帮朋友写的迷宫小游戏程序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,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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,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•删除 |•。

相关文档
最新文档