Generate walls procedurally at runtime

This commit is contained in:
Thibaud Gasser 2018-10-12 12:36:44 +02:00
parent 2031291d00
commit 96f120d943
2 changed files with 13 additions and 1 deletions

View File

@ -69,7 +69,7 @@ class AStarSearch {
// If the node is a wall, don't add it to the list // If the node is a wall, don't add it to the list
if (grid.get(loc).isWall()) continue; if (grid.get(loc).isWall()) continue;
// Don't overflow off the grid // Don't overflow off the grid
if (loc.x > gridSize.width || loc.y > gridSize.height) continue; if (loc.x >= gridSize.width || loc.y >= gridSize.height || loc.x < 0 || loc.y < 0) continue;
node.setLoc(loc); node.setLoc(loc);
neighbors.add(node); neighbors.add(node);
} }

View File

@ -29,6 +29,7 @@ public class App extends JFrame {
private App() throws HeadlessException { private App() throws HeadlessException {
super("Pathfinding"); super("Pathfinding");
grid = new Grid(ROWS, COLS, CELL_SIZE); grid = new Grid(ROWS, COLS, CELL_SIZE);
generateWalls();
setupInterface(); setupInterface();
pack(); pack();
setVisible(true); setVisible(true);
@ -77,6 +78,16 @@ public class App extends JFrame {
getContentPane().add(gridPane); getContentPane().add(gridPane);
} }
/**
* Generate walls randomly at runtime
*/
private void generateWalls() {
for (Cell cell : grid) {
final double wallProb = (Math.random() * ((0 - 0.2) + 1));
if (Math.random() < wallProb) grid.setWall(cell.getPos(), true);
}
}
private void setWallPlacing(JMenuItem placeWallItem) { private void setWallPlacing(JMenuItem placeWallItem) {
// Invert selection state // Invert selection state
placeWallItem.setSelected(!placeWallItem.isSelected()); placeWallItem.setSelected(!placeWallItem.isSelected());
@ -100,6 +111,7 @@ public class App extends JFrame {
startNode = null; startNode = null;
endNode = null; endNode = null;
grid.clear(); grid.clear();
generateWalls();
} }
private void doCancel() { private void doCancel() {