扫雷示例中类中的方法数

时间:2013-01-11 09:49:56

标签: java swing oop

我是新手,所以请不要给我太多烫伤,因为我只想从一开始就遵循优秀的OOP路径:)所以我用Swing编写了一个用Java编写的扫雷艇,现在,我的代码看起来像这样:

  • 只有main()的类,它通过创建一个对象Minesweeper()
  • 来启动游戏
  • Minesweeper类,我在其中创建一个JFRame,用于菜单的JPanel(以及用于它的ActionListener)并创建一个Grid(x,y)对象
  • Grid(int width,int height)类,它扩展了JPanel,使用它创建一个具有给定尺寸的网格,在其上放置地雷并处理所有播放
但是,我对Grid()有些担忧。可以处理所有数据,从绘制所需数量的JButton,通过在它们上设置地雷并监听点击(以及解决这些点击)到finds_empty_cells算法,以防用户点击炸弹以外的其他东西,我们必须显示周围环境在一堂课中倒空?这不违反单一责任原则吗?或者可以吗?

1 个答案:

答案 0 :(得分:1)

我不熟悉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.
        }
    }

}
相关问题