2016-05-11 26 views
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); 
} 

}

+1

增加'score'變量並重新繪製遊戲的分數? – saloomi2012

回答

0

您已經返回true碰撞方法如果球碰撞你的球拍。所以你可以很容易地增加你的分數:

if (collision()) { 
    ya = -1; 
    y = game.racquet.getTopY() - DIAMETER; 
    score++; //// like this 
} 

只是一個建議,通過複製粘貼教程,你不會學習它。從開始開始。