I'm pretty sure the problem occurs in line 72, but I can't see why, the method seems fine to me.
package com.codegym.games.minesweeper;
import com.codegym.engine.cell.*;
import java.util.ArrayList;
public class MinesweeperGame extends Game {
public static void main(String[] args){
}
private static final int SIDE = 9;//边长
private int countMinesOnField = 0;//雷数汇总
private static final String MINE = "\\uD83D\\uDCA3";
private static final String FLAG = "\uD83D\uDEA9";
private int countFlags;//还没有被插上去的旗子数量
public void initialize() {//初始化
setScreenSize(SIDE,SIDE);
createGame();
countMineNeighbors();
}
private GameObject[][] gameField = new GameObject[SIDE][SIDE];
//初始化游戏区块
private void createGame() {
for(int i = 0; i < SIDE; i++ ){
for(int j = 0; j < SIDE; j++){
boolean isMine = (getRandomNumber(10)==0);//通过随机数判别是否有雷
gameField[i][j] = new GameObject(j,i,isMine);
setCellColor(j,i,Color.ORANGE);
if (isMine)
countMinesOnField++;
}
}
countFlags = countMinesOnField;
}
//初始化:生成递给的方块的周边区块的list
public ArrayList<GameObject> getNeighbors(GameObject obj){
ArrayList<GameObject> list = new ArrayList<>();
for (int i = -1; i < 2; i++) {
for (int j = -1; j < 2; j++) {
try {
if (!(i==0&&j==0))
list.add(gameField[obj.y+j][obj.x+i]);
} catch (Exception e) {
}
}
}
return list;
}
//初始化:遍历数雷
private void countMineNeighbors() {
for (GameObject[] objects : gameField) {
for (GameObject object : objects) {
if (!object.isMine) {
for (GameObject o : getNeighbors(object)) {
if (o.isMine)
object.countMineNeighbors++;
}
}
}
}
}
//机制:鼠标点击方块时的动作
private void openTile(int x, int y) {
gameField[y][x].isOpen = true;
setCellColor(x,y,Color.WHITE);
if (gameField[y][x].isMine)
setCellValue(x,y,MINE);
else {
if (gameField[y][x].countMineNeighbors==0) {
//本身不是雷,如果周围没有雷,那么继续扩散自动点开
for(GameObject o: getNeighbors(gameField[y][x])) {
openTile(o.x, o.y);
}
}
//本身不是雷,周围至少有一个雷:显示出那个雷的数字
else {
setCellNumber(x, y, gameField[y][x].countMineNeighbors);
}
}
}
//覆盖:左键点击的操作
@Override
public void onMouseLeftClick(int x, int y) {
openTile(x,y);
}
}