我是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);
}
}
答案 0 :(得分:0)
你已经有了一个碰撞方法,如果球与你的球拍碰撞,它会返回true。所以你可以很容易地增加你的分数:
if (collision()) {
ya = -1;
y = game.racquet.getTopY() - DIAMETER;
score++; //// like this
}
只是一个建议,通过复制粘贴教程,你不会学习它。从开始处开始。