-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPaddle.java
More file actions
60 lines (54 loc) · 1.82 KB
/
Copy pathPaddle.java
File metadata and controls
60 lines (54 loc) · 1.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* This class represents a Paddle in the Ping Pong game.
* It handles the movement and controls for the paddle.
@authors (Rupert & Raymond Van Niekerk)
* @student Numbers (222894237 & 221154469)
* @version (1.0)
*/
public class Paddle extends Actor {
private int speed = 5;
public boolean isPlayerOne; // Determines if this is player one's paddle
public Paddle(boolean isPlayerOne) {
// Constructor to set if this paddle belongs to player one
this.isPlayerOne = isPlayerOne;
}
public void act() {
// Act method called in every cycle to handle movement
handleMovement();
}
private void handleMovement() {
// Handle the movement of the paddle based on key presses
int halfHeight = getImage().getHeight() / 2;
int minY = halfHeight;
int maxY = getWorld().getHeight() - halfHeight;
int newY = getY();
if (newY < minY) {
newY = minY;
} else if (newY > maxY) {
newY = maxY;
}
setLocation(getX(), newY);
if (isPlayerOne) {
// Controls for player one
if (Greenfoot.isKeyDown("w")) {
setLocation(getX(), getY() - speed);
}
if (Greenfoot.isKeyDown("s")) {
setLocation(getX(), getY() + speed);
}
} else {
// Controls for player two
if (Greenfoot.isKeyDown("up")) {
setLocation(getX(), getY() - speed);
}
if (Greenfoot.isKeyDown("down")) {
setLocation(getX(), getY() + speed);
}
}
}
public void setSpeed(int newSpeed) {
// Set a new speed for the paddle
speed = newSpeed;
}
}