迷宫问题java图形界面
时间: 2023-09-25 10:15:54 浏览: 92
你可以使用Java Swing和AWT库来创建迷宫问题的图形界面。以下是一个简单的示例代码:
```java
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MazeGame extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L;
private static final int WIDTH = 800;
private static final int HEIGHT = 600;
private static final int ROWS = 20;
private static final int COLS = 20;
private static final int CELL_SIZE = 30;
private static final int WALL_THICKNESS = 5;
private static final Color WALL_COLOR = Color.BLACK;
private static final Color PATH_COLOR = Color.WHITE;
private static final Color START_COLOR = Color.GREEN;
private static final Color END_COLOR = Color.RED;
private JButton generateButton;
private int[][] maze;
private int startRow, startCol, endRow, endCol;
public MazeGame() {
setLayout(null);
generateButton = new JButton("Generate");
generateButton.setBounds(10, 10, 100, 30);
generateButton.addActionListener(this);
add(generateButton);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Maze Game");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(WIDTH, HEIGHT);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.add(new MazeGame());
frame.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == generateButton) {
generateMaze();
}
}
private void generateMaze() {
maze = new int[ROWS][COLS];
Random rand = new Random();
startRow = rand.nextInt(ROWS);
startCol = rand.nextInt(COLS);
endRow = rand.nextInt(ROWS);
endCol = rand.nextInt(COLS);
while (endRow == startRow && endCol == startCol) {
endRow = rand.nextInt(ROWS);
endCol = rand.nextInt(COLS);
}
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
if (i == startRow && j == startCol) {
maze[i][j] = 2; // start cell
} else if (i == endRow && j == endCol) {
maze[i][j] = 3; // end cell
} else {
maze[i][j] = rand.nextInt(2); // 0 for wall, 1 for path
}
}
}
repaint();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(WALL_COLOR);
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
if (maze != null && maze[i][j] == 0) {
g.fillRect(j * CELL_SIZE, i * CELL_SIZE, CELL_SIZE, CELL_SIZE);
}
}
}
g.setColor(PATH_COLOR);
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
if (maze != null && maze[i][j] == 1) {
g.fillRect(j * CELL_SIZE, i * CELL_SIZE, CELL_SIZE, CELL_SIZE);
}
}
}
if (maze != null) {
g.setColor(START_COLOR);
g.fillOval(startCol * CELL_SIZE, startRow * CELL_SIZE, CELL_SIZE, CELL_SIZE);
g.setColor(END_COLOR);
g.fillOval(endCol * CELL_SIZE, endRow * CELL_SIZE, CELL_SIZE, CELL_SIZE);
}
}
}
```
这个代码会生成一个20x20的迷宫,其中随机生成起点和终点。点击“Generate”按钮会重新生成迷宫。你可以根据自己的需要调整代码以生成更大或更小的迷宫,或者添加其他功能。
阅读全文