我最近一直在尝试了解有关Java的更多信息,因此我遵循了有关如何用Java编写游戏的在线指南。一切正常,但我想添加更多内容,以便自己制作。到目前为止,一切都还可以,但是最近我陷入了个人僵局。到目前为止,这是代码,包括我自己添加的内容(我的问题在底部):
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 。我将它设置为lessTime
在第一个if语句中调用该方法,当球从球拍上弹起以提高游戏速度时(我正在努力实现计数器),但似乎并没有提高速度。全部。
我已经尝试在方法中使用--time;
,time--;
和方法,并且在语句中单独使用它们,但是它们都没有从变量中删除任何金额。有人可以解释为什么变量不受方法或语句内单独影响的原因,以及如何解决该问题的方法吗?time = time - 1;
lessTime
if
time
time
if
谢谢!
您遇到的问题是因为Java是一种“按值传递”语言。这意味着,当您将int time
变量传递到用于实例化变量的构造函数时Timer t
,实际上已经传递了int time
(15)的值,而不是int time
变量本身。结果是,如果int time
通过减少变量来更改变量的值(现在为14),则变量内的值Timer t
仍为15。
我能想到的解决最僵局的最短解决方案是在您的lessTime()
方法中添加一行代码,如下所示:
public static void lessTime() {
time--;
// set t to a new Timer with the new decremented time value.
t = new Timer(time, game);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句