I’m having trouble with my Pong game AI and hope someone can help me figure this out.
I wrote some code for controlling the computer paddle in my LWJGL Pong game. The basic version works perfectly - the paddle follows the ball and stops correctly at screen edges:
public void controlPaddle(int ballPosition, int SCREEN_HEIGHT, int paddleSize) {
if (ballPosition < this.position + height / 2) {
if (this.position <= 0) {
System.out.println("Hit top wall");
position = 0;
} else {
position -= 2;
}
}
if (ballPosition > this.position + height / 2) {
if (this.position >= SCREEN_HEIGHT - paddleSize) {
System.out.println("Hit bottom wall");
position = SCREEN_HEIGHT - paddleSize;
} else {
position += 2;
}
}
}
This works great. The paddle moves up and down, hits the boundaries, prints messages, and stays within screen limits.
But when I try to add random speed variation, everything breaks:
public void controlPaddle(int ballPosition, int SCREEN_HEIGHT, int paddleSize) {
if (ballPosition < this.position + height / 2) {
if (this.position <= 0) {
System.out.println("Hit top wall");
position = 0;
} else {
if(random.nextInt(2)+1 == 1){
position -= 2;
}else{
position -= 3;
}
}
}
if (ballPosition > this.position + height / 2) {
if (this.position >= SCREEN_HEIGHT - paddleSize) {
System.out.println("Hit bottom wall");
position = SCREEN_HEIGHT - paddleSize;
} else {
position += 2;
}
}
}
With this change, the paddle works once but then completely ignores boundaries and moves off screen. The console shows negative positions and values way bigger than screen height. I just wanted to make the AI sometimes move faster or slower for variety.
I thought maybe nested if statements were the problem so I tried restructuring but got the same result. What am I missing here?