-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSand.java
More file actions
82 lines (72 loc) · 2.86 KB
/
Sand.java
File metadata and controls
82 lines (72 loc) · 2.86 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
import java.awt.*;
public class Sand implements Constants {
private int x;
private int y;
private Color color;
public Sand(int x, int y) {
this.x = x;
this.y = y;
this.color = colors[random.nextInt(colors.length)];
}
public void draw(Graphics g, int x, int y) {
g.setColor(color);
g.fillRect(x, y, Constants.SIZE, Constants.SIZE);
}
public void move() {
boolean grainBelow = false;
boolean belowRightFree = true;
boolean belowLeftFree = true;
// Check if there is a grain below
for (Sand grain : App.getGrains()) {
if (grain.getX() == this.x && grain.getY() == this.y + Constants.SIZE) {
grainBelow = true;
break;
}
}
// Check if below right position is free
for (Sand grain : App.getGrains()) {
if (grain.getX() == this.x + Constants.SIZE && grain.getY() == this.y + Constants.SIZE) {
belowRightFree = false;
break;
}
}
// Check if below left position is free
for (Sand grain : App.getGrains()) {
if (grain.getX() == this.x - Constants.SIZE && grain.getY() == this.y + Constants.SIZE) {
belowLeftFree = false;
break;
}
}
// Move to the right if grain below and below right position is free
if (grainBelow && belowRightFree && belowLeftFree) {
int randomChoice = random.nextInt(2); // Randomly choose 0 or 1
if (randomChoice == 0 && this.y != Constants.HEIGHT * Constants.SIZE - Constants.SIZE && this.x != Constants.WIDTH * Constants.SIZE - Constants.SIZE) {
this.y += Constants.SIZE;
this.x += Constants.SIZE;
} else if (randomChoice == 1 && this.y != Constants.HEIGHT * Constants.SIZE - Constants.SIZE && this.x != 0) {
this.y += Constants.SIZE;
this.x -= Constants.SIZE;
}
} else if (grainBelow && belowRightFree) {
if (this.y != Constants.HEIGHT * Constants.SIZE - Constants.SIZE && this.x != Constants.WIDTH * Constants.SIZE - Constants.SIZE) {
this.y += Constants.SIZE;
this.x += Constants.SIZE;
}
} else if (grainBelow && belowLeftFree) {
if (this.y != Constants.HEIGHT * Constants.SIZE - Constants.SIZE && this.x != 0) {
this.y += Constants.SIZE;
this.x -= Constants.SIZE;
}
} else if (!grainBelow) { // Only move down if there is no grain below
if (this.y != Constants.HEIGHT * Constants.SIZE - Constants.SIZE) {
this.y += Constants.SIZE;
}
}
}
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
}