/
Jumper.java
82 lines (74 loc) · 1.78 KB
/
Jumper.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
package info.gridworld.actor;
import info.gridworld.grid.Grid;
import info.gridworld.grid.Location;
import java.awt.Color;
public class Jumper extends Actor
{
/**
* Constructs a red jumper.
*/
public Jumper()
{
setColor(Color.RED);
}
/**
* Constructs a jumper of a given color.
* @param jumperColor the color for this jumper
*/
public Jumper(Color jumperColor)
{
setColor(jumperColor);
}
/**
* Moves if it can move, turns otherwise.
*/
public void act()
{
if (canMove()) {
move();
move();
}
else
turn();
}
/**
* Turns the jumper 45 degrees to the right without changing its location.
*/
public void turn()
{
setDirection(getDirection() + Location.HALF_RIGHT);
}
/**
* Moves the jumper forward
*/
public void move()
{
Grid<Actor> gr = getGrid();
if (gr == null)
return;
Location loc = getLocation();
Location next = loc.getAdjacentLocation(getDirection());
if (gr.isValid(next))
moveTo(next);
else
removeSelfFromGrid();
}
/**
* Tests whether this jumper can move forward into a location that is empty
* @return true if this jumper can move.
*/
public boolean canMove()
{
Grid<Actor> gr = getGrid();
if (gr == null)
return false;
Location loc = getLocation();
Location next = loc.getAdjacentLocation(getDirection());
if (!gr.isValid(next))
return false;
Actor neighbor = gr.get(next);
return (neighbor == null);
// ok to move into empty location
// not ok to move onto any other actor
}
}