用java代码设计一个扫雷游戏,能够运行
时间: 2023-12-19 07:05:59 浏览: 29
好的,这里是一个简单的Java代码实现扫雷游戏的示例。这个示例仅包含基本的游戏逻辑和界面,你可以根据自己的需求进行修改和完善:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MineSweeper implements ActionListener {
private JFrame frame;
private JButton[][] buttons;
private int[][] board;
private int size;
private int mines;
private int remaining;
public MineSweeper(int size, int mines) {
this.size = size;
this.mines = mines;
this.remaining = size * size - mines;
// Create the game board
board = new int[size][size];
for (int i = 0; i < mines; i++) {
int row, col;
do {
row = (int) (Math.random() * size);
col = (int) (Math.random() * size);
} while (board[row][col] == -1);
board[row][col] = -1;
}
for (int row = 0; row < size; row++) {
for (int col = 0; col < size; col++) {
if (board[row][col] != -1) {
int count = 0;
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
if (row + i >= 0 && row + i < size && col + j >= 0 && col + j < size && board[row + i][col + j] == -1) {
count++;
}
}
}
board[row][col] = count;
}
}
}
// Create the game window
frame = new JFrame("Mine Sweeper");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(size, size));
buttons = new JButton[size][size];
for (int row = 0; row < size; row++) {
for (int col = 0; col < size; col++) {
JButton button = new JButton();
button.setActionCommand(row + "," + col);
button.addActionListener(this);
frame.add(button);
buttons[row][col] = button;
}
}
frame.pack();
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String[] parts = e.getActionCommand().split(",");
int row = Integer.parseInt(parts[0]);
int col = Integer.parseInt(parts[1]);
if (board[row][col] == -1) {
JOptionPane.showMessageDialog(frame, "Game Over!");
frame.dispose();
} else {
reveal(row, col);
remaining--;
if (remaining == 0) {
JOptionPane.showMessageDialog(frame, "You Win!");
frame.dispose();
}
}
}
private void reveal(int row, int col) {
buttons[row][col].setEnabled(false);
buttons[row][col].setText(String.valueOf(board[row][col]));
if (board[row][col] == 0) {
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
if (row + i >= 0 && row + i < size && col + j >= 0 && col + j < size && buttons[row + i][col + j].isEnabled()) {
reveal(row + i, col + j);
}
}
}
}
}
public static void main(String[] args) {
int size = 10;
int mines = 10;
new MineSweeper(size, mines);
}
}
```
运行这个程序,你将会看到一个简单的扫雷游戏界面。你可以单击方格来揭开它,如果揭开的方格上有地雷,游戏结束。如果揭开的方格上没有地雷,程序会递归地揭开周围的方格,直到所有没有地雷的方格都被揭开。当所有没有地雷的方格都被揭开时,游戏获胜。