/
Actor.java
147 lines (101 loc) · 2.7 KB
/
Actor.java
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
import java.awt.Dimension;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
public abstract class Actor implements Runnable {
protected int zIndex;
private JLabel image;
public static World world;
protected Cell cell;
protected boolean alive = true;
private int sleepTime;
public Actor(ImageIcon img, int sleep) {
image = new JLabel(img);
image.setSize(new Dimension(50,50));
sleepTime = sleep;
}
public void setCell(Cell c) {
cell = c;
}
public int getZIndex() {
return zIndex;
}
public JLabel getImage() {
return image;
}
public abstract Move move(MoveOptions options);
protected void makeMove() {
MoveOptions options = Actor.world.getMoveOptions(cell);
boolean moved = false;
while(!moved) {
Move move = move(options);
if(move == null) return;
Cell lock1, lock2;
Move.Direction direction = move.getMove();
Cell center = options.getOption(Move.Direction.CENTER),
newCell = options.getOption(direction);
switch(direction) {
case DOWN:
lock1 = center;
lock2 = newCell;
break;
case CENTER:
lock1 = center;
lock2 = center;
newCell = center;
default:
lock1 = newCell;
lock2 = center;
}
synchronized(lock1) {
synchronized(lock2) {
if(alive) {
// if the new location already has an object of the same class as us find another set of moves.
if(newCell != center && newCell.hasClass(this.getClass())) {
continue;
}
moved = true;
// kill to actor on the cell you are moving to
// this can be "this", as in a flower has reached the end of its life
Class<?> toKill = move.getClassToConsume();
if(toKill != null) newCell.kill(toKill);
if(newCell != center) {
center.remove(this.getClass());
newCell.add(this);
}
cell = newCell;
if(this instanceof HasLife) {
Class<?> kill = ((HasLife)this).getClassToKill(cell);
if(kill != null) {
cell.kill(kill);
}
}
Actor toCreate = move.getActorToCreate();
if(toCreate != null) {
center.add(toCreate);
world.startActor(toCreate);
}
world.redrawCell(newCell);
world.redrawCell(center);
} else {
moved = true;
}
}
}
}
}
public void kill() {
alive = false;
}
public void run() {
//Thread thisThread = Thread.currentThread();
while(alive && world.running) {
try {
if(!world.paused) {
makeMove();
}
Thread.sleep(sleepTime);
} catch (InterruptedException e){}
}
}
public abstract boolean canInhabitSpace(Cell cell);
}