I've been trying to learn more about Java recently, so I followed an online guide on how to build a game in Java. Everything worked fine, but I wanted to add on more so I could make it my own. It's been going OK so far, but I've recently reached a personal impasse. Here's the code so far, including what I've added on my own (my question is at the bottom):
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--;
}
}
As you can see, I have a variable in there called time
near the top which is used by Timer t
right below it, and a method named lessTime
at the bottom which just removes 1 from the time
variable when called. I have it set to call the lessTime
method in the first if statement when the ball bounces off of the paddle to increase the speed of the game (I'm working towards a hit counter), but it doesn't seem to increase the speed at all.
I've tried using --time;
, time--;
, and time = time - 1;
all inside the lessTime
method and by themselves in the if
statement, but none of them remove any amount from the time
variable. Can someone explain why the time
variable isn't affected by either the method or alone inside the if
statement, and also how I can fix it?
Thank you!