-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBouncingBall.java
More file actions
45 lines (38 loc) · 1.18 KB
/
BouncingBall.java
File metadata and controls
45 lines (38 loc) · 1.18 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
public class BouncingBall {
public static void main(String[] args) throws InterruptedException {
final int ROWS = 10;
final int COLS = 20;
int ballRow = 0;
int ballCol = 0;
int velocityRow = 1;
int velocityCol = 1;
while (true) {
// Clear console (simulate by printing many new lines)
for (int i = 0; i < 50; i++) {
System.out.println();
}
// Print the grid with ball
for (int r = 0; r < ROWS; r++) {
for (int c = 0; c < COLS; c++) {
if (r == ballRow && c == ballCol) {
System.out.print("*");
} else {
System.out.print(".");
}
}
System.out.println();
}
// Update position
ballRow += velocityRow;
ballCol += velocityCol;
// Bounce on wall
if (ballRow == 0 || ballRow == ROWS - 1) {
velocityRow *= -1;
}
if (ballCol == 0 || ballCol == COLS - 1) {
velocityCol *= -1;
}
Thread.sleep(100); // Delay for animation
}
}
}