You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

扫雷游戏布雷方法实现求助:二维数组周边单元格计数逻辑

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). Your Minefield method is treated as a regular method instead of initializing the object.
  • Hardcoded Board Size: You're using 5 for rows/columns everywhere instead of the passed-in row and column parameters.
  • Misplaced Initialization: emptySpaces is initialized at the class level when row and column are still 0, so it will always be 0 initially.
  • Boundary Check Errors: The mineCount method doesn't validate if neighboring cells are within the board bounds during the loop, leading to potential ArrayIndexOutOfBoundsException.
  • 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

  1. 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.
  2. Proper State Management:

    • maxMines ensures we never try to place more mines than there are board cells.
    • currentMines tracks how many mines have been successfully placed, making it easy to check against the limit.
    • emptySpaces is now initialized correctly in the constructor after row and column are set.
  3. Fixed Display:

    • The display method works for any board size (no more hardcoded 5s) and uses clear, standard Minesweeper symbols: * for mines, numbers for neighbor counts, and . for empty cells with no adjacent mines.
  4. Random Mine Placement:

    • The placeRandomMines helper method uses the validated placeMine method to safely fill the board with mines, avoiding duplicates and invalid placements.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 16:44:07