基于JAVA实现的迷宫鼠迷宫小游戏
时间: 2023-08-11 07:06:41 浏览: 107
好的,下面是基于JAVA实现的迷宫鼠迷宫小游戏的代码示例:
```
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class MazeGame extends JPanel implements KeyListener {
private int[][] maze;
private int row; //迷宫行数
private int col; //迷宫列数
private int x,y; //鼠标当前位置
private int startX,startY; //鼠标起始位置
private int endX,endY; //鼠标结束位置
public MazeGame(int[][] maze, int row, int col) {
this.maze = maze;
this.row = row;
this.col = col;
this.x = startX = 1;
this.y = startY = 0;
//设置窗口大小和标题
JFrame frame = new JFrame("Maze Game");
frame.setSize(500, 500);
frame.getContentPane().add(this);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//设置键盘监听器
this.addKeyListener(this);
this.setFocusable(true);
}
public void paint(Graphics g) {
//绘制迷宫
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (maze[i][j] == 1) {
g.setColor(Color.black);
g.fillRect(j * 20, i * 20, 20, 20);
} else {
g.setColor(Color.white);
g.fillRect(j * 20, i * 20, 20, 20);
}
}
}
//绘制鼠标
g.setColor(Color.red);
g.fillOval(x * 20, y * 20, 20, 20);
}
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
switch (code) {
case KeyEvent.VK_UP:
if (y > 0 && maze[y - 1][x] == 0) {
y--;
}
break;
case KeyEvent.VK_DOWN:
if (y < row - 1 && maze[y + 1][x] == 0) {
y++;
}
break;
case KeyEvent.VK_LEFT:
if (x > 0 && maze[y][x - 1] == 0) {
x--;
}
break;
case KeyEvent.VK_RIGHT:
if (x < col - 1 && maze[y][x + 1] == 0) {
x++;
}
break;
}
//重绘鼠标
repaint();
//判断是否到达终点
if (x == endX && y == endY) {
JOptionPane.showMessageDialog(this, "You Win!");
}
}
public void keyReleased(KeyEvent e) {
}
public static void main(String[] args) {
int[][] maze = {
{1,1,1,1,1,1,1,1,1,1},
{0,0,0,0,1,0,0,0,0,1},
{1,0,1,0,0,0,1,1,0,1},
{1,0,1,1,1,1,0,0,0,0},
{1,0,0,0,0,0,0,1,1,1},
{1,1,1,1,1,1,1,1,1,1}
};
new MazeGame(maze, 6, 10);
}
}
```
这个代码实现了一个简单的迷宫游戏,玩家通过键盘控制鼠标的移动,到达终点即为胜利。其中,迷宫的墙用1表示,空地用0表示,起点为(1,0),终点为(4,7)。你可以根据需要修改迷宫的大小和起点、终点的位置。
阅读全文