-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBall.java
More file actions
119 lines (86 loc) · 2.09 KB
/
Ball.java
File metadata and controls
119 lines (86 loc) · 2.09 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
public class Ball {
public int x, y, width = 25, height = 25;
public int motionX, motionY;
public Random random;
public int amountOfHits;
private Pong pong;
public Ball(Pong pong) {
this.pong = pong;
this.random = new Random();
spawn();
}
public void update(Paddle paddle1, Paddle paddle2) {
int speed = 5;
this.x += motionX * speed;
this.y += motionY * speed;
if (this.y + height - motionY > pong.height || this.y + motionY < 0) {
if (this.motionY < 0) {
this.y = 0;
this.motionY = random.nextInt(4);
if (motionY == 0) {
motionY = -1;
}
} else {
this.y = pong.height - height;
this.motionY = -random.nextInt(4);
if (motionY == 0) {
motionY = -1;
}
}
}
if (checkCollision(paddle1) == 1) {
this.motionX = 1 + (amountOfHits / 5);
this.motionY = -2 + random.nextInt(4);
if (motionY == 0) {
motionY = -1;
}
amountOfHits++;
} else if (checkCollision(paddle2) == 1) {
this.motionX = -1 - (amountOfHits / 5);
this.motionY = -2 + random.nextInt(4);
if (motionY == 0) {
motionY = -1;
}
amountOfHits++;
}
if (checkCollision(paddle1) == 2) {
paddle2.score++;
spawn();
} else if (checkCollision(paddle2) == 2) {
paddle1.score++;
spawn();
}
}
public void spawn() {
amountOfHits = 0;
this.x = pong.width / 2 - this.width / 2;
this.y = pong.height / 2 - this.height / 2;
this.motionY = -2 + random.nextInt(4);
if (motionY == 0) {
motionY = 1;
}
if (random.nextBoolean()) {
motionX = 1;
} else {
motionX = -1;
}
}
public int checkCollision(Paddle paddle) {
if (this.x < paddle.x + paddle.width && this.x + width > paddle.x
&& this.y < paddle.y + paddle.height
&& this.y + height > paddle.y) {
return 1;
} else if ((paddle.x > x && paddle.paddleNumber == 1)
|| (paddle.x < x - width && paddle.paddleNumber == 2)) {
return 2;
}
return 0; // nothing
}
public void render(Graphics g) {
g.setColor(Color.WHITE);
g.fillOval(x, y, width, height);
}
}