-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHawk.java
80 lines (67 loc) · 2.38 KB
/
Hawk.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
/* *****************************************************************************
* Compilation: javac Hawk.java
* Execution: none
* Dependencies: none
*
* Implementation of a hawk for the boid simulator.
*
**************************************************************************** */
import edu.princeton.cs.algs4.Point2D;
import edu.princeton.cs.algs4.Vector;
import edu.princeton.cs.algs4.StdDraw;
public class Hawk {
private Point2D position;
private Vector velocity;
// create a hawk at (x, y) with zero velocity
public Hawk(double x, double y) {
position = new Point2D(x, y);
velocity = new Vector(2);
}
public Point2D position() {
return position;
}
public double x() {
return position.x();
}
public double y() {
return position.y();
}
// compare by y-coordinate, breaking ties by x-coordinate
public int compareTo(Hawk that) {
if (this.position.y() < that.position.y()) return -1;
if (this.position.y() > that.position.y()) return +1;
if (this.position.x() < that.position.x()) return -1;
if (this.position.x() > that.position.x()) return +1;
return 0;
}
// compare by y-coordinate, breaking ties by x-coordinate
public double distanceSquaredTo(Hawk that) {
return position.distanceSquaredTo(that.position);
}
public Vector returnToWorld() {
Vector requestedVector = new Vector(2);
Vector center = new Vector(0.5, 0.5);
Vector myPosition = new Vector(x(), y());
requestedVector = center.minus(myPosition);
return requestedVector;
}
public Vector eatBoid(Boid boid) {
Vector requestedVector = new Vector(2);
Vector boidPosition = new Vector(boid.x(), boid.y());
Vector myPosition = new Vector(x(), y());
requestedVector = boidPosition.minus(myPosition);
return requestedVector;
}
public Vector updatePositionAndVelocity(Boid nearest) {
double x = x() + velocity.cartesian(0);
double y = y() + velocity.cartesian(1);
position = new Point2D(x, y);
Vector desire = eatBoid(nearest).direction().scale(0.0003);
velocity = velocity.plus(desire);
return desire;
}
public void draw() {
StdDraw.setPenColor(StdDraw.RED);
StdDraw.point(x(), y());
}
}