Browse Source

Fix random cases where init would error out

Tyler Hallada 6 years ago
parent
commit
12b2fa7400
1 changed files with 15 additions and 3 deletions
  1. 15 3
      src/transport.ts

+ 15 - 3
src/transport.ts

@@ -65,7 +65,12 @@ const initLines = (numLines: number, stations: Station[]): Line[] => {
65 65
     const stationsWithoutConnections = stations.filter(station =>
66 66
       station.connections.length === 0,
67 67
     );
68
-    const centralHub = Station.largestStation(stationsWithoutConnections);
68
+    let centralHub: Station;
69
+    if (stationsWithoutConnections.length > 0) {
70
+      centralHub = Station.largestStation(stationsWithoutConnections);
71
+    } else {
72
+      centralHub = stations[randomInt(0, stations.length - 1)];
73
+    }
69 74
     const line = new Line(`line-${i}`, tinycolor.random());
70 75
     const stationsLeft = stations.slice(0);
71 76
     line.connectStations(centralHub, stationsLeft, [], LINE_CONNECTION_LIMIT);
@@ -203,8 +208,15 @@ const run = () => {
203 208
   const ticker = new PIXI.ticker.Ticker();
204 209
   const graphics = new PIXI.Graphics();
205 210
 
206
-  const stations = initStations(30);
207
-  const lines = initLines(4, stations);
211
+  let stations: Station[] = [];
212
+  let lines: Line[] = [];
213
+  let stationsWithConnections: Station[] = [];
214
+  while (stationsWithConnections.length === 0) {
215
+    // If all stations are too far away to connect, try generating again
216
+    stations = initStations(30);
217
+    lines = initLines(4, stations);
218
+    stationsWithConnections = stations.filter(station => station.connections.length > 0);
219
+  }
208 220
   const trains = initTrains(50, stations);
209 221
 
210 222
   ticker.stop();