1000字范文,内容丰富有趣,学习的好帮手!
1000字范文 > java小游戏之扫雷

java小游戏之扫雷

时间:2022-02-17 04:09:36

相关推荐

java小游戏之扫雷

package game;import java.util.Random;import java.util.Scanner;public class Minesweeper {private int[][] board; // 扫雷面板private boolean[][] revealed; // 已经翻开的方块private final int mineCount; // 总雷数private int remainingMines; // 剩余雷数private boolean gameEnd; // 游戏是否结束public Minesweeper(int rows, int cols, int mineCount) {this.board = new int[rows][cols];this.revealed = new boolean[rows][cols];this.mineCount = mineCount;this.remainingMines = mineCount;this.gameEnd = false;setMines();setNumber();}// 随机设置雷private void setMines() {Random random = new Random();int count = 0;while (count < mineCount) {int row = random.nextInt(board.length);int col = random.nextInt(board[0].length);if (board[row][col] != -1) {board[row][col] = -1;count++;}}}// 设置数字(表示周围的雷数)private void setNumber() {for (int i = 0; i < board.length; i++) {for (int j = 0; j < board[0].length; j++) {if (board[i][j] == -1) {continue;}int count = 0;for (int r = i - 1; r <= i + 1; r++) {for (int c = j - 1; c <= j + 1; c++) {if (r >= 0 && r < board.length && c >= 0 && c < board[0].length && board[r][c] == -1) {count++;}}}board[i][j] = count;}}}// 输出当前局面public void printBoard() {System.out.print(" ");for (int i = 0; i < board[0].length; i++) {System.out.print(i + " ");}System.out.println();for (int i = 0; i < board.length; i++) {System.out.print(i + " ");for (int j = 0; j < board[0].length; j++) {if (!revealed[i][j]) {System.out.print("* ");} else if (board[i][j] == -1) {System.out.print("X ");} else {System.out.print(board[i][j] + " ");}}System.out.println();}}// 翻开指定位置的方块,并判断游戏是否结束private void reveal(int row, int col) {if (revealed[row][col]) {return;}revealed[row][col] = true;if (board[row][col] == -1) {gameEnd = true;System.out.println("很遗憾,你输了!");return;}if (--remainingMines == 0) {gameEnd = true;System.out.println("恭喜你,你赢了!");return;}if (board[row][col] == 0) {for (int r = row - 1; r <= row + 1; r++) {for (int c = col - 1; c <= col + 1; c++) {if (r >= 0 && r < board.length && c >= 0 && c < board[0].length) {reveal(r, c);}}}}}// 开始游戏public void play() {Scanner scanner = new Scanner(System.in);while (!gameEnd) {System.out.println("当前雷数:" + remainingMines);printBoard();System.out.println("请输入行列坐标(用空格分隔):");int row = scanner.nextInt();int col = scanner.nextInt();if (row < 0 || row >= board.length || col < 0 || col >= board[0].length) {System.out.println("输入不合法,请重新输入!");continue;}reveal(row, col);}scanner.close();}public static void main(String[] args) {Minesweeper game = new Minesweeper(10, 10, 10);game.play();}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。