BreadthFirstSearch/extra.pde
2022-05-15 16:36:38 +02:00

112 lines
2.7 KiB
Plaintext

class Mover {
PVector position;
int steps;
Mover(float x, float y, int s) {
position = new PVector(x, y);
steps = s;
}
boolean isNextOf(Mover other) {
return ((other.steps == steps-1) && maxDistFrom(other, scl) && other.canMoveTo(position));
}
boolean maxDistFrom(Mover other, float maxDist) {
return (PVector.dist(position, other.position) <= maxDist);
}
Mover copy() {
return new Mover(position.x, position.y, steps);
}
boolean equals(Mover other) {
return pointEquals(position, other.position);
}
boolean canMoveTo(PVector newPos) {
if ((newPos.x < 0 || newPos.x > /*height*/width) || (newPos.y < 0 || newPos.y > height)) { return false; }
final Wall path = new Wall(position, newPos);
boolean noIntersects = true;
for (Wall w : walls) {
if (w.intersect(path)) {
noIntersects = false;
break;
}
}
return noIntersects;
}
ArrayList<Mover> getNeighbors() {
ArrayList<Mover> neighbors = new ArrayList<Mover>();
for (int i = 0; i < 4; i++) {
final PVector converted = convertDirection(i);
if (converted == null) { continue; }
final PVector newPosition = PVector.add(position, converted);
if (canMoveTo(newPosition)) {
neighbors.add(new Mover(newPosition.x, newPosition.y, steps+1));
}
}
return neighbors;
}
}
PVector convertDirection(int direction) {
if (direction < 0 || direction > 3) { return null; }
switch (direction) {
case 0:
return new PVector(-scl, 0);
case 1:
return new PVector(scl, 0);
case 2:
return new PVector(0, -scl);
case 3:
return new PVector(0, scl);
}
return null;
}
class Wall {
PVector start, end;
Wall(PVector a, PVector b) {
start = new PVector(a.x, a.y);
end = new PVector(b.x, b.y);
}
void show() {
line(start.x, start.y, end.x, end.y);
}
boolean intersect(Wall other) {
final PVector a = start.copy();
final PVector b = end.copy();
final PVector c = other.start.copy();
final PVector d = other.end.copy();
if ((pointEquals(a,c) && pointEquals(b,d)) || (pointEquals(a,d) && pointEquals(b,c))) { return true; }
final float t = (a.x-c.x) * (c.y-d.y) - (a.y-c.y) * (c.x-d.x);
final float u = (b.x-a.x) * (a.y-c.y) - (b.y-a.y) * (a.x-c.x);
final float D = (a.x-b.x) * (c.y-d.y) - (a.y-b.y) * (c.x-d.x);
if (D == 0) { return false; }
final float td = t / D;
final float ud = u / D;
if (td >= 0 && td <= 1 && ud >= 0 && ud <= 1) { return true; }
return false;
}
}
boolean pointEquals(PVector A, PVector B) {
return (A.x == B.x && A.y == B.y);
}