扫雷游戏布雷方法实现求助:二维数组周边单元格计数逻辑
Hey there! Let's fix up your Minesweeper implementation to meet your requirements. I'll break down the issues in your current code and provide a corrected version with the proper mine-placement method you need.
Key Issues in Your Current Code
- Incorrect Constructor: Java constructors don't have a return type (including
void). YourMinefieldmethod is treated as a regular method instead of initializing the object. - Hardcoded Board Size: You're using
5for rows/columns everywhere instead of the passed-inrowandcolumnparameters. - Misplaced Initialization:
emptySpacesis initialized at the class level whenrowandcolumnare still0, so it will always be0initially. - Boundary Check Errors: The
mineCountmethod doesn't validate if neighboring cells are within the board bounds during the loop, leading to potentialArrayIndexOutOfBoundsException. - Missing Required Mine-Placement Method: You don't have a dedicated method that accepts coordinates to place a mine and returns a boolean as requested.
Corrected Minefield Class
import java.util.Random; public class Minefield { private boolean[][] minefield; private int[][] minedNeighbour; private final Random r = new Random(); private int row; private int column; private int maxMines; // Maximum allowed mines for the board private int currentMines; // Tracks how many mines have been placed private int emptySpaces; // Proper constructor (no return type) public Minefield(int row, int column, int maxMines) { this.row = row; this.column = column; // Ensure max mines doesn't exceed total cells (can't have more mines than spaces) this.maxMines = Math.min(maxMines, row * column); this.currentMines = 0; this.emptySpaces = row * column; // Initialize arrays minefield = new boolean[row][column]; minedNeighbour = new int[row][column]; } // The requested mine-placement method public boolean placeMine(int x, int y) { // 1. Check if coordinates are within board bounds if (x < 0 || x >= row || y < 0 || y >= column) { return false; } // 2. Check if cell already has a mine if (minefield[x][y]) { return false; } // 3. Check if we've reached the maximum allowed mines if (currentMines >= maxMines) { return false; } // Place the mine minefield[x][y] = true; currentMines++; emptySpaces--; // Increment neighboring cells' mine counts for (int i = x - 1; i <= x + 1; i++) { for (int j = y - 1; j <= y + 1; j++) { // Skip the mine cell itself and validate bounds if ((i != x || j != y) && i >= 0 && i < row && j >= 0 && j < column) { minedNeighbour[i][j]++; } } } return true; } // Optional: Randomly place all max mines (for quick setup) public void placeRandomMines() { while (currentMines < maxMines) { int x = r.nextInt(row); int y = r.nextInt(column); placeMine(x, y); // Uses our validated placeMine method } } // Fixed display method (no hardcoding, proper formatting) public void display() { // Print column headers System.out.print(". "); for (int j = 0; j < column; j++) { System.out.print(j + " "); } System.out.println(); // Print each row for (int i = 0; i < row; i++) { System.out.print(i + " "); for (int j = 0; j < column; j++) { if (minefield[i][j]) { System.out.print("* "); // Show mine as * } else if (minedNeighbour[i][j] > 0) { System.out.print(minedNeighbour[i][j] + " "); } else { System.out.print(". "); // Empty cell with 0 neighbors } } System.out.println(); } } // Getters if needed (optional) public int getCurrentMines() { return currentMines; } public int getEmptySpaces() { return emptySpaces; } }
Key Improvements Explained
Validated Mine-Placement Method:
- The
placeMine(int x, int y)method checks all your required conditions first: bounds, existing mine, and max mine limit. - When a mine is placed, it loops through all 8 neighboring cells, validates they're within bounds, and increments their neighbor count automatically.
- The
Proper State Management:
maxMinesensures we never try to place more mines than there are board cells.currentMinestracks how many mines have been successfully placed, making it easy to check against the limit.emptySpacesis now initialized correctly in the constructor afterrowandcolumnare set.
Fixed Display:
- The
displaymethod works for any board size (no more hardcoded5s) and uses clear, standard Minesweeper symbols:*for mines, numbers for neighbor counts, and.for empty cells with no adjacent mines.
- The
Random Mine Placement:
- The
placeRandomMineshelper method uses the validatedplaceMinemethod to safely fill the board with mines, avoiding duplicates and invalid placements.
- The
Example Usage
public class Main { public static void main(String[] args) { Minefield minefield = new Minefield(5, 5, 5); // 5x5 board, max 5 mines // Place a mine manually boolean placed = minefield.placeMine(2, 2); System.out.println("Mine placed at (2,2): " + placed); // Should print true // Try placing a mine on an already mined cell placed = minefield.placeMine(2, 2); System.out.println("Mine placed at (2,2) again: " + placed); // Should print false // Fill remaining mines randomly minefield.placeRandomMines(); // Display the board minefield.display(); } }
内容的提问来源于stack exchange,提问作者Pioneer
相关产品推荐
相关产品推荐

