-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCop.java
More file actions
65 lines (54 loc) · 1.86 KB
/
Cop.java
File metadata and controls
65 lines (54 loc) · 1.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
/* Implementation of a Cop.
*
* Wanders around the simulation grid; arrests active Agents.
*
*/
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
public class Cop {
// location in simulation grid
private Cell location;
public Cop(Cell location) {
this.location = location;
this.location.enter(this);
}
// Execute the "move" action for the cop: moves to a random unoccupied
// unoccupied cell in the vicinity; stays at current location if all
// nearby cells are occupied.
public void move() {
Cell target = this.location.getRandomUnoccupiedNeighbor();
if (target != null) {
this.moveTo(target);
}
}
// Move from current location to the given target cell.
private void moveTo(Cell target) {
this.location.leave(this);
target.enter(this);
this.location = target;
}
// Execute the "enforce" action for the cop: searches for all active
// agents in the neighborhood, randomly selects one, and arrests
// them. Does nothing if there are no active agents within signt.
public void enforce() {
// fetch the list of all active agents in neighborhood
ArrayList<Agent> active =
this.location.getActiveAgentsInNeighborhood();
// if there is at least one active agent within sight ...
if (active.size() > 0) {
// ... choose one of them at random
Collections.shuffle(active);
Agent agent = active.get(0);
// move to the active agent's location
Cell target = agent.getLocation();
this.moveTo(target);
// and arrest them
agent.arrest(Rebellion.generateJailTerm());
}
}
// Getter: returns cop location
public Cell getLocation(){
return this.location;
}
}