0
我是Java的新手,我正在创建一个基本的“迷你网球比赛”,我希望每次球接触球拍时将比分提高一分。我已经将屏幕上的分数显示为0,但我不知道如何让它增加。我将非常感谢您可以给我的任何帮助。这里是我的代码至今:我想增加迷你网球比赛的分数
游戏类
private int score = 0;
Ball ball = new Ball(this);
SecondBall ball2 = new SecondBall(this);
Racquet racquet = new Racquet(this);
public Game() {
addKeyListener(new KeyListener() {
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
racquet.keyPressed(e);
}
@Override
public void keyReleased(KeyEvent e) {
racquet.keyReleased(e);
}
});
setFocusable(true);
}
private void move() {
ball.move();
ball2.move();
racquet.move();
}
@Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
ball.paint(g2d);
ball2.paint(g2d);
racquet.paint(g2d);
**//Show score on screen
String s = Integer.toString(score);
String sc = "Your score: ";
g.drawString(sc, getWidth()-150, 50);
g.drawString(s, getWidth()-50, 50);**
}
public void gameOver() {
JOptionPane.showMessageDialog(this, "You Suck!!", "Game Over", JOptionPane.YES_NO_OPTION);
System.exit(ABORT);
}
public static void main(String[] args) throws InterruptedException {
JFrame frame = new JFrame("Mini Tennis");
Game game = new Game();
frame.add(game);
frame.setSize(300, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
while (true) {
game.move();
game.repaint();
Thread.sleep(10);
}
}
}
球类
private static final int DIAMETER = 30;
int x = 0;
int y = 0;
int xa = 1;
int ya = 1;
private Game game;
private int score = 0;
private String yourScoreName;
public Ball(Game game) {
this.game = game;
}
public void move() {
if (x + xa < 0)
xa = 1;
if (x + xa > game.getWidth() - DIAMETER)
xa = -1;
if (y + ya < 0)
ya = 1;
if (y + ya > game.getHeight() - DIAMETER)
game.gameOver();
if (collision()) {
ya = -1;
y = game.racquet.getTopY() - DIAMETER;
}
x = x + xa;
y = y + ya;
}
private boolean collision() {
return game.racquet.getBounds().intersects(getBounds());
}
public void paint(Graphics2D g) {
g.fillOval(x, y, 30, 30);
}
public Rectangle getBounds() {
return new Rectangle(x, y, DIAMETER, DIAMETER);
}
}
增加'score'变量并重新绘制游戏的分数? – saloomi2012