-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJumper.java
92 lines (82 loc) · 2.09 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
83
84
85
86
87
88
89
90
91
92
//
// Period 9
// HW #33
// 2014-04-28
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 bug of a given color.
* @param bugColor the color for this bug
*/
public Jumper(Color bugColor)
{
setColor(bugColor);
}
/**
* Moves if it can move, turns otherwise.
*/
public void act()
{
if (canMove())
move();
else
turn();
}
/**
* Turns the bug 45 degrees to the right without changing its location.
*/
public void turn()
{
setDirection(getDirection() + Location.HALF_RIGHT);
}
/**
* Moves the bug forward, putting a flower into the location it previously
* occupied.
*/
public void move()
{
Grid<Actor> gr = getGrid();
if (gr == null)
return;
Location loc = getLocation();
Location next = loc.getAdjacentLocation(getDirection());
next = next.getAdjacentLocation(getDirection());
if (gr.isValid(next))
moveTo(next);
else
removeSelfFromGrid();
Flower flower = new Flower(getColor());
flower.putSelfInGrid(gr, loc);
}
/**
* Tests whether this bug can move forward into a location that is empty or
* contains a flower.
* @return true if this bug can move.
*/
public boolean canMove()
{
Grid<Actor> gr = getGrid();
if (gr == null)
return false;
Location loc = getLocation();
Location next = loc.getAdjacentLocation(getDirection());
next = next.getAdjacentLocation(getDirection());
if (!gr.isValid(next))
return false;
Actor neighbor = gr.get(next);
return (neighbor == null) || (neighbor instanceof Flower);
// ok to move into empty location or onto flower
// not ok to move onto any other actor
}
}