feat: add 4-connected Bresenham pathfinding algorithm

This commit is contained in:
punchready 2021-06-01 18:30:32 +02:00
parent 8e6f61a665
commit 2f45e2b772
2 changed files with 65 additions and 1 deletions

View File

@ -13,6 +13,7 @@ import uulm.teamname.marvelous.gamelibrary.requests.RequestType;
import java.awt.*;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
@ -911,7 +912,7 @@ class GameLogic {
}
}
}
//
//TODO: implement thanos ai
}
@ -1074,4 +1075,39 @@ class GameLogic {
return result;
}
//https://stackoverflow.com/a/5187612
public static ArrayList<IntVector2> Bresenham4Connected(IntVector2 a, IntVector2 b) {
ArrayList<IntVector2> result = new ArrayList<>();
int x0 = a.getX();
int y0 = a.getY();
int x1 = b.getX();
int y1 = b.getY();
int dx = Math.abs(x1 - x0);
int dy = Math.abs(y1 - y0);
int ix = x0 < x1 ? 1 : -1;
int iy = y0 < y1 ? 1 : -1;
int e = 0;
for(int i = 0; i < dx + dy; i++) {
result.add(new IntVector2(x0, y0));
int e1 = e + dy;
int e2 = e - dx;
if(Math.abs(e1) < Math.abs(e2)) {
x0 += ix;
e = e1;
}else {
y0 += iy;
e = e2;
}
}
result.add(b);
return result;
}
}

View File

@ -196,6 +196,34 @@ class GameLogicTest {
), new HashSet<>(Arrays.asList(result3)), "Tilted lines work correctly");
}
@Test
void testPathfind() {
int size = 20;
IntVector2 a = new IntVector2(Math.abs(randomIntegers.next() % size), Math.abs(randomIntegers.next() % size));
IntVector2 b = new IntVector2(Math.abs(randomIntegers.next() % size), Math.abs(randomIntegers.next() % size));
ArrayList<IntVector2> result = GameLogic.Bresenham4Connected(a, b);
StringBuilder sb = new StringBuilder();
for(int y = 0; y < size; y++) {
for(int x = 0; x < size; x++) {
IntVector2 pos = new IntVector2(x, y);
if(pos.equals(a)) {
sb.append("A ");
}else if(pos.equals(b)) {
sb.append("B ");
}else if(result.contains(pos)) {
sb.append("o ");
}else {
sb.append(". ");
}
}
sb.append("\n");
}
System.out.println(sb.toString());
}
// @Provide("gamestate")
// Arbitrary<GameState> gamestate() {