import java.awt.*;
import java.awt.event.*;
import java.util.Random;
public class Minesweeper {
private static final int ROWS = 10;
private static final int COLUMNS = 10;
private static final int MINES = 10;
private final JFrame frame = new JFrame("Minesweeper");
private final JPanel boardPanel = new JPanel(new GridLayout(ROWS, COLUMNS));
private final JButton[][] buttons = new JButton[ROWS][COLUMNS];
private final boolean[][] mines = new boolean[ROWS][COLUMNS];
private boolean gameOver = false;
public Minesweeper() {
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLUMNS; j++) {
buttons[i][j] = new JButton();
buttons[i][j].addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (gameOver) {
return;
}
if (mines[i][j]) {
gameOver = true;
buttons[i][j].setText("*");
} else {
int count = 0;
for (int row = i - 1; row <= i + 1; row++) {
for (int col = j - 1; col <= j + 1; col++) {
if (row >= 0 && row < ROWS && col >= 0 && col < COLUMNS && mines[row][col]) {
count++;
}
}
}
if (count == 0) {
buttons[i][j].setText("");
for (int row = i - 1; row <= i + 1; row++) {
for (int col = j - 1; col <= j + 1; col++) {
if (row >= 0 && row < ROWS && col >= 0 && col < COLUMNS && !mines[row][col]) {
buttons[row][col].doClick();
}
}
}
} else {
buttons[i][j].setText(String.valueOf(count));
}
}
}
});
boardPanel.add(buttons[i][j]);
}
}
frame.add(boardPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
placeMines();
}
private void placeMines() {
Random random = new Random();
for (int i = 0; i < MINES; i++) {
int row = random.nextInt(ROWS);
int col = random.nextInt(COLUMNS);
mines[row][col] = true;
}
}
public static void main(String[] args) {
new Minesweeper();
}
}