Hacker News new | past | comments | ask | show | jobs | submit login

Hey, good work! What algorithm did you use?



Thanks! You can see the code here: https://repl.it/@EdwardCunningh2/Random-Roads

It's not especially clever:

1. I define a set of possible moves (eg. straight ahead, left turn, junction, etc). One possible move is a dead-end, which looks a bit like a house in my interpretation.

2. Each move is assigned a relative weight (eg. continuing straight ahead 10x more likely than turning left).

3. Each iteration, for each of the roads under construction, a random move is selected. Some moves are impossible (based on other roads already drawn on the map) and so it will ensure not to select one that would result in a collision. At worst, it will terminate the road with a dead-end.

4. Repeat forever, until every road has terminated in a dead-end.

Most of the script itself is dealing with the rendering logic. To avoid collisions I maintain a 2D array of all visited points.


Nice! My first page load I got a single line that stopped at the first point. Is that just able to happen?


Yes, there's nothing to prevent very small maps like what you saw - even ones that terminate with a dead-end before a road has been drawn (eg. https://random-roads--edwardcunningh2.repl.co/#1592758760947).

I considered adding logic to prevent this, but have decided to embrace it as a feature rather than a bug.

I quite like some of the small-ish maps, like this: https://random-roads--edwardcunningh2.repl.co/#1592759118928


Kind of reminds me of the algorithm to create a maze: https://medium.com/swlh/how-to-create-a-maze-with-javascript...


Not the author, but the algorithm is at

https://random-roads--edwardcunningh2.repl.co/script.js




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: