-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJumper.java
86 lines (79 loc) · 2.33 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
/*
* AP(r) Computer Science GridWorld Case Study:
* Copyright(c) 2005-2006 Cay S. Horstmann (http://horstmann.com)
*
* This code is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* @author Cay Horstmann
*/
package info.gridworld.actor;
import info.gridworld.grid.Grid;
import info.gridworld.grid.Location;
import java.awt.Color;
/**
* A <code>Bug</code> is an actor that can move and turn. It drops flowers as
* it moves. <br />
* The implementation of this class is testable on the AP CS A and AB exams.
*/
public class Jumper extends Bug
{
/**
* Constructs a red bug.
*/
public Jumper()
{
setColor(Color.GREEN);
}
/**
* Constructs a bug of a given color.
* @param bugColor the color for this bug
*/
public Jumper(Color bugColor)
{
setColor(bugColor);
}
/**
* 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
turn;
}
/**
* 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
}
}