0

我相信这是一个非常简单的 OO 问题,但我似乎找不到答案:/ 我有一个游戏面板,其中有很多球被涂在面板上。当球击中面板底部时,应显示 Game Over 消息。

我正在处理的问题是关于这个 Game Over JOptionPane。我认为它应该保留在这个类中,但我需要在Ball类中调用它。

这是Ball我要调用该方法的类的一部分(标有**):

private void moveBall() {

    if (x == panel.getWidth() - size) {
        xa -= speed;
    } else if (x < 0) {
        xa += speed;
    }

    if (y == panel.getHeight() - size) {
        ya -= speed;
    } else if (y < 0) {
        ya += speed;
    }

    if (collision()) {
        ya = -speed;
        y = platform.getY() - DIAMETER;
    }

    if (y == panel.getHeight() - size) {

        // ***Call gameOver here***

    }
    x += xa;
    y += ya;
}

这是从我的游戏面板中的球类调用的构造函数:

// Constructor to pass a colour and a platform
public Ball(JFrame frame, JPanel panel, Platform platform, Color colour,
        int x, int y, int size) {

    this.platform = platform;

    this.frame = frame;
    this.panel = panel;
    this.colour = colour;

    // Location of the ball
    this.x = x;
    this.y = y;

    // Size of the ball
    this.size = size;

    animator = new Thread(this);
    animator.start();
}

那么如何访问该方法呢?

注意(结构):框架 -> 面板 -> 球

谢谢

如果我没有很好地解释自己或者您需要更多信息,请告诉我

4

2 回答 2

2

考虑从可以访问 gameOver 函数的不同类中观察球的位置。这样您就不需要将面板暴露给Ball班级,并且避免了您的问题。

此外,您不能调用该gameOver函数,因为它不存在于 中JFrame,如果要使用此当前方法,则需要向构造函数提供包含该gameOver函数的类或接口。Ball

于 2013-07-25T14:22:31.307 回答
1

与其让你的班级从你的Ball班级调用一个方法,我认为实现你想要的更好的方法是在你的班级中有一个方法来指示/设置一个布尔值,如果你的球已经击中屏幕底部。然后让这个方法在球接触屏幕底部时触发(您当前想要将游戏置于方法调用的位置)。FramePanelBall

从那里,让有权访问您的游戏结束方法的类检查此指示器/布尔值是否应该触发游戏结束方法。

于 2013-07-25T14:25:10.680 回答