-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.html
More file actions
2340 lines (2108 loc) · 135 KB
/
index.html
File metadata and controls
2340 lines (2108 loc) · 135 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Planned Community</title>
<!--
(C) 2020 Electric Sheep Co. <https://electricsheep.co>
Icons by Justin Arnold <https://zeromatrix.itch.io/rpgiab-icons>
Built with TileMapTool <https://tmt.rpjios.com>
This game is entirely self-contained & without external depedencies:
save this file as "plain HTML" for offline play.
-->
<script>
/* A 2D array (matrix) with one slot for each tile on the map. Each leaf "tile" object contains
three properties representing the three layers of the map. The values are objects with keys "type",
"sprite", and other type-specific optional keys. The sprite values are (unless otherwise specified)
string keypaths delimited by forward-slash, i.e. "mapName/groupName/tileName". "null" is the correct
"unset"/"zero" value for these fields, *not* "undefined". The fields themselves are specified as follows:
- "gnd" is the ground layer, which is set once in gamemapInit() and never changes thereafter.
- "col" is the collision layer, where all player-created objects (roads and zones) live: this is
the only player-mutable layer. Zones do not use image sprites but rather canvas styles as defined
in `zoneColors`, below. Accordingly, the `sprite` key for zone objects is *just* this style string,
not a keypath.
- "sim" is the simulation layer, where all simulation-created objects are placed. these fields
*must include* the group in the tile keypath.
*/
const gamemap = [];
// in tile-space this is: 20x20, 25x25, 30x30
const allowedMapDims = [320, 400, 480];
// tile object types
const [t_Ground, t_Empty, t_Road, t_Zone, t_Home, t_Employer, t_Traffic] = [-1, 0, 1, 2, 3, 4, 5];
// cardinal direction bitmaps for checkAndSetRoads
const [b_N, b_S, b_E, b_W] = [0b1000, 0b0100, 0b0010, 0b0001];
// zone types; values must match the icon indexes for those zones in player mode
const [z_Res, z_Com, z_Ind, z_Unz] = [2, 3, 4, 5];
// values are appplied to .strokeStyle or .fillStyle respectively, not as CSS styles
const zoneColors = {
[z_Res]: { stroke: "rgb(32, 92, 32)", fill: "rgb(128, 255, 128, 0.4)" },
[z_Com]: { stroke: "rgb(0, 64, 128)", fill: "rgb(128, 200, 255, 0.4)" },
[z_Ind]: { stroke: "rgb(128, 28, 28)", fill: "rgb(255, 212, 128, 0.4)" },
[z_Unz]: { stroke: "rgb(200, 0, 0)", fill: "rgb(100, 100, 100, 0.4)" }
};
// various game parameters
const SIMUGINE_TICK = 300;
const Z_IND_EMPS_PER = 3;
const POP_GROWTH_HAPPINESS_REQD = 0.75;
const WORKING_POP_WEEKDAY_WORK_PRCNT = 0.85;
const WORK_TAKE_SCENIC_ROUTE_CHANCE = 0.75;
const WEEKEND_OUTING_POP_PRCNT_PERDAY = 0.50;
const ENDGAME_SAMPLE_NUM_WEEKS = 4;
const GROWTH_WIN_SIZE = 28; // in ticks, so four "weeks"
const TRAFFIC_FINAL_SCORE_MULT = 100;
const UNFILLED_JOBS_SCORE_DIV = 10;
const RP_HUER_MULT = 3;
/***** [MARK] Setup & init *****/
const iconListeners = [];
const mappedMaps = {};
const roadPathsCache = {};
const dirMods = {
[b_N]: ['y', -1],
[b_S]: ['y', 1],
[b_E]: ['x', 1],
[b_W]: ['x', -1]
};
let cDIM, simugine_handle, DEBUG = false, canvasListeners = {};
// "main()"
window.addEventListener('load', (_) => {
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const imgmap = document.getElementById('tilemap');
mappedMaps.tiles = { img: imgmap, map: tilemap };
mappedMaps.icons = { img: document.getElementById('iconmap'), map: iconmap };
mappedMaps.buildings = { img: document.getElementById('buildingsmap'), map: buildingsmap };
gamemapInit(canvas, ctx, imgmap);
gameInit(canvas, ctx, imgmap);
});
function gamemapInit(canvas, ctx, imgmap) {
cDIM = { width: canvas.width, height: canvas.height };
gamemap.length = 0;
try {
if (cDIM.width % DIM + cDIM.height % DIM > 0) {
throw new Error(`canvas dims ${cDIM} not a multiple of tile dim ${DIM}`);
}
//super simple gamemap init... TODO: use perlin noise!
for (let row = 0; row < cDIM.height / DIM; row++) {
gamemap.push(Array.from({ length: cDIM.height / DIM }, (_) => ({
gnd: { type: t_Ground, sprite: 'tiles/ground/grass_blank_1' },
col: { type: t_Empty },
sim: { type: t_Empty }
})));
}
render(ctx, imgmap);
} catch (e) {
console.log(e);
}
}
function gameInit(canvas, ctx, imgmap) {
let curMapDimIdx = 1;
//TODO: disable (greyscale filter over, disallow clicks) plus/minus when
//at limit of allowedMapDims
const overlay = document.getElementById('overlay_canvas');
setIcon(2, 'map_plus', 'increase map size', () => {
if (curMapDimIdx + 1 < allowedMapDims.length) {
overlay.width = overlay.height = canvas.width = canvas.height = allowedMapDims[++curMapDimIdx];
gamemapInit(canvas, ctx, imgmap);
}
});
setIcon(3, 'map_minus', 'decrease map size', () => {
if (curMapDimIdx - 1 >= 0) {
overlay.width = overlay.height = canvas.width = canvas.height = allowedMapDims[--curMapDimIdx];
gamemapInit(canvas, ctx, imgmap);
}
});
setIcon(4, 'green_check', 'start community planning...', () => enterPlayerMode(canvas, ctx, imgmap));
}
function setIcon(iconIdx, iconName, tooltipText, clickListener) {
const iconmapEle = document.getElementById('iconmap');
const icon = document.getElementById(`tb_icon${iconIdx}`);
if (!icon) {
throw new Error(`bad icon ${iconIdx} ${iconName}`);
}
// remove any previous listeners as soon as we know we have a valid `icon` element
if (iconListeners[iconIdx]) {
const listenersMap = iconListeners[iconIdx];
Object.keys(listenersMap).forEach((evName) => {
icon.removeEventListener(evName, listenersMap[evName]);
listenersMap[evName] = undefined;
})
}
// clear tooltip if only iconIdx is given
if (!iconName && !tooltipText && !clickListener) {
icon.getContext('2d').clearRect(0, 0, cDIM.width, cDIM.height);
icon.style.display = 'none';
document.getElementById(`tb_icon_tt${iconIdx}`).style.display = 'none';
return;
}
icon.getContext('2d')
.drawImage(iconmapEle,
iconmap.icon[iconName].src.topLeft.x,
iconmap.icon[iconName].src.topLeft.y,
IDIM, IDIM, 0, 0, IDIM, IDIM);
icon.style.display = 'block';
if (clickListener) {
iconListeners[iconIdx] = { click: (e) => clickListener(icon, e) };
icon.addEventListener('click', iconListeners[iconIdx].click);
}
if (tooltipText && tooltipText.length) {
const tt = document.getElementById(`tb_icon_tt${iconIdx}`);
tt.innerText = tooltipText;
tt.style.display = 'block';
}
}
function selectIcon(idx) {
for (let i = 1; i <= 7; i++) {
document.getElementById(`tb_icon${i}`).style.border = i === idx ? '2px solid var(--select_icon)' : '0';
}
};
/***** [MARK] Rendering *****/
function clearCanvas(ctx) {
ctx.imageSmoothingEnabled = false;
ctx.clearRect(0, 0, cDIM.width, cDIM.height);
}
function render(ctx, imgmap, renderOpts) {
clearCanvas(ctx);
clearCanvas(document.getElementById('overlay_canvas').getContext('2d'));
drawLayers(ctx, imgmap, renderOpts);
}
function drawLayers(ctx, imgmap, renderOpts) {
const overlayCtx = document.getElementById('overlay_canvas').getContext('2d');
const d_2 = DIM / 2;
gamemap.forEach((gmRow, tileX) => {
gmRow.forEach((tileSpec, tileY) => {
const boundDrawTile = drawTile.bind(null, ctx, imgmap, renderOpts, tileX, tileY);
boundDrawTile(tileSpec.gnd);
if (tileSpec.col.type > t_Empty) {
boundDrawTile(tileSpec.col);
}
if (tileSpec.sim.type > t_Empty) {
boundDrawTile(tileSpec.sim);
}
if (DEBUG) {
const tileObj = tileSpec.sim;
const curCenter = [tileX * DIM + d_2, tileY * DIM + d_2];
const drawToWithStyle = (to, style) => {
overlayCtx.strokeStyle = style;
overlayCtx.beginPath();
overlayCtx.moveTo(...curCenter);
overlayCtx.lineTo(to.x * DIM + d_2, to.y * DIM + d_2);
overlayCtx.stroke();
};
if (tileX === 0 || tileY === 0) {
overlayCtx.fillStyle = 'red';
overlayCtx.font = '7pt monospace';
overlayCtx.fillText(`${tileX === 0 ? tileY : tileX}`, tileX * DIM, tileY * DIM + d_2);
}
if (tileObj.type === t_Home && tileObj.employer) {
drawToWithStyle(tileObj.employer, 'rgba(100, 100, 100, 0.1)');
}
if (tileObj.paths) {
tileObj.paths.all.forEach((p) => drawToWithStyle(p.roadTile, 'rgba(255, 0, 0, 0.15)'));
drawToWithStyle(tileObj.paths.shortest.roadTile, 'rgba(255, 0, 0, 0.25)');
}
}
});
});
}
function drawTile(ctx, imgmap, renderOpts, tileX, tileY, tileObj) {
if (tileObj.type === t_Zone) {
ctx.fillStyle = tileObj.sprite;
ctx.fillRect(tileX * DIM, tileY * DIM, DIM, DIM);
return;
}
if (tileObj.type === t_Traffic) {
if (tileObj.cars > 0) {
const overlayCtx = document.getElementById('overlay_canvas').getContext('2d');
overlayCtx.fillStyle = `rgb(255, 0, 0, ${Math.min(0.95, tileObj.cars / renderOpts.maxPop)})`;
overlayCtx.fillRect(tileX * DIM, tileY * DIM, DIM, DIM);
}
return;
}
let [mapName, groupName, imgName] = tileObj.sprite.split('/');
const curMap = mappedMaps[mapName];
if (!curMap.img || !curMap.map || !curMap.map[groupName] || !curMap.map[groupName][imgName]) {
throw new Error(`bad sprite def @(${tileX},${tileY}): '${JSON.stringify(tileObj)}'`);
}
ctx.drawImage(curMap.img,
curMap.map[groupName][imgName].src.topLeft.x,
curMap.map[groupName][imgName].src.topLeft.y,
DIM, DIM, tileX * DIM, tileY * DIM, DIM, DIM);
}
function setCanvasListeners(canvas, newListeners) {
Object.keys(canvasListeners).forEach(ev => canvas.removeEventListener(ev, canvasListeners[ev]));
Object.keys(newListeners).forEach((ev) => canvas.addEventListener(ev, newListeners[ev]));
canvasListeners = newListeners;
};
function checkCardDirsForColType(tX, tY, colType) {
const checkDir = (x, y, setMaskIfExists, curMask) => {
if (x >= 0 && x < gamemap.length && y >= 0 && y < gamemap[x].length && gamemap[x][y].col.type === colType) {
curMask |= setMaskIfExists;
}
return curMask;
}
return checkDir(tX - 1, tY, b_W,
checkDir(tX + 1, tY, b_E,
checkDir(tX, tY - 1, b_N,
checkDir(tX, tY + 1, b_S, 0))));
}
// re-check all tiles with .col set to a road for their connections and re-adjust if necessary
// uses a bitmask for each road tile to describe its connections to other road tiles
function checkAndSetRoads(tileX, tileY) {
const mods = [-1, 0, 1];
mods.map(n => tileX + n).forEach((tX) => {
mods.map(n => tileY + n).forEach((tY) => {
// skip any tile that either doesn't not have a collision object at all, or
// does not have a 'roads' object in the collision layer
if (!(tX in gamemap) || !(tY in gamemap[tX]) || gamemap[tX][tY].col.type !== t_Road) {
return;
}
let connMask = checkCardDirsForColType(tX, tY, t_Road);
let roadTile;
switch (connMask) {
case (b_E | b_W | b_N):
roadTile = 'intersection_3s';
break;
case (b_E | b_W | b_S):
roadTile = 'intersection_3n';
break;
case (b_N | b_S | b_E):
roadTile = 'intersection_3w';
break;
case (b_N | b_S | b_W):
roadTile = 'intersection_3e';
break;
case (b_N | b_E):
roadTile = 'corner_sw';
break;
case (b_N | b_W):
roadTile = 'corner_se';
break;
case (b_S | b_E):
roadTile = 'corner_nw';
break;
case (b_S | b_W):
roadTile = 'corner_ne';
break;
case b_N:
case b_S:
case (b_N | b_S):
roadTile = 'single_ns';
break;
case b_E:
case b_W:
case (b_E | b_W):
roadTile = 'single_ew';
break;
default:
roadTile = 'intersection_4'; //TODO: maybe a blank road tile instead?
}
gamemap[tX][tY].col = { type: t_Road, sprite: `tiles/roads/${roadTile}` };
});
});
}
/***** [MARK] Player mode *****/
function enterPlayerMode(canvas, ctx, imgmap) {
const tileCoordsFromEvent = (e) => [Math.floor(e.offsetX / DIM), Math.floor(e.offsetY / DIM)];
const setRoadMode = () => {
selectIcon(1);
const overlay = document.getElementById('overlay_canvas');
const overlayCtx = overlay.getContext('2d');
let dragAdder;
const maybeXTileAt = (conditionFunc, successFunc, tileX, tileY) => {
if (tileX < 0 || tileX >= gamemap.length || tileY < 0 || tileY >= gamemap[tileX].length) {
return;
}
if (conditionFunc(tileX, tileY)) {
successFunc(tileX, tileY);
checkAndSetRoads(tileX, tileY);
render(ctx, imgmap);
}
};
const maybeAddTileAt = maybeXTileAt.bind(null,
// second clause allows for roads to overwrite zones
(tileX, tileY) => gamemap[tileX][tileY].col.type === t_Empty || gamemap[tileX][tileY].col.type === t_Zone,
// set type but not sprite, which will be set by checkAndSetRoads
(tileX, tileY) => { gamemap[tileX][tileY].col.type = t_Road; });
const maybeRemoveTileAt = maybeXTileAt.bind(null,
(tileX, tileY) => gamemap[tileX][tileY].col !== t_Empty && gamemap[tileX][tileY].col.type === t_Road,
(tileX, tileY) => { gamemap[tileX][tileY].col = { type: t_Empty }; });
const cancelMoveListening = (e) => {
e.stopPropagation();
dragAdder = undefined;
document.removeEventListener('mousemove', moveListener);
};
const moveListener = (e) => {
if (e.target !== overlay) {
return cancelMoveListening(e);
}
if (dragAdder !== undefined) {
e.preventDefault();
dragAdder(...tileCoordsFromEvent(e));
}
};
const clickListener = (dragFunc, e) => {
e.preventDefault();
(dragAdder = dragFunc)(...tileCoordsFromEvent(e));
document.addEventListener('mousemove', moveListener);
}
setCanvasListeners(overlay, {
contextmenu: clickListener.bind(null, maybeRemoveTileAt),
mousedown: clickListener.bind(null, maybeAddTileAt),
mouseup: cancelMoveListening
});
};
const setZoneMode = (zoneIdx) => {
selectIcon(zoneIdx);
let dragStart;
const overlay = document.getElementById('overlay_canvas');
const overlayCtx = overlay.getContext('2d');
const moveListener = (e) => {
e.preventDefault();
const drawCoords = [dragStart.offsetX, dragStart.offsetY,
e.offsetX - dragStart.offsetX, e.offsetY - dragStart.offsetY];
clearCanvas(overlayCtx);
overlayCtx.fillStyle = zoneColors[zoneIdx].fill;
overlayCtx.fillRect(...drawCoords);
overlayCtx.strokeStyle = zoneColors[zoneIdx].stroke;
overlayCtx.lineJoin = 'round';
overlayCtx.strokeRect(...drawCoords);
};
const startDrag = (e) => {
dragStart = { offsetX: e.offsetX, offsetY: e.offsetY };
overlay.addEventListener('mousemove', moveListener);
};
const getTopLeftAndBottomRight = (c1, c2) => {
// user's box is from botLeft to topRight, must convert to tL/bR pair
if (c1.offsetX <= c2.offsetX && c1.offsetY >= c2.offsetY) {
return [{ offsetX: c1.offsetX, offsetY: c2.offsetY }, { offsetX: c2.offsetX, offsetY: c1.offsetY }];
}
// user's box if from topRight to botLeft, must convert to tL/bR pair
if (c1.offsetX >= c2.offsetX && c1.offsetY <= c2.offsetY) {
return [{ offsetX: c2.offsetX, offsetY: c1.offsetY }, { offsetX: c1.offsetX, offsetY: c2.offsetY }];
}
if (c1.offsetX >= c2.offsetX && c1.offsetY >= c2.offsetY) {
return [c2, c1];
}
if (c1.offsetX < c2.offsetX || c1.offsetY < c2.offsetY) {
return [c1, c2];
}
};
const endDrag = (e) => {
if (!dragStart) {
// happens if the user starts a drag outside the canvas and ends it within; we just discard the event
return;
}
const [topLeft, botRight] = getTopLeftAndBottomRight(dragStart, {
offsetX: e.offsetX, offsetY: e.offsetY
});
const [tlTileX, tlTileY] = tileCoordsFromEvent(topLeft);
const [blTileX, blTileY] = tileCoordsFromEvent(botRight);
for (let x = tlTileX; x <= blTileX; x++) {
for (let y = tlTileY; y <= blTileY; y++) {
// potential fix for out-of-bounds drag because user is outside of the border? not sure this is a good idea...
if (!gamemap[x] || !gamemap[x][y]) {
continue;
}
if (zoneIdx === z_Unz) {
// only remove .col layers that are zone layers
if (gamemap[x][y].col.type === t_Zone) {
gamemap[x][y].col = { type: t_Empty };
}
} else if (gamemap[x][y].col.type === t_Empty) {
gamemap[x][y].col = { type: t_Zone, zoneType: zoneIdx, sprite: `${zoneColors[zoneIdx].fill}` };
}
}
}
dragStart = undefined;
overlay.removeEventListener('mousemove', moveListener);
clearCanvas(overlayCtx);
render(ctx, imgmap);
};
setCanvasListeners(overlay, {
mousedown: startDrag,
mouseup: endDrag,
contextmenu: (e) => e.preventDefault()
});
};
setIcon(1, 'road_blank', 'place roads, right-click to remove', setRoadMode);
setIcon(z_Res, 'target_green', 'zone residential', setZoneMode.bind(null, z_Res));
setIcon(z_Com, 'target_blue', 'zone commerical', setZoneMode.bind(null, z_Com));
setIcon(z_Ind, 'target_yellow', 'zone industrial', setZoneMode.bind(null, z_Ind));
setIcon(z_Unz, 'map_minus', 'de-zone', setZoneMode.bind(null, z_Unz));
setIcon(6, 'world_red_x', 'clear all roads & zones', () => gamemapInit(canvas, ctx, imgmap));
setIcon(7, 'world_green_check', 'start simulatation', () => enterSimMode(canvas, ctx, imgmap))
setRoadMode();
}
/***** [MARK] Simulation mode *****/
function roadPaths_srch(from, to, opts, path = [], lvl = 0) {
// if the heuristic found a path short "enough" below, it will mark continue=true to inform
// all remaining search branches to terminate immediately with an invalid return (as we no
// longer care about their path returns)
if (!opts.continue) {
return null
}
// goal-path-found branch
if (from.x === to.x && from.y === to.y) {
if (path.length < opts.hueristic) {
const newHuer = path.length - 1;
// the key to the use of the hueristic is that it be used to decide when the search
// has found a "good enough" solution (here), defined as anything larger (in ratio)
// than the original hueristic multiplier -- this forcefully terminates all outsranding
// branches of the current search
if (opts.origHueristic / newHuer > RP_HUER_MULT) {
opts.continue = false;
}
// reset hueristic to now-shortest path! don't need/want to find *anything* longer
opts.hueristic = newHuer;
}
return path.concat([to]);
}
// last-ditch time culling, before the proper hueristic above this would be hit
// often but now it should *never* be needed
if (performance.now() - opts.start > opts.rtLim) {
++opts.otCulled;
return path;
}
let neighbors = checkCardDirsForColType(from.x, from.y, t_Road);
if (neighbors) {
const cdTmpl = [b_N, b_S, b_E, b_W];
let cardDirsToSearch = [...cdTmpl];
if (path.length) {
const revVec = contigRevMovementVec(from, path[path.length - 1]);
if (revVec) {
const curVec = revVec === b_N ? b_S : (revVec === b_E ? b_W : b_E);
// removes the previous tile from consideration
neighbors &= ~revVec & 0xf;
// ensures the current direction is first in the search order below,
// which significantly improves real-world complexitly of the algorithm
// (in concert with the hueristic), as most optmial paths will be along
// straight-line movement vectors and this allows the algorithm to reach those
// more-optmial paths quickly and cull more branches (or even terminate early)
if (neighbors & curVec) {
let maskDirs = [...cdTmpl];
maskDirs.splice(maskDirs.indexOf(curVec), 1);
cardDirsToSearch = [curVec, ...maskDirs];
}
}
}
// if any of the valid neighbor directions aren't already in our path,
// recurse, starting from that neighbor, onto a copy of the current path plus the current coord (`from`)
return cardDirsToSearch
// checking if the given cardinal direction bit is set in `neighbors`
.map((cDir) => neighbors & cDir ? modCoord(cDir, {...from}) : null)
// (and ignoring any that aren't)
.filter(x => x !== null)
.flatMap((sc) => {
// use A* as inspiriation and cull the DFS if the current path length exceeds the given hueristic
// the important bit of this enhancement is that the hueristic is *adjusted* when a goal-path is found
// that is less than it is currently! done above, in the goal-path-found early return branch
const _hskip = path.length + 1 > opts.hueristic;
if (!path.some(t => t.x === sc.x && t.y === sc.y)) {
if (!_hskip) {
return roadPaths_srch(sc, to, opts, [...path, from], lvl + 1);
} else {
++opts.culled;
}
}
// 'sc' is already in 'path', meaning this would be a cycle which we cannot allow; return an invalid path
return null;
});
}
return path;
}
function roadPaths(from, to) {
const _start = performance.now();
const key = rpKey(from, to);
// this cache won't see many hits during the early phase of simulation as the population
// is growing, but once things settle, most paths will have already been explored once
// and thus by the late sim phaase nearly *all* of the calls to roadPaths() will be cache hits
if (roadPathsCache[key]) {
return roadPathsCache[key];
}
const mhDist = Math.abs(to.x - from.x) + Math.abs(to.y - from.y);
const opts = {
hueristic: (mhDist * RP_HUER_MULT) + 1,
culled: 0,
otCulled: 0,
start: _start,
rtLim: SIMUGINE_TICK * 0.6,
continue: true
};
opts.origHueristic = opts.hueristic;
// transforms a flat list into a list-of-lists-of-paths
const pathsXform = roadPaths_srch(from, to, opts).reduce((acc, pEle) => {
if (pEle) {
if (pEle.x === from.x && pEle.y === from.y) {
acc.push([]);
}
acc[acc.length - 1].push(pEle);
}
return acc;
}, []);
// removes any dead ends
let filteredPaths = pathsXform.filter(x => x[x.length - 1].x === to.x && x[x.length - 1].y === to.y);
const rv = {
all: filteredPaths,
shortest: filteredPaths.reduce((al, x) => [x.length < al[0] ? x.length : al[0], x.length < al[0] ? x : al[1]], [2e32, null])[1]
};
roadPathsCache[key] = rv;
opts.counts = { total: pathsXform.length, filtered: filteredPaths.length };
dLog(`[${performance.now() - _start}ms] opts for "${key}":` + JSON.stringify(opts));
return rv;
}
function connectBizToEmp(bizType, gamestate, nCoord) {
const bldgType = bizType === z_Com ? 'commerical' : 'industrial';
const bldgNum = Object.keys(buildingsmap[bldgType]).length;
let curBizObj = {
type: t_Employer,
subType: bizType,
sprite: `buildings/${bldgType}/${Math.floor((Math.random() * bldgNum) + 1)}`,
employees: []
};
let addedJobs = 0;
if (gamemap[nCoord.x] && gamemap[nCoord.x][nCoord.y] && gamemap[nCoord.x][nCoord.y].sim.type === t_Employer) {
curBizObj = gamemap[nCoord.x][nCoord.y].sim;
} else {
// this is a new business; account for its added jobs
addedJobs += bizType === z_Com ? 1 : Z_IND_EMPS_PER;
}
const bizToRoadPaths = curBizObj.bizToRoadPaths || findRoadsInAllCardDirs(nCoord, bizType);
if (!curBizObj.paths) {
curBizObj.paths = bizToRoadPaths;
}
// may be validly called without any availble workforce if the given biz is first to move into town via random choice
if (gamestate.population.unemployed.length) {
const potEmp = gamestate.population.unemployed[0];
const empToRoadPaths = gamemap[potEmp.x][potEmp.y].sim.paths || findRoadsInAllCardDirs(gamestate.population.unemployed[0], z_Res);
if (!bizToRoadPaths || bizToRoadPaths.all.length === 0 || !empToRoadPaths || empToRoadPaths.all.length === 0) {
const err = new Error(`UNREACHABLE PAIR! biz=${JSON.stringify(nCoord)} emp=${JSON.stringify(gamestate.population.unemployed[0])}`);
err.__mpc_score_sub = 0.01;
throw err;
}
const from = empToRoadPaths.shortest.roadTile;
const to = bizToRoadPaths.shortest.roadTile;
const commutePaths = roadPaths(from, to);
if (commutePaths.all.length < 1) {
console.log(JSON.stringify(commutePaths, null, 2));
throw new Error(`NO PATH BETWEEN empRT=${JSON.stringify(from)} ` +
`bizRT=${JSON.stringify(to)} -- RTs: biz=${JSON.stringify(nCoord)} ` +
`emp=${JSON.stringify(gamestate.population.unemployed[0])}`);
}
const newEmployee = gamestate.population.unemployed.shift();
const newEmpObj = gamemap[newEmployee.x][newEmployee.y].sim;
newEmpObj.employer = nCoord;
newEmpObj.paths = empToRoadPaths;
newEmpObj.commute = {
cardinal: cardinalDirection(newEmployee, nCoord),
paths: commutePaths
};
curBizObj.employees.push(newEmployee);
addedJobs -= 1;
}
gamestate.jobs += addedJobs; // -1 is valid, when this is just an employee taking a new job & not a new biz as well
return curBizObj;
}
// returns an object that has .pause() and .resume(), which act as their names suggest
function simugine(canvas, ctx, imgmap, infoBar, endgameCallback) {
let jitter = 0;
const availableTiles = {
[z_Res]: [],
[z_Com]: [],
[z_Ind]: []
};
const completeTiles = {
[t_Road]: [],
[z_Res]: [],
[z_Com]: [],
[z_Ind]: []
};
const gamestate = {
happiness: 1.0,
population: {
unemployed: [],
total: 0
},
jobs: 0,
ticks: 0,
growth: [],
endgame: {
samplesRemain: ENDGAME_SAMPLE_NUM_WEEKS,
samples: []
}
};
// decisionators decide if a new entity will move into a given tile type
const simugineDecisionators = {
// population will grow if happiness > POP_GROWTH_HAPPINESS_REQD *or* if jobs are available
[z_Res]: (tickRand, gamestate, availableTiles) => gamestate.jobs > 0,
[z_Com]: (tickRand, gamestate, availableTiles) => tickRand > POP_GROWTH_HAPPINESS_REQD || gamestate.population.unemployed.length,
[z_Ind]: (tickRand, gamestate, availableTiles) => tickRand > POP_GROWTH_HAPPINESS_REQD || gamestate.population.unemployed.length
};
// creators do the work to add the new entity to the tile type
const simugineCreators = {
[z_Res]: (gamestate, newHomeCoordinate) => {
gamestate.population.unemployed.push(newHomeCoordinate);
gamestate.population.total++;
const size = ['small', 'medium', 'big'][Math.floor(Math.random() * 3)];
const idx = Math.floor((Math.random() * 3) + 1);
return { type: t_Home, sprite: `buildings/houses/${size}_${idx}`, employer: null };
},
[z_Com]: connectBizToEmp.bind(null, z_Com),
[z_Ind]: connectBizToEmp.bind(null, z_Ind)
};
// destroyers remove a given tile from the availableTiles list when appropriate
const simugineDestroyers = {
[z_Res]: () => true,
[z_Com]: (gamestate, bizCoord) => gamemap[bizCoord.x][bizCoord.y].sim.employees.length > 0,
[z_Ind]: (gamestate, bizCoord) => gamemap[bizCoord.x][bizCoord.y].sim.employees.length >= Z_IND_EMPS_PER
};
// build availableTiles & completeTiles (only roads at this point); also setups the .sim object for road tiles
allTiles((tX, tY) => {
const tileObj = gamemap[tX][tY];
if (tileObj.col && tileObj.col.type > t_Empty) {
const binType = tileObj.col.type === t_Zone ? tileObj.col.zoneType : tileObj.col.type;
let binRef = availableTiles;
if (binType === t_Road) {
binRef = completeTiles;
tileObj.sim = { type: t_Traffic, cars: 0 };
}
binRef[binType].push({ x: tX, y: tY });
}
});
const renderOpts = { maxPop: availableTiles[z_Res].length * 1.1 /* a fudge for rendering; that's all. TODO: this better */};
const _simugine = () => {
simugine_handle = setTimeout(() => {
const _start = performance.now();
const tickRand = Math.random();
const tickStartPop = gamestate.population.total;
const growthMode = !tickStartPop || gamestate.growth.reduce((a, x) => a + x, 0);
if (jitter > SIMUGINE_TICK) {
console.warn(`lagging! ${jitter} -> ${SIMUGINE_TICK - jitter}`);
}
// at each tick, consider one residental tile and *either* a commericial or industrial ("employers"), alternating
// until there are no more employees available (e.g. "growth" mode is complete)
if (growthMode) {
[z_Res, (gamestate.ticks % 2 ? z_Com : z_Ind)].forEach((sdKey) => {
if (availableTiles[sdKey].length > 0 && simugineDecisionators[sdKey](tickRand, gamestate, availableTiles)) {
const newHomeTileIdx = Math.floor(Math.random() * availableTiles[sdKey].length);
const nhC = availableTiles[sdKey][newHomeTileIdx];
if (simugineCreators[sdKey]) {
try {
gamemap[nhC.x][nhC.y].sim = simugineCreators[sdKey](gamestate, nhC);
// the creator function is supposed to throw on error to be caught below and
// hence this first clause shouldn't be necessary, but i've accidently broken this
// rule just now and hence am adding this clause & comment to remind myself of why
if (gamemap[nhC.x][nhC.y].sim && simugineDestroyers[sdKey](gamestate, nhC)) {
completeTiles[sdKey].push(availableTiles[sdKey].splice(newHomeTileIdx, 1)[0]);
}
} catch (e) {
console.log(`<${e.__mpc_score_sub}> ${e.toString()}`);
if (DEBUG) console.log(e);
if (e.__mpc_score_sub) {
gamestate.happiness -= gamestate.happiness * e.__mpc_score_sub;
}
}
}
}
});
}
const weekday = gamestate.ticks % 7;
let daysRoutes;
completeTiles[t_Road].forEach((t) => (gamemap[t.x][t.y].sim.cars = 0));
if (weekday >= 0 && weekday < 5) {
// workdays; WORKING_POP_WEEKDAY_WORK_PRCNT of population with jobs go to work
// most of the time they take the shortest route; sometimes (WORK_TAKE_SCENIC_ROUTE_CHANCE) they take a random one
daysRoutes = completeTiles[z_Res].map((t) => {
if (Math.random() >= WORKING_POP_WEEKDAY_WORK_PRCNT) {
return null;
}
if (!gamemap[t.x][t.y].sim.commute) {
//TODO: throw? ding score? fix?
return null;
}
if (Math.random() >= WORK_TAKE_SCENIC_ROUTE_CHANCE) {
const allPaths = gamemap[t.x][t.y].sim.commute.paths.all;
return allPaths[Math.floor(Math.random() * allPaths.lengtht)];
}
return gamemap[t.x][t.y].sim.commute.paths.shortest;
}).filter(x => x !== null);
}
else {
// weekends; WEEKEND_OUTING_POP_PRCNT_PERDAY of population goes to a random commercial tile each day
// (when commercial tiles have businesses on them, that is)
if (completeTiles[z_Com].length > 0) {
daysRoutes = completeTiles[z_Res].filter(() => Math.random() > WEEKEND_OUTING_POP_PRCNT_PERDAY).map((rt) => {
const rs = completeTiles[z_Com][Math.floor(Math.random() * completeTiles[z_Com].length)];
const storeRoad = gamemap[rs.x][rs.y].sim.paths.shortest.roadTile;
const tsObj = gamemap[rt.x][rt.y].sim;
if (!tsObj.paths) {
tsObj.paths = findRoadsInAllCardDirs(rt, z_Res);
}
if (storeRoad && tsObj.paths && tsObj.paths.shortest.roadTile) {
return roadPaths(tsObj.paths.shortest.roadTile, storeRoad).shortest;
}
else {
console.log('no path in traffic calc between:', rs, rt);
if (growthMode) {
gamestate.happiness -= gamestate.happiness * 0.01;
}
}
});
} else if (growthMode && availableTiles[z_Com].length === 0) {
// no commerical zones! ding 1% every time a simuzen tries to get to one! (only in growth mode)
dLog(`no comm!`);
gamestate.happiness -= gamestate.happiness * 0.01;
}
}
// simulate the entire "day" of driving at once by accumulating "cars" at each tile for the day
if (daysRoutes && daysRoutes.length) {
// TODO: route===null, recalc here?
daysRoutes.forEach((route) => {
if (route) {
route.forEach((rp) => gamemap[rp.x][rp.y].sim.cars++);
}
});
}
if (!growthMode) {
if (!gamestate.endgame.samples.length) {
infoBar.innerText = 'City has finished growing. Calculating score...';
}
if (gamestate.endgame.samplesRemain) {
if (weekday === 0) {
gamestate.endgame.samples.push([]);
}
// this effectively causes this sampler to wait until weekday 0 to start sampling,
// if the first time we enter the sampling mode is *not* on weekday 0
if (gamestate.endgame.samples.length) {
const trafficAgg = completeTiles[t_Road].reduce((acc, rTile) => {
return acc + (gamemap[rTile.x][rTile.y].sim.cars / renderOpts.maxPop);
}, 0.0);
const trafficScore = trafficAgg / completeTiles[t_Road].length;
gamestate.endgame.samples[gamestate.endgame.samples.length - 1].push({
trafficAgg, trafficScore
});
if (weekday === 6) {
--gamestate.endgame.samplesRemain;
}
}
} else { // endgame!
if (gamestate.lastDisplayTick) {
endgameCallback(gamestate, availableTiles);
return;
}
gamestate.lastDisplayTick = true;
}
} else {
const tickPopGrowth = gamestate.population.total - tickStartPop;
gamestate.growth.push(tickPopGrowth);
if (gamestate.growth.length > GROWTH_WIN_SIZE) {
gamestate.growth.shift();
}
}
render(ctx, imgmap, renderOpts);
++gamestate.ticks;
jitter = performance.now() - _start;
_simugine();
}, SIMUGINE_TICK - jitter);
};
return {
pause: () => {
clearTimeout(simugine_handle);
simugine_handle = undefined;
},
resume: () => {
if (!simugine_handle) {
_simugine();
}
}
};
}
function enterSimMode(canvas, ctx, imgmap) {
setCanvasListeners(document.getElementById('overlay_canvas'), {}); // clears previous listeners
selectIcon(-1); // clears the selection
setIcon(1);
setIcon(4);
setIcon(5);
setIcon(6);
setIcon(7);
const infoBar = document.getElementById('info_bar');
infoBar.style.visibility = 'visible';
const simEngine = simugine(canvas, ctx, imgmap, infoBar, (gamestate, remainingTiles) => {
console.log('FIN.');
console.log(gamestate, remainingTiles);
selectIcon(-1);
setIcon(2);
setIcon(3);
const trafficMeanScore = Math.floor((gamestate.endgame.samples.reduce((a, sList) => {
return a + (sList.reduce((aa, x) => aa + x.trafficScore, 0) / sList.length);