方法在启动时启动

时间:2014-11-24 17:28:53

标签: java user-interface methods

所以,我有一个gameOver()方法,当椭圆超出界限中止游戏时,但是,一旦我开始游戏,它就会运行gameOver方法。我一直在寻找不同的东西。我认为对我而言最重要的是删除游戏运行的中止序列,因为它应该在之后,弹出窗口关闭,如果我替换game.gameOver();当ya = -1时,球从墙上反弹。

gaveOver()

public void gameOver(){
    JOptionPane.showMessageDialog(this, "Game Over", "Game Over", JOptionPane.YES_NO_OPTION);
    System.exit(ABORT);
}

移动()

package com.edu4java.minitennis1;

import java.awt.Graphics2D;
 import java.awt.Rectangle;

public class Ball {
private static final int DIAMETER = 30;
int x = 0;
int y = 0;
int xa = 1; // Represent the speed in which the ball is moving
int ya = 1; // Represent the speed in which the ball is moving
private Game game;

public Ball(Game game){
    this.game=game;
}

/*
 * If xa=1, the ball moves to the right, one pixel every round of the Game Loop,
 * if xa=-1, the ball moves to the left. 
 * If ya=1 moves the ball down and 
 * If ya=-1 moves the ball up.
 */

void move(){
    if (x + xa < 0) // Makes left bounds
        xa = 3; // Moves the ball right
    if (x + xa > game.getWidth() - DIAMETER) // Makes right bounds
        xa = -3; // Moves the ball left
    if(y + ya < 0) // Makes top bounds
        ya = 3; // Moves ball down

    if(y + ya > game.getHeight() - DIAMETER) // Makes bottom bounds
        game.gameOver();

    if (collision()){ // Makes collision with Racquet
        ya = -3;
        y = game.racquet.getTopY() - DIAMETER;
    }
    x = x + xa;
    y = y + ya;
}

private boolean collision(){
    return game.racquet.getBounds().intersects(getBoundsBall());
}

public void paint(Graphics2D g){
    g.fillOval(x, y, DIAMETER, DIAMETER);
}

public Rectangle getBoundsBall(){
    return new Rectangle(x, y, DIAMETER, DIAMETER);
}

}

问题已经解决我刚回去重写了move()方法并用

替换了它
void move(){
     if(x + xa < 0)// Makes left bounds
         xa = 1;// Moves the ball right
     if(x + xa == game.getWidth() - DIAMETER)// Makes right bounds
         xa = -1;// Moves the ball left
     if (y + ya < 0)// Makes top bounds
         ya = 1;// Moves ball down
     if(y + ya == game.getHeight() - DIAMETER){ // Makes bottom bounds
        ya = 0;// Moves ball up
        xa = 0;
        game.gameOver();
     }

有时您需要做的就是回去。

1 个答案:

答案 0 :(得分:0)

我想你已经回答了你的问题。假设你的gameOver()方法没有进一步调用你的move()方法中的那个,那么从if if块调用gameOver:

if(y + ya > game.getHeight() - DIAMETER)
    game.gameOver();

这意味着(y + ya)大于(game.getHeight() - DIAMETER)。由于我不知道您的变量应该是什么,我只能猜测您的初始值可能存在问题等。

尝试使用调试程序逐步执行程序,这样可以更轻松地查看问题并了解正在进行的操作。