我对swing不熟悉,所以只能给你一些伪java代码。但是,它应该服务于演示目的。当您想达到 OOP 的下一个级别时,我建议为扫雷网格中的单元格创建一个类。
public class Cell extends JPanel {
private MinesweepController controller;
private int points;
private boolean revealed;
// Index in the grid.
private int x, y;
public Cell(MinesweepController controller_, int x_, int y_, int points_) {
controller = controller_;
points = points_;
x = x_;
y = y_;
}
public void onClick(MouseEvent event) {
controller.reveal(x, y);
}
public void paint(Graphics gfx) {
if (revealed) {
if (points < 0) {
drawBomb(getX(), getY())
}
else {
drawPoints(getX(), getY(), points);
}
}
else {
drawRect(getX(), getY());
}
}
public int getPoints() {
return points;
}
public boolean isRevealed() {
return revealed;
}
public void reveal() {
revealed = true;
}
}
public class MinesweepController {
private Grid grid;
private int score;
// ...
public boid reveal(int x, int y) {
Cell cell = grid.getCell(x, y);
if (cell.getPoints() < 0) {
// End game.
}
else {
score += cell.getPoints();
// Reveal ascending cells.
}
}
}