-
Notifications
You must be signed in to change notification settings - Fork 238
Expand file tree
/
Copy pathsimulation.ts
More file actions
4263 lines (3724 loc) · 153 KB
/
Copy pathsimulation.ts
File metadata and controls
4263 lines (3724 loc) · 153 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
// Simulation engine for IsoCity
import {
GameState,
Tile,
Building,
BuildingType,
ZoneType,
Stats,
Budget,
ServiceCoverage,
AdvisorMessage,
HistoryPoint,
Notification,
AdjacentCity,
WaterBody,
BridgeType,
BridgeOrientation,
BUILDING_STATS,
RESIDENTIAL_BUILDINGS,
COMMERCIAL_BUILDINGS,
INDUSTRIAL_BUILDINGS,
TOOL_INFO,
} from '@/types/game';
import { generateCityName, generateWaterName } from './names';
import { isMobile } from 'react-device-detect';
// Default grid size for new games
export const DEFAULT_GRID_SIZE = isMobile ? 50 : 70;
// Check if a factory_small at this position would render as a farm
// This matches the deterministic logic in Game.tsx for farm variant selection
function isFarmBuilding(x: number, y: number, buildingType: string): boolean {
if (buildingType !== 'factory_small') return false;
// Same seed calculation as in Game.tsx rendering
const seed = (x * 31 + y * 17) % 100;
// ~50% chance to be a farm variant (when seed < 50)
return seed < 50;
}
// Check if a building is a "starter" type that can operate without utilities
// This includes all factory_small (farms AND small factories), small houses, and small shops
// All starter buildings represent small-scale, self-sufficient operations that don't need
// municipal power/water infrastructure to begin operating
function isStarterBuilding(x: number, y: number, buildingType: string): boolean {
if (buildingType === 'house_small' || buildingType === 'shop_small') return true;
// ALL factory_small are starters - they can spawn without utilities
// Some will render as farms (~50%), others as small factories
// Both represent small-scale operations that can function off-grid
if (buildingType === 'factory_small') return true;
return false;
}
// Perlin-like noise for terrain generation (exported for reuse in other games)
function noise2D(x: number, y: number, seed: number = 42): number {
const n = Math.sin(x * 12.9898 + y * 78.233 + seed) * 43758.5453123;
return n - Math.floor(n);
}
function smoothNoise(x: number, y: number, seed: number): number {
const corners = (noise2D(x - 1, y - 1, seed) + noise2D(x + 1, y - 1, seed) +
noise2D(x - 1, y + 1, seed) + noise2D(x + 1, y + 1, seed)) / 16;
const sides = (noise2D(x - 1, y, seed) + noise2D(x + 1, y, seed) +
noise2D(x, y - 1, seed) + noise2D(x, y + 1, seed)) / 8;
const center = noise2D(x, y, seed) / 4;
return corners + sides + center;
}
function interpolatedNoise(x: number, y: number, seed: number): number {
const intX = Math.floor(x);
const fracX = x - intX;
const intY = Math.floor(y);
const fracY = y - intY;
const v1 = smoothNoise(intX, intY, seed);
const v2 = smoothNoise(intX + 1, intY, seed);
const v3 = smoothNoise(intX, intY + 1, seed);
const v4 = smoothNoise(intX + 1, intY + 1, seed);
const i1 = v1 * (1 - fracX) + v2 * fracX;
const i2 = v3 * (1 - fracX) + v4 * fracX;
return i1 * (1 - fracY) + i2 * fracY;
}
export function perlinNoise(x: number, y: number, seed: number, octaves: number = 4): number {
let total = 0;
let frequency = 0.05;
let amplitude = 1;
let maxValue = 0;
for (let i = 0; i < octaves; i++) {
total += interpolatedNoise(x * frequency, y * frequency, seed + i * 100) * amplitude;
maxValue += amplitude;
amplitude *= 0.5;
frequency *= 2;
}
return total / maxValue;
}
// Generate 2-3 large, round lakes and return water bodies
function generateLakes(grid: Tile[][], size: number, seed: number): WaterBody[] {
// Use noise to find potential lake centers - look for low points
const lakeNoise = (x: number, y: number) => perlinNoise(x, y, seed + 1000, 3);
// Find lake seed points (local minimums in noise)
const lakeCenters: { x: number; y: number; noise: number }[] = [];
const minDistFromEdge = Math.max(8, Math.floor(size * 0.15)); // Keep lakes away from ocean edges
const minDistBetweenLakes = Math.max(size * 0.2, 10); // Adaptive but ensure minimum separation
// Collect all potential lake centers with adaptive threshold
// Start with a lenient threshold and tighten if we find too many
let threshold = 0.5;
let attempts = 0;
const maxAttempts = 3;
while (lakeCenters.length < 2 && attempts < maxAttempts) {
lakeCenters.length = 0; // Reset for this attempt
for (let y = minDistFromEdge; y < size - minDistFromEdge; y++) {
for (let x = minDistFromEdge; x < size - minDistFromEdge; x++) {
const noiseVal = lakeNoise(x, y);
// Check if this is a good lake center (low noise value)
if (noiseVal < threshold) {
// Check distance from other lake centers
let tooClose = false;
for (const center of lakeCenters) {
const dist = Math.sqrt((x - center.x) ** 2 + (y - center.y) ** 2);
if (dist < minDistBetweenLakes) {
tooClose = true;
break;
}
}
if (!tooClose) {
lakeCenters.push({ x, y, noise: noiseVal });
}
}
}
}
// If we found enough centers, break
if (lakeCenters.length >= 2) break;
// Otherwise, relax the threshold for next attempt
threshold += 0.1;
attempts++;
}
// If still no centers found, force create at least 2 lakes at strategic positions
if (lakeCenters.length === 0) {
// Place lakes at strategic positions, ensuring they're far enough from edges
const safeZone = minDistFromEdge + 5; // Extra buffer for lake growth
const quarterSize = Math.max(safeZone, Math.floor(size / 4));
const threeQuarterSize = Math.min(size - safeZone, Math.floor(size * 3 / 4));
lakeCenters.push(
{ x: quarterSize, y: quarterSize, noise: 0 },
{ x: threeQuarterSize, y: threeQuarterSize, noise: 0 }
);
} else if (lakeCenters.length === 1) {
// If only one center found, add another at a safe distance
const existing = lakeCenters[0];
const safeZone = minDistFromEdge + 5;
const quarterSize = Math.max(safeZone, Math.floor(size / 4));
const threeQuarterSize = Math.min(size - safeZone, Math.floor(size * 3 / 4));
let newX = existing.x > size / 2 ? quarterSize : threeQuarterSize;
let newY = existing.y > size / 2 ? quarterSize : threeQuarterSize;
lakeCenters.push({ x: newX, y: newY, noise: 0 });
}
// Sort by noise value (lowest first) and pick 2-3 best candidates
lakeCenters.sort((a, b) => a.noise - b.noise);
const numLakes = 2 + Math.floor(Math.random() * 2); // 2 or 3 lakes
const selectedCenters = lakeCenters.slice(0, Math.min(numLakes, lakeCenters.length));
const waterBodies: WaterBody[] = [];
const usedLakeNames = new Set<string>();
// Grow lakes from each center using radial expansion for rounder shapes
for (const center of selectedCenters) {
// Target size: 40-80 tiles for bigger lakes
const targetSize = 40 + Math.floor(Math.random() * 41);
const lakeTiles: { x: number; y: number }[] = [{ x: center.x, y: center.y }];
const candidates: { x: number; y: number; dist: number; noise: number }[] = [];
// Add initial neighbors as candidates
const directions = [[-1, 0], [1, 0], [0, -1], [0, 1], [-1, -1], [-1, 1], [1, -1], [1, 1]];
for (const [dx, dy] of directions) {
const nx = center.x + dx;
const ny = center.y + dy;
if (nx >= minDistFromEdge && nx < size - minDistFromEdge &&
ny >= minDistFromEdge && ny < size - minDistFromEdge) {
const dist = Math.sqrt(dx * dx + dy * dy);
const noise = lakeNoise(nx, ny);
candidates.push({ x: nx, y: ny, dist, noise });
}
}
// Grow lake by adding adjacent tiles, prioritizing:
// 1. Closer to center (for rounder shape)
// 2. Lower noise values (for organic shape)
while (lakeTiles.length < targetSize && candidates.length > 0) {
// Sort by distance from center first, then noise
candidates.sort((a, b) => {
if (Math.abs(a.dist - b.dist) < 0.5) {
return a.noise - b.noise; // If similar distance, prefer lower noise
}
return a.dist - b.dist; // Prefer closer tiles for rounder shape
});
// Pick from top candidates (closest/lowest noise)
const pickIndex = Math.floor(Math.random() * Math.min(5, candidates.length));
const picked = candidates.splice(pickIndex, 1)[0];
// Check if already in lake
if (lakeTiles.some(t => t.x === picked.x && t.y === picked.y)) continue;
// Check if tile is valid (not already water from another lake)
if (grid[picked.y][picked.x].building.type === 'water') continue;
lakeTiles.push({ x: picked.x, y: picked.y });
// Add new neighbors as candidates
for (const [dx, dy] of directions) {
const nx = picked.x + dx;
const ny = picked.y + dy;
if (nx >= minDistFromEdge && nx < size - minDistFromEdge &&
ny >= minDistFromEdge && ny < size - minDistFromEdge &&
!lakeTiles.some(t => t.x === nx && t.y === ny) &&
!candidates.some(c => c.x === nx && c.y === ny)) {
const dist = Math.sqrt((nx - center.x) ** 2 + (ny - center.y) ** 2);
const noise = lakeNoise(nx, ny);
candidates.push({ x: nx, y: ny, dist, noise });
}
}
}
// Apply lake tiles to grid
for (const tile of lakeTiles) {
grid[tile.y][tile.x].building = createBuilding('water');
grid[tile.y][tile.x].landValue = 60; // Water increases nearby land value
}
// Calculate center for labeling
const avgX = lakeTiles.reduce((sum, t) => sum + t.x, 0) / lakeTiles.length;
const avgY = lakeTiles.reduce((sum, t) => sum + t.y, 0) / lakeTiles.length;
// Assign a random name to this lake
let lakeName = generateWaterName('lake');
while (usedLakeNames.has(lakeName)) {
lakeName = generateWaterName('lake');
}
usedLakeNames.add(lakeName);
// Add to water bodies list
waterBodies.push({
id: `lake-${waterBodies.length}`,
name: lakeName,
type: 'lake',
tiles: lakeTiles,
centerX: Math.round(avgX),
centerY: Math.round(avgY),
});
}
return waterBodies;
}
// Generate ocean connections on map edges (sometimes) with organic coastlines
function generateOceans(grid: Tile[][], size: number, seed: number): WaterBody[] {
const waterBodies: WaterBody[] = [];
const oceanChance = 0.4; // 40% chance per edge
// Use noise for coastline variation
const coastNoise = (x: number, y: number) => perlinNoise(x, y, seed + 2000, 3);
// Check each edge independently
const edges: Array<{ side: 'north' | 'east' | 'south' | 'west'; tiles: { x: number; y: number }[] }> = [];
// Ocean parameters
const baseDepth = Math.max(4, Math.floor(size * 0.12));
const depthVariation = Math.max(4, Math.floor(size * 0.08));
const maxDepth = Math.floor(size * 0.18);
// Helper to generate organic ocean section along an edge
const generateOceanEdge = (
isHorizontal: boolean,
edgePosition: number, // 0 for north/west, size-1 for south/east
inwardDirection: 1 | -1 // 1 = increasing coord, -1 = decreasing coord
): { x: number; y: number }[] => {
const tiles: { x: number; y: number }[] = [];
// Randomize the span of the ocean (40-80% of edge, not full length)
const spanStart = Math.floor(size * (0.05 + Math.random() * 0.25));
const spanEnd = Math.floor(size * (0.7 + Math.random() * 0.25));
for (let i = spanStart; i < spanEnd; i++) {
// Use noise to determine depth at this position, with fade at edges
const edgeFade = Math.min(
(i - spanStart) / 5,
(spanEnd - i) / 5,
1
);
// Layer two noise frequencies for more interesting coastline
// Higher frequency noise for fine detail, lower for broad shape
const coarseNoise = coastNoise(
isHorizontal ? i * 0.08 : edgePosition * 0.08,
isHorizontal ? edgePosition * 0.08 : i * 0.08
);
const fineNoise = coastNoise(
isHorizontal ? i * 0.25 : edgePosition * 0.25 + 500,
isHorizontal ? edgePosition * 0.25 + 500 : i * 0.25
);
const noiseVal = coarseNoise * 0.6 + fineNoise * 0.4;
// Depth varies based on noise and fades at the ends
const rawDepth = baseDepth + (noiseVal - 0.5) * depthVariation * 2.5;
const localDepth = Math.max(1, Math.min(Math.floor(rawDepth * edgeFade), maxDepth));
// Place water tiles from edge inward
for (let d = 0; d < localDepth; d++) {
const x = isHorizontal ? i : (inwardDirection === 1 ? d : size - 1 - d);
const y = isHorizontal ? (inwardDirection === 1 ? d : size - 1 - d) : i;
if (x >= 0 && x < size && y >= 0 && y < size && grid[y][x].building.type !== 'water') {
grid[y][x].building = createBuilding('water');
grid[y][x].landValue = 60;
tiles.push({ x, y });
}
}
}
return tiles;
};
// North edge (top, y=0, extends downward)
if (Math.random() < oceanChance) {
const tiles = generateOceanEdge(true, 0, 1);
if (tiles.length > 0) {
edges.push({ side: 'north', tiles });
}
}
// South edge (bottom, y=size-1, extends upward)
if (Math.random() < oceanChance) {
const tiles = generateOceanEdge(true, size - 1, -1);
if (tiles.length > 0) {
edges.push({ side: 'south', tiles });
}
}
// East edge (right, x=size-1, extends leftward)
if (Math.random() < oceanChance) {
const tiles = generateOceanEdge(false, size - 1, -1);
if (tiles.length > 0) {
edges.push({ side: 'east', tiles });
}
}
// West edge (left, x=0, extends rightward)
if (Math.random() < oceanChance) {
const tiles = generateOceanEdge(false, 0, 1);
if (tiles.length > 0) {
edges.push({ side: 'west', tiles });
}
}
// Create water body entries for oceans
const usedOceanNames = new Set<string>();
for (const edge of edges) {
if (edge.tiles.length > 0) {
const avgX = edge.tiles.reduce((sum, t) => sum + t.x, 0) / edge.tiles.length;
const avgY = edge.tiles.reduce((sum, t) => sum + t.y, 0) / edge.tiles.length;
let oceanName = generateWaterName('ocean');
while (usedOceanNames.has(oceanName)) {
oceanName = generateWaterName('ocean');
}
usedOceanNames.add(oceanName);
waterBodies.push({
id: `ocean-${edge.side}-${waterBodies.length}`,
name: oceanName,
type: 'ocean',
tiles: edge.tiles,
centerX: Math.round(avgX),
centerY: Math.round(avgY),
});
}
}
return waterBodies;
}
// Generate adjacent cities - always create one for each direction (undiscovered until road reaches edge)
function generateAdjacentCities(): AdjacentCity[] {
const cities: AdjacentCity[] = [];
const directions: Array<'north' | 'south' | 'east' | 'west'> = ['north', 'south', 'east', 'west'];
const usedNames = new Set<string>();
for (const direction of directions) {
let name: string;
do {
name = generateCityName();
} while (usedNames.has(name));
usedNames.add(name);
cities.push({
id: `city-${direction}`,
name,
direction,
connected: false,
discovered: false, // Cities are discovered when a road reaches their edge
});
}
return cities;
}
// Check if there's a road tile at any edge of the map in a given direction
export function hasRoadAtEdge(grid: Tile[][], gridSize: number, direction: 'north' | 'south' | 'east' | 'west'): boolean {
switch (direction) {
case 'north':
// Check top edge (y = 0)
for (let x = 0; x < gridSize; x++) {
const type = grid[0][x].building.type;
if (type === 'road' || type === 'bridge') return true;
}
return false;
case 'south':
// Check bottom edge (y = gridSize - 1)
for (let x = 0; x < gridSize; x++) {
const type = grid[gridSize - 1][x].building.type;
if (type === 'road' || type === 'bridge') return true;
}
return false;
case 'east':
// Check right edge (x = gridSize - 1)
for (let y = 0; y < gridSize; y++) {
const type = grid[y][gridSize - 1].building.type;
if (type === 'road' || type === 'bridge') return true;
}
return false;
case 'west':
// Check left edge (x = 0)
for (let y = 0; y < gridSize; y++) {
const type = grid[y][0].building.type;
if (type === 'road' || type === 'bridge') return true;
}
return false;
}
}
// Check all edges and return cities that can be connected (have roads reaching them)
// Returns: { newlyDiscovered: cities just discovered, connectableExisting: already discovered but not connected }
export function checkForDiscoverableCities(
grid: Tile[][],
gridSize: number,
adjacentCities: AdjacentCity[]
): AdjacentCity[] {
const citiesToShow: AdjacentCity[] = [];
for (const city of adjacentCities) {
if (!city.connected && hasRoadAtEdge(grid, gridSize, city.direction)) {
// Include both undiscovered cities (they'll be discovered) and discovered-but-unconnected cities
if (!city.discovered) {
// This is a new discovery
citiesToShow.push(city);
}
// Note: We only return undiscovered cities here. For already-discovered cities,
// the UI can show them in a different way (e.g., a persistent indicator)
}
}
return citiesToShow;
}
// Check for cities that are discovered, have roads at their edge, but are not yet connected
// This can be used to remind players they can connect to a city
export function getConnectableCities(
grid: Tile[][],
gridSize: number,
adjacentCities: AdjacentCity[]
): AdjacentCity[] {
const connectable: AdjacentCity[] = [];
for (const city of adjacentCities) {
if (city.discovered && !city.connected && hasRoadAtEdge(grid, gridSize, city.direction)) {
connectable.push(city);
}
}
return connectable;
}
// Generate terrain - grass with scattered trees, lakes, and oceans
function generateTerrain(size: number): { grid: Tile[][]; waterBodies: WaterBody[] } {
const grid: Tile[][] = [];
const seed = Math.random() * 1000;
// First pass: create base terrain with grass
for (let y = 0; y < size; y++) {
const row: Tile[] = [];
for (let x = 0; x < size; x++) {
row.push(createTile(x, y, 'grass'));
}
grid.push(row);
}
// Second pass: add lakes (small contiguous water regions)
const lakeBodies = generateLakes(grid, size, seed);
// Third pass: add oceans on edges (sometimes)
const oceanBodies = generateOceans(grid, size, seed);
// Combine all water bodies
const waterBodies = [...lakeBodies, ...oceanBodies];
// Fourth pass: add scattered trees (avoiding water)
for (let y = 0; y < size; y++) {
for (let x = 0; x < size; x++) {
if (grid[y][x].building.type === 'water') continue; // Don't place trees on water
const treeNoise = perlinNoise(x * 2, y * 2, seed + 500, 2);
const isTree = treeNoise > 0.72 && Math.random() > 0.65;
// Also add some trees near water for visual appeal
const nearWater = isNearWater(grid, x, y, size);
const isTreeNearWater = nearWater && Math.random() > 0.7;
if (isTree || isTreeNearWater) {
grid[y][x].building = createBuilding('tree');
}
}
}
return { grid, waterBodies };
}
// Check if a tile is near water
function isNearWater(grid: Tile[][], x: number, y: number, size: number): boolean {
for (let dy = -2; dy <= 2; dy++) {
for (let dx = -2; dx <= 2; dx++) {
const nx = x + dx;
const ny = y + dy;
if (nx >= 0 && nx < size && ny >= 0 && ny < size) {
if (grid[ny][nx].building.type === 'water') {
return true;
}
}
}
}
return false;
}
// Building types that require water adjacency
const WATERFRONT_BUILDINGS: BuildingType[] = ['marina_docks_small', 'pier_large'];
// Check if a building type requires water adjacency
export function requiresWaterAdjacency(buildingType: BuildingType): boolean {
return WATERFRONT_BUILDINGS.includes(buildingType);
}
// Check if a building footprint is adjacent to water (for multi-tile buildings, any edge touching water counts)
// Returns whether water is found and if the sprite should be flipped to face it
// In isometric view, sprites can only be normal or horizontally mirrored
export function getWaterAdjacency(
grid: Tile[][],
x: number,
y: number,
width: number,
height: number,
gridSize: number
): { hasWater: boolean; shouldFlip: boolean } {
// In isometric view (looking from SE toward NW):
// - The default sprite faces toward the "front" (south-east in world coords)
// - To face the opposite direction, we flip horizontally
// Check all four edges and track which sides have water
let waterOnSouthOrEast = false; // "Front" sides - no flip needed
let waterOnNorthOrWest = false; // "Back" sides - flip needed
// Check south edge (y + height) - front-right in isometric view
for (let dx = 0; dx < width; dx++) {
const checkX = x + dx;
const checkY = y + height;
if (checkY < gridSize && grid[checkY]?.[checkX]?.building.type === 'water') {
waterOnSouthOrEast = true;
break;
}
}
// Check east edge (x + width) - front-left in isometric view
if (!waterOnSouthOrEast) {
for (let dy = 0; dy < height; dy++) {
const checkX = x + width;
const checkY = y + dy;
if (checkX < gridSize && grid[checkY]?.[checkX]?.building.type === 'water') {
waterOnSouthOrEast = true;
break;
}
}
}
// Check north edge (y - 1) - back-left in isometric view
for (let dx = 0; dx < width; dx++) {
const checkX = x + dx;
const checkY = y - 1;
if (checkY >= 0 && grid[checkY]?.[checkX]?.building.type === 'water') {
waterOnNorthOrWest = true;
break;
}
}
// Check west edge (x - 1) - back-right in isometric view
if (!waterOnNorthOrWest) {
for (let dy = 0; dy < height; dy++) {
const checkX = x - 1;
const checkY = y + dy;
if (checkX >= 0 && grid[checkY]?.[checkX]?.building.type === 'water') {
waterOnNorthOrWest = true;
break;
}
}
}
const hasWater = waterOnSouthOrEast || waterOnNorthOrWest;
// Only flip if water is on the back sides and NOT on the front sides
const shouldFlip = hasWater && waterOnNorthOrWest && !waterOnSouthOrEast;
return { hasWater, shouldFlip };
}
// Check if a building footprint is adjacent to roads and determine flip direction
// Similar to getWaterAdjacency but for roads - makes buildings face the road
export function getRoadAdjacency(
grid: Tile[][],
x: number,
y: number,
width: number,
height: number,
gridSize: number
): { hasRoad: boolean; shouldFlip: boolean } {
// In isometric view (looking from SE toward NW):
// - The default sprite faces toward the "front" (south-east in world coords)
// - To face the opposite direction, we flip horizontally
// Check all four edges and track which sides have roads
let roadOnSouthOrEast = false; // "Front" sides - no flip needed
let roadOnNorthOrWest = false; // "Back" sides - flip needed
// Check south edge (y + height) - front-right in isometric view
for (let dx = 0; dx < width; dx++) {
const checkX = x + dx;
const checkY = y + height;
const checkType = grid[checkY]?.[checkX]?.building.type;
if (checkY < gridSize && (checkType === 'road' || checkType === 'bridge')) {
roadOnSouthOrEast = true;
break;
}
}
// Check east edge (x + width) - front-left in isometric view
if (!roadOnSouthOrEast) {
for (let dy = 0; dy < height; dy++) {
const checkX = x + width;
const checkY = y + dy;
const checkType = grid[checkY]?.[checkX]?.building.type;
if (checkX < gridSize && (checkType === 'road' || checkType === 'bridge')) {
roadOnSouthOrEast = true;
break;
}
}
}
// Check north edge (y - 1) - back-left in isometric view
for (let dx = 0; dx < width; dx++) {
const checkX = x + dx;
const checkY = y - 1;
const checkType = grid[checkY]?.[checkX]?.building.type;
if (checkY >= 0 && (checkType === 'road' || checkType === 'bridge')) {
roadOnNorthOrWest = true;
break;
}
}
// Check west edge (x - 1) - back-right in isometric view
if (!roadOnNorthOrWest) {
for (let dy = 0; dy < height; dy++) {
const checkX = x - 1;
const checkY = y + dy;
const checkType = grid[checkY]?.[checkX]?.building.type;
if (checkX >= 0 && (checkType === 'road' || checkType === 'bridge')) {
roadOnNorthOrWest = true;
break;
}
}
}
const hasRoad = roadOnSouthOrEast || roadOnNorthOrWest;
// Only flip if road is on the back sides and NOT on the front sides
const shouldFlip = hasRoad && roadOnNorthOrWest && !roadOnSouthOrEast;
return { hasRoad, shouldFlip };
}
function createTile(x: number, y: number, buildingType: BuildingType = 'grass'): Tile {
return {
x,
y,
zone: 'none',
building: createBuilding(buildingType),
landValue: 50,
pollution: 0,
crime: 0,
traffic: 0,
hasSubway: false,
};
}
// Building types that don't require construction (already complete when placed)
const NO_CONSTRUCTION_TYPES: BuildingType[] = ['grass', 'empty', 'water', 'road', 'bridge', 'tree'];
function createBuilding(type: BuildingType): Building {
// Buildings that don't require construction start at 100% complete
const constructionProgress = NO_CONSTRUCTION_TYPES.includes(type) ? 100 : 0;
return {
type,
level: type === 'grass' || type === 'empty' || type === 'water' ? 0 : 1,
population: 0,
jobs: 0,
powered: false,
watered: false,
onFire: false,
fireProgress: 0,
age: 0,
constructionProgress,
abandoned: false,
};
}
// ============================================================================
// Bridge Detection and Creation
// ============================================================================
/** Maximum width of water a bridge can span */
const MAX_BRIDGE_SPAN = 10;
/** Bridge type thresholds based on span width */
const BRIDGE_TYPE_THRESHOLDS = {
large: 5, // 1-5 tiles = truss bridge
suspension: 10, // 6-10 tiles = suspension bridge
} as const;
/** Get the appropriate bridge type for a given span */
function getBridgeTypeForSpan(span: number): BridgeType {
// 1-tile bridges are simple bridges without trusses
if (span === 1) return 'small';
if (span <= BRIDGE_TYPE_THRESHOLDS.large) return 'large';
return 'suspension';
}
/** Number of variants per bridge type */
const BRIDGE_VARIANTS: Record<BridgeType, number> = {
small: 3,
medium: 3,
large: 2,
suspension: 2,
};
/** Generate a deterministic variant based on position */
function getBridgeVariant(x: number, y: number, bridgeType: BridgeType): number {
const seed = (x * 31 + y * 17) % 100;
return seed % BRIDGE_VARIANTS[bridgeType];
}
/** Create a bridge building with all metadata */
function createBridgeBuilding(
bridgeType: BridgeType,
orientation: BridgeOrientation,
variant: number,
position: 'start' | 'middle' | 'end',
index: number,
span: number,
trackType: 'road' | 'rail' = 'road'
): Building {
return {
type: 'bridge',
level: 0,
population: 0,
jobs: 0,
powered: true,
watered: true,
onFire: false,
fireProgress: 0,
age: 0,
constructionProgress: 100,
abandoned: false,
bridgeType,
bridgeOrientation: orientation,
bridgeVariant: variant,
bridgePosition: position,
bridgeIndex: index,
bridgeSpan: span,
bridgeTrackType: trackType,
};
}
/** Check if a tile at position is water */
function isWaterTile(grid: Tile[][], gridSize: number, x: number, y: number): boolean {
if (x < 0 || y < 0 || x >= gridSize || y >= gridSize) return false;
return grid[y][x].building.type === 'water';
}
/** Check if a tile at position is a road or bridge */
function isRoadOrBridgeTile(grid: Tile[][], gridSize: number, x: number, y: number): boolean {
if (x < 0 || y < 0 || x >= gridSize || y >= gridSize) return false;
const type = grid[y][x].building.type;
return type === 'road' || type === 'bridge';
}
/** Bridge opportunity data */
interface BridgeOpportunity {
startX: number;
startY: number;
endX: number;
endY: number;
orientation: BridgeOrientation;
span: number;
bridgeType: BridgeType;
waterTiles: { x: number; y: number }[];
trackType: 'road' | 'rail'; // What the bridge carries
}
/** Scan for a bridge opportunity in a specific direction */
function scanForBridgeInDirection(
grid: Tile[][],
gridSize: number,
startX: number,
startY: number,
dx: number,
dy: number,
orientation: BridgeOrientation,
trackType: 'road' | 'rail'
): BridgeOpportunity | null {
const waterTiles: { x: number; y: number }[] = [];
let x = startX + dx;
let y = startY + dy;
// Count consecutive water tiles
while (x >= 0 && x < gridSize && y >= 0 && y < gridSize) {
const tile = grid[y][x];
if (tile.building.type === 'water') {
waterTiles.push({ x, y });
// Check if we've exceeded max bridge span
if (waterTiles.length > MAX_BRIDGE_SPAN) {
return null; // Too wide to bridge
}
} else if (tile.building.type === trackType) {
// Found the same track type on the other side - valid bridge opportunity!
// Note: We only connect to the same track type, NOT to bridges
// This prevents creating spurious bridges when placing tracks near existing bridges
if (waterTiles.length > 0) {
const span = waterTiles.length;
const bridgeType = getBridgeTypeForSpan(span);
return {
startX,
startY,
endX: x,
endY: y,
orientation,
span,
bridgeType,
waterTiles,
trackType,
};
}
return null;
} else if (tile.building.type === 'bridge') {
// Found a bridge - don't create another bridge connecting to it
return null;
} else {
// Found land that's not the same track type - no bridge possible in this direction
break;
}
x += dx;
y += dy;
}
return null;
}
/** Detect if placing a road or rail creates a bridge opportunity from this tile */
function detectBridgeOpportunity(
grid: Tile[][],
gridSize: number,
x: number,
y: number,
trackType: 'road' | 'rail'
): BridgeOpportunity | null {
const tile = grid[y]?.[x];
if (!tile) return null;
// Only check from the specified track type tiles, not bridges
// Bridges should only be created when dragging across water to another tile of the same type
if (tile.building.type !== trackType) {
return null;
}
// Check each direction for water followed by same track type
// North (x-1, y stays same in grid coords)
const northOpp = scanForBridgeInDirection(grid, gridSize, x, y, -1, 0, 'ns', trackType);
if (northOpp) return northOpp;
// South (x+1, y stays same)
const southOpp = scanForBridgeInDirection(grid, gridSize, x, y, 1, 0, 'ns', trackType);
if (southOpp) return southOpp;
// East (x stays, y-1)
const eastOpp = scanForBridgeInDirection(grid, gridSize, x, y, 0, -1, 'ew', trackType);
if (eastOpp) return eastOpp;
// West (x stays, y+1)
const westOpp = scanForBridgeInDirection(grid, gridSize, x, y, 0, 1, 'ew', trackType);
if (westOpp) return westOpp;
return null;
}
/** Build bridges by converting water tiles to bridge tiles */
function buildBridges(
grid: Tile[][],
opportunity: BridgeOpportunity
): void {
const variant = getBridgeVariant(
opportunity.waterTiles[0].x,
opportunity.waterTiles[0].y,
opportunity.bridgeType
);
// Sort waterTiles consistently to ensure same result regardless of scan direction
// For NS orientation (bridges going NW-SE on screen): sort by x first (grid row), then by y
// For EW orientation (bridges going NE-SW on screen): sort by y first (grid column), then by x
// This ensures 'start' is always at the NW/NE end and 'end' at the SE/SW end
const sortedTiles = [...opportunity.waterTiles].sort((a, b) => {
if (opportunity.orientation === 'ns') {
// NS bridges: sort by x first (lower x = more NW on screen)
return a.x !== b.x ? a.x - b.x : a.y - b.y;
} else {
// EW bridges: sort by y first (lower y = more NE on screen)
return a.y !== b.y ? a.y - b.y : a.x - b.x;
}
});
const span = sortedTiles.length;
sortedTiles.forEach((pos, index) => {
let position: 'start' | 'middle' | 'end';
if (index === 0) {
position = 'start';
} else if (index === sortedTiles.length - 1) {
position = 'end';
} else {
position = 'middle';
}
grid[pos.y][pos.x].building = createBridgeBuilding(
opportunity.bridgeType,
opportunity.orientation,
variant,
position,
index,
span,
opportunity.trackType
);
// Keep the tile as having no zone
grid[pos.y][pos.x].zone = 'none';
});
}
/** Check and create bridges after road or rail placement */
function checkAndCreateBridges(
grid: Tile[][],
gridSize: number,
placedX: number,
placedY: number,
trackType: 'road' | 'rail'
): void {
// Check for bridge opportunities from the placed tile
const opportunity = detectBridgeOpportunity(grid, gridSize, placedX, placedY, trackType);
if (opportunity) {
buildBridges(grid, opportunity);
}