Java扫雷小游戏
发布时间
阅读量:
阅读量
简单的Java扫雷游戏示例代码。这个游戏使用了控制台作为游戏界面
import java.util.Scanner;
public class Minesweeper {
private static final int ROWS = 10;
private static final int COLS = 10;
private static final int MINES = 10;
private static char[][] board = new char[ROWS][COLS];
private static boolean[][] mines = new boolean[ROWS][COLS];
private static boolean[][] revealed = new boolean[ROWS][COLS];
public static void main(String[] args) {
// 初始化游戏板
initBoard();
// 随机放置地雷
placeMines();
// 游戏循环
while (true) {
// 打印游戏板
printBoard();
// 获取玩家输入
Scanner scanner = new Scanner(System.in);
System.out.print("Enter row and column: ");
int row = scanner.nextInt();
int col = scanner.nextInt();
// 判断玩家是否踩到了地雷
if (mines[row][col]) {
System.out.println("Game over! You stepped on a mine.");
break;
}
// 揭开格子并显示周围地雷数量
int count = countAdjacentMines(row, col);
board[row][col] = (char) (count + '0');
revealed[row][col] = true;
// 判断是否胜利
if (isWin()) {
System.out.println("Congratulations! You win!");
break;
}
}
}
private static void initBoard() {
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
board[i][j] = '-';
}
}
}
private static void placeMines() {
int count = 0;
while (count < MINES) {
int row = (int) (Math.random() * ROWS);
int col = (int) (Math.random() * COLS);
if (!mines[row][col]) {
mines[row][col] = true;
count++;
}
}
}
private static void printBoard() {
System.out.print(" ");
for (int j = 0; j < COLS; j++) {
System.out.print(j + " ");
}
System.out.println();
for (int i = 0; i < ROWS; i++) {
System.out.print(i + " ");
for (int j = 0; j < COLS; j++) {
if (revealed[i][j]) {
System.out.print(board[i][j] + " ");
} else {
System.out.print("- ");
}
}
System.out.println();
}
}
private static int countAdjacentMines(int row, int col) {
int count = 0;
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
int r = row + i;
int c = col + j;
if (r >= 0 && r < ROWS && c >= 0 && c < COLS && mines[r][c]) {
count++;
}
}
}
return count;
}
private static boolean isWin() {
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
if (!revealed[i][j] && !mines[i][j]) {
return false;
}
}
}
return true;
}
}
全部评论 (0)
还没有任何评论哟~
