我一直在努力學習最近關於Java的更多內容,所以我遵循了關於如何使用Java構建遊戲的在線指南。一切工作正常,但我想補充更多,所以我可以讓它成爲我自己的。到目前爲止一切正常,但我最近陷入了個人僵局。下面的代碼,到目前爲止,包括我對我自己添加的內容(我的問題是在底部):爲什麼我不能在if-then語句中更改變量的值?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class PongGame extends JComponent implements ActionListener, MouseMotionListener {
public static PongGame game = new PongGame();
private int ballX = 400;
private int ballY = 250;
private int paddleX = 0;
private int ballYSpeed = 2;
private int ballXSpeed = 2;
private static int time = 15;
public static Timer t = new Timer(time, game);
public static void main(String[] args) {
JFrame window = new JFrame("Pong Game by Ethan");
window.add(game);
window.pack();
window.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
window.setLocationRelativeTo(null);
window.setVisible(true);
t.start();
window.addMouseMotionListener(game);
}
public Dimension getPreferredSize() {
return new Dimension(800, 600);
}
@Override
protected void paintComponent(Graphics g) {
//draw the background
g.setColor(Color.WHITE);
g.fillRect(0, 0, 800, 600);
//draw the paddle
g.setColor(Color.BLACK);
g.fillRect(paddleX, 510, 150, 15);
//draw the ball
g.setColor(Color.BLACK);
g.fillOval(ballX, ballY, 25, 25);
}
@Override
public void actionPerformed(ActionEvent e) {
ballX = ballX + ballXSpeed;
ballY = ballY + ballYSpeed;
if (ballX >= paddleX && ballX <= paddleX + 150 && ballY >= 485) {
ballYSpeed = -2;
lessTime();
}
if (ballX >=775) {
ballXSpeed = -2;
}
if (ballX <= 0) {
ballXSpeed = 2;
}
if (ballY <= 0) {
ballYSpeed = 2;
}
if (ballY == 500) {
PongGame.infoBox("GAME OVER","");
t.stop();
System.exit(0);
}
repaint();
}
@Override
public void mouseDragged(MouseEvent e) {
}
@Override
public void mouseMoved(MouseEvent e) {
paddleX = e.getX() - 75;
repaint();
}
public static void infoBox(String infoMessage, String titleBar) {
JOptionPane.showMessageDialog(null, infoMessage, "Game Over" + titleBar, JOptionPane.INFORMATION_MESSAGE);
}
public static void lessTime() {
time--;
}
}
正如你所看到的,我有一個變量在那裏叫time
附近使用該頂通過Timer t
正下方,並在底部命名爲lessTime
方法,只調用時從time
變量中刪除1。我已經設置在第一條if語句中調用lessTime
方法,此時球從球拍反彈以增加遊戲速度(我正朝着一個計數器工作),但它似乎並沒有提高速度在所有。
我使用--time;
,time--;
和time = time - 1;
裏面的所有lessTime
方法,並通過自己在if
聲明試過,但沒有人從time
變量去除任何量。有人可以解釋爲什麼time
變量不受if
聲明中的方法或單獨影響,以及我如何解決它?
謝謝!
你混淆包含在'Timer'與值的修改'time'變量的值的修改。更改一個不會影響另一個,因爲Java是[按值傳遞](http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value)語言。 – azurefrog