扫雷游戏java代码
时间: 2023-12-19 11:03:09 浏览: 153
扫雷游戏是一个经典的益智游戏,玩家需要根据数字推断出雷的位置,然后进行标记或揭开方块。以下是一个简单的扫雷游戏的Java代码示例:
```java
import java.util.Random;
import java.util.Scanner;
public class Minesweeper {
private char[][] board;
private int size;
private int mines;
public Minesweeper(int size, int mines) {
this.size = size;
this.mines = mines;
this.board = new char[size][size];
}
public void initBoard() {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
board[i][j] = '-';
}
}
}
public void placeMines() {
Random rand = new Random();
int count = 0;
while (count < mines) {
int x = rand.nextInt(size);
int y = rand.nextInt(size);
if (board[x][y] != '*') {
board[x][y] = '*';
count++;
}
}
}
public void displayBoard() {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter board size: ");
int size = scanner.nextInt();
System.out.print("Enter number of mines: ");
int mines = scanner.nextInt();
Minesweeper game = new Minesweeper(size, mines);
game.initBoard();
game.placeMines();
game.displayBoard();
}
}
```
以上代码是一个简单的扫雷游戏的Java代码示例,实现了初始化游戏面板、布雷和显示游戏面板的功能。在实际开发中,还需要添加玩家交互和游戏规则等功能。
阅读全文