Repository navigation
Expand file tree
/
Copy pathbot_logic.py
More file actions
1493 lines (1270 loc) · 58.5 KB
/
Copy pathbot_logic.py
File metadata and controls
1493 lines (1270 loc) · 58.5 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
"""
NPC Bot AI for AstroWebEngine
Creates bot accounts and runs them through build-up cycles.
Bots upgrade buildings, research tech, build ships, colonize planets,
build defenses, and attack nearby enemies.
"""
import random
import math
import logging
from datetime import datetime, timedelta
from sqlalchemy.orm import Session
from sqlalchemy import or_
from models import (User, Colony, Building, Defense, Research, Fleet, Galaxy,
ConstructionQueue, ResearchQueue, Planet, StarSystem, Region, ShipQueue,
TradeRoute, ScoutedBase, ScoutedFleet, Commander)
from specs import BUILDING_SPECS, RESEARCH_SPECS, DEFENSE_SPECS
from auth import (hash_password, get_config, get_config_float, get_config_int,
get_effective_building_spec, get_effective_research_spec,
get_effective_defense_spec, get_effective_ship_spec,
get_all_building_specs, get_all_research_specs,
get_all_defense_specs, get_all_ship_specs,
is_building_disabled, is_research_disabled, is_defense_disabled,
ships_with_capability, fleet_capability_ship,
log_event, log_credits)
from game_logic import (calc_base_stats, calc_building_cost, calc_research_cost,
calc_defense_cost,
collect_resources, get_building_level, get_tech_level,
_ship_build_time, _check_completions, _process_ship_queues,
_process_fleet_arrivals, _fleet_is_empty,
project_resources_after_queue, _calc_distance)
from resources import (can_afford, deduct_cost, scale_cost, total_cost_value,
get_user_resources, seed_starting_resources)
from config_defaults import FLEET_TRAVEL_DIVISOR, JUMP_GATE_SPEED_BONUS_PER_LEVEL, COLONIZE_SCORE_BONUS
from combat import resolve_battle
logger = logging.getLogger("awe")
# Bot name pools
BOT_FIRST = [
"Admiral", "Captain", "Commander", "Lord", "Baron", "Duke", "General",
"Marshal", "Colonel", "Warlord", "Emperor", "Khan", "Overlord", "Sentinel",
"Phantom", "Shadow", "Iron", "Steel", "Dark", "Storm", "Thunder", "Nova",
"Stellar", "Cosmic", "Void", "Nexus", "Apex", "Prime", "Alpha", "Omega",
]
BOT_LAST = [
"Hawk", "Wolf", "Viper", "Raven", "Phoenix", "Dragon", "Falcon", "Titan",
"Reaper", "Hunter", "Striker", "Blaze", "Fury", "Surge", "Bolt", "Fang",
"Claw", "Edge", "Core", "Star", "Fleet", "Force", "Guard", "Shield",
"Blade", "Arrow", "Lance", "Axe", "Hammer", "Pike",
]
# Build priority orders for different strategies
BUILD_ORDER_BALANCED = [
("urban_structures", 2), ("solar_plants", 2), ("metal_refineries", 2),
("research_labs", 1), ("shipyard", 1),
("urban_structures", 4), ("solar_plants", 4), ("metal_refineries", 4),
("robotic_factories", 2), ("research_labs", 2), ("shipyard", 3),
("spaceports", 1), ("crystal_mines", 1),
("urban_structures", 6), ("solar_plants", 6), ("metal_refineries", 6),
("robotic_factories", 4), ("shipyard", 5), ("research_labs", 3),
("spaceports", 3), ("crystal_mines", 3),
("urban_structures", 8), ("solar_plants", 8), ("metal_refineries", 8),
("robotic_factories", 6), ("shipyard", 8), ("research_labs", 5),
("spaceports", 5), ("command_centers", 2),
("urban_structures", 10), ("solar_plants", 10), ("metal_refineries", 10),
("shipyard", 10), ("research_labs", 8),
]
RESEARCH_ORDER_BALANCED = [
("computer", 2), ("energy", 2), ("laser", 1), ("armour", 2),
("computer", 4), ("energy", 4), ("laser", 2), ("missiles", 1),
("armour", 4), ("stellar_drive", 1),
("energy", 6), ("laser", 4), ("plasma", 1), ("armour", 6),
("stellar_drive", 3), ("shielding", 1),
("energy", 8), ("armour", 8), ("plasma", 3), ("shielding", 2),
("warp_drive", 1), ("stellar_drive", 5),
("energy", 10), ("armour", 10), ("plasma", 5), ("shielding", 4),
]
BUILD_ORDER_BUILDER = [
("urban_structures", 3), ("solar_plants", 3), ("metal_refineries", 3),
("robotic_factories", 2), ("spaceports", 2), ("crystal_mines", 2),
("urban_structures", 6), ("solar_plants", 6), ("metal_refineries", 6),
("robotic_factories", 4), ("spaceports", 4), ("crystal_mines", 4),
("research_labs", 2), ("shipyard", 2),
("urban_structures", 10), ("solar_plants", 10), ("metal_refineries", 10),
("robotic_factories", 8), ("spaceports", 8), ("crystal_mines", 6),
("research_labs", 4), ("shipyard", 4),
("nanite_factories", 2), ("orbital_base", 1),
]
BUILD_ORDER_MILITARY = [
("urban_structures", 2), ("solar_plants", 2), ("metal_refineries", 2),
("shipyard", 2), ("research_labs", 1),
("urban_structures", 4), ("solar_plants", 4), ("metal_refineries", 4),
("shipyard", 5), ("research_labs", 2),
("robotic_factories", 2), ("command_centers", 2),
("urban_structures", 6), ("solar_plants", 6), ("metal_refineries", 6),
("shipyard", 8), ("research_labs", 3), ("command_centers", 4),
("urban_structures", 8), ("solar_plants", 8), ("metal_refineries", 8),
("shipyard", 12), ("research_labs", 5), ("command_centers", 6),
]
DEFENSE_ORDER_BALANCED = [
("barracks", 3), ("laser_turrets", 3),
("barracks", 5), ("laser_turrets", 5), ("missile_turrets", 3),
("plasma_turrets", 2), ("missile_turrets", 5),
]
DEFENSE_ORDER_BUILDER = [
("barracks", 5), ("laser_turrets", 5), ("missile_turrets", 5),
("plasma_turrets", 3), ("ion_turrets", 2),
]
DEFENSE_ORDER_MILITARY = [
("barracks", 2), ("laser_turrets", 2),
("barracks", 4), ("laser_turrets", 4),
]
# Extended research orders (Phase 2 — mid/late game)
RESEARCH_ORDER_PHASE2 = [
("computer", 6), ("energy", 12), ("laser", 6), ("plasma", 6),
("armour", 12), ("shielding", 6), ("warp_drive", 4),
("ion", 1), ("plasma", 8), ("armour", 14),
("ion", 4), ("shielding", 8), ("warp_drive", 8),
("photon", 1), ("armour", 16), ("shielding", 10),
]
# Extended build orders (Phase 2 — expand economy for late game)
BUILD_ORDER_PHASE2 = [
("urban_structures", 12), ("solar_plants", 12), ("metal_refineries", 12),
("robotic_factories", 8), ("nanite_factories", 2), ("shipyard", 12),
("research_labs", 10), ("spaceports", 8), ("command_centers", 4),
("economic_centers", 2), ("orbital_base", 2),
("shipyard", 14), ("research_labs", 12),
("nanite_factories", 4), ("android_factories", 2),
("shipyard", 16),
]
# Max colonies per simulated player-bot strategy. NPC faction accounts use
# strategy keys "settlers"/"raiders", which intentionally fall back to one fixed base.
MAX_COLONIES = {"balanced": 4, "builder": 5, "military": 3}
STRATEGIES = {
"balanced": (BUILD_ORDER_BALANCED, RESEARCH_ORDER_BALANCED, DEFENSE_ORDER_BALANCED),
"builder": (BUILD_ORDER_BUILDER, RESEARCH_ORDER_BALANCED, DEFENSE_ORDER_BUILDER),
"military": (BUILD_ORDER_MILITARY, RESEARCH_ORDER_BALANCED, DEFENSE_ORDER_MILITARY),
}
NPC_FACTIONS = {
"settlers": {
"username": "Settlers",
"email": "settlers@npc.local",
"base_prefix": "Settler Base",
"starting_credits": 500.0,
},
"raiders": {
"username": "Raiders",
"email": "raiders@npc.local",
"base_prefix": "Raider Base",
"starting_credits": 500.0,
},
}
NPC_STRATEGIES = set(NPC_FACTIONS.keys())
NPC_ALIASES = {
"settlers": "settlers",
"settler": "settlers",
"raiders": "raiders",
"raider": "raiders",
}
def normalize_npc_type(npc_type: str = "settlers") -> str:
"""Normalize admin-facing NPC names into stable faction keys."""
key = str(npc_type or "settlers").strip().lower()
key = NPC_ALIASES.get(key, key)
if key not in NPC_FACTIONS:
raise ValueError(f"Unknown NPC type '{npc_type}'. Use 'settlers', 'raiders', or 'both'.")
return key
def get_or_create_npc_account(db: Session, npc_type: str = "settlers") -> User:
"""Return the shared account for an NPC faction, creating it if needed."""
faction_key = normalize_npc_type(npc_type)
faction = NPC_FACTIONS[faction_key]
user = db.query(User).filter(User.username == faction["username"]).first()
if not user:
user = db.query(User).filter(User.email == faction["email"]).first()
if user and not user.is_bot:
raise ValueError(f"NPC username '{faction['username']}' is already used by a player account")
if not user:
user = User(
username=faction["username"],
email=faction["email"],
hashed_password=hash_password(f"npc_{faction_key}_{random.randint(10000, 99999)}"),
is_bot=True,
bot_strategy=faction_key,
credits=faction["starting_credits"],
)
db.add(user)
seed_starting_resources(user) # multi-resource economies: starting stash
db.flush()
else:
user.is_bot = True
user.bot_strategy = faction_key
if not user.email:
user.email = faction["email"]
for tech_type in RESEARCH_SPECS.keys():
existing = db.query(Research).filter(
Research.user_id == user.id,
Research.tech_type == tech_type,
).first()
if not existing:
db.add(Research(user_id=user.id, tech_type=tech_type, level=0))
db.flush()
return user
def _server_midnight(dt: datetime) -> datetime:
return dt.replace(hour=0, minute=0, second=0, microsecond=0)
def _parse_config_datetime(value: str):
if not value:
return None
text = str(value).strip()
if not text:
return None
try:
return datetime.fromisoformat(text.replace("Z", "+00:00")).replace(tzinfo=None)
except ValueError:
return None
def _config_bool(db: Session, key: str, default: bool = True) -> bool:
raw = get_config(db, key, "true" if default else "false")
return str(raw).strip().lower() not in ("0", "false", "no", "off", "")
def _clamp_fraction(value: float, default: float) -> float:
try:
parsed = float(value)
except (TypeError, ValueError):
parsed = default
return max(0.0, min(1.0, parsed))
def get_settlers_target_per_galaxy(db: Session, now: datetime = None) -> int:
"""Settlers target: starts high, drops yearly, floors at minimum."""
now = now or datetime.utcnow()
start = max(0, get_config_int(db, "NPC_SETTLERS_BASES_START", 5))
minimum = max(0, get_config_int(db, "NPC_SETTLERS_BASES_MIN", 2))
reduction = max(0, get_config_int(db, "NPC_SETTLERS_BASES_REDUCTION_PER_YEAR", 1))
started_at = _parse_config_datetime(get_config(db, "game_started_at", ""))
years = 0
if started_at:
years = max(0, (now.date() - started_at.date()).days // 365)
return max(minimum, start - reduction * years)
def _initialize_npc_base_state(db: Session, user: User, colony: Colony, now: datetime = None):
now = now or datetime.utcnow()
if user.bot_strategy == "settlers":
colony.npc_stability = _clamp_fraction(
get_config_float(db, "NPC_SETTLERS_STABILITY_INITIAL", 1.0),
1.0,
)
colony.npc_last_stability_tick = _server_midnight(now)
else:
colony.npc_stability = None
colony.npc_last_stability_tick = None
def delete_npc_colony(db: Session, colony: Colony, delete_empty_account: bool = False):
"""Delete one NPC base and local data without wiping shared faction accounts."""
bot = colony.user or db.query(User).filter(User.id == colony.user_id).first()
planet_id = colony.planet_id
db.query(ShipQueue).filter(ShipQueue.colony_id == colony.id).delete(synchronize_session=False)
db.query(ConstructionQueue).filter(ConstructionQueue.colony_id == colony.id).delete(synchronize_session=False)
db.query(ResearchQueue).filter(ResearchQueue.colony_id == colony.id).delete(synchronize_session=False)
db.query(Commander).filter(Commander.user_id == colony.user_id, Commander.colony_id == colony.id).delete(synchronize_session=False)
db.query(TradeRoute).filter(or_(TradeRoute.base_a_id == colony.id, TradeRoute.base_b_id == colony.id)).delete(synchronize_session=False)
db.query(ScoutedBase).filter(ScoutedBase.planet_id == planet_id).delete(synchronize_session=False)
db.query(ScoutedFleet).filter(ScoutedFleet.planet_id == planet_id).delete(synchronize_session=False)
# Foreign fleets at a disbanded base become orbiting fleets at the same astro.
for foreign_fleet in db.query(Fleet).filter(Fleet.user_id != colony.user_id, Fleet.base_id == colony.id).all():
foreign_fleet.base_id = None
foreign_fleet.location_planet_id = planet_id
for inbound_fleet in db.query(Fleet).filter(Fleet.destination_base_id == colony.id).all():
inbound_fleet.destination_base_id = None
inbound_fleet.destination_planet_id = planet_id
for fleet in db.query(Fleet).filter(
Fleet.user_id == colony.user_id,
or_(
Fleet.base_id == colony.id,
Fleet.origin_base_id == colony.id,
Fleet.destination_base_id == colony.id,
Fleet.location_planet_id == planet_id,
Fleet.origin_planet_id == planet_id,
Fleet.destination_planet_id == planet_id,
),
).all():
db.delete(fleet)
if colony.planet:
colony.planet.is_colonized = False
db.delete(colony)
db.flush()
if bot and delete_empty_account and bot.bot_strategy not in ("settlers", "raiders"):
remaining = db.query(Colony).filter(Colony.user_id == bot.id).count()
if remaining == 0:
db.query(ResearchQueue).filter(ResearchQueue.user_id == bot.id).delete(synchronize_session=False)
db.query(Research).filter(Research.user_id == bot.id).delete(synchronize_session=False)
db.query(Fleet).filter(Fleet.user_id == bot.id).delete(synchronize_session=False)
db.delete(bot)
def process_settlers_stability(db: Session, now: datetime = None):
"""Apply Settlers daily stability decay and disband bases at 0%."""
if not _config_bool(db, "NPC_SETTLERS_STABILITY_ENABLED", True):
return {"processed": 0, "disbanded": 0, "created": 0}
now = now or datetime.utcnow()
current_midnight = _server_midnight(now)
initial = _clamp_fraction(get_config_float(db, "NPC_SETTLERS_STABILITY_INITIAL", 1.0), 1.0)
decay = max(0.0, get_config_float(db, "NPC_SETTLERS_STABILITY_DECAY_PER_DAY", 0.03))
settlers = db.query(User).filter(User.is_bot == True, User.bot_strategy == "settlers").first()
if not settlers:
return {"processed": 0, "disbanded": 0, "created": 0}
processed = 0
disbanded = 0
for colony in list(settlers.colonies):
if colony.npc_stability is None:
colony.npc_stability = initial
if colony.npc_last_stability_tick is None:
colony.npc_last_stability_tick = current_midnight
continue
last_midnight = _server_midnight(colony.npc_last_stability_tick)
days = (current_midnight.date() - last_midnight.date()).days
if days <= 0:
continue
processed += 1
colony.npc_stability = max(0.0, (colony.npc_stability or initial) - decay * days)
colony.npc_last_stability_tick = current_midnight
if colony.npc_stability <= 0:
base_name = colony.name
delete_npc_colony(db, colony)
disbanded += 1
logger.info(f"[npc-stability] Settlers base disbanded: {base_name}")
db.commit()
maintenance = maintain_settlers_bases(db, now=now, settlers_user=settlers)
return {
"processed": processed,
"disbanded": disbanded,
"created": maintenance.get("created", 0),
"target_per_galaxy": maintenance.get("target_per_galaxy", get_settlers_target_per_galaxy(db, now)),
}
def maintain_settlers_bases(db: Session, now: datetime = None, settlers_user: User = None):
"""Top up Settlers bases to the configured per-galaxy target."""
if not _config_bool(db, "NPC_SETTLERS_AUTO_MAINTAIN_ENABLED", True):
return {"created": 0, "target_per_galaxy": get_settlers_target_per_galaxy(db, now)}
now = now or datetime.utcnow()
target = get_settlers_target_per_galaxy(db, now)
if target <= 0:
return {"created": 0, "target_per_galaxy": target}
settlers = settlers_user or db.query(User).filter(User.is_bot == True, User.bot_strategy == "settlers").first()
if not settlers:
return {"created": 0, "target_per_galaxy": target}
created = 0
for galaxy in db.query(Galaxy).order_by(Galaxy.id).all():
result = create_bot_accounts(db, count=target, galaxy_id=galaxy.id, npc_type="settlers")
created += len(result)
if created:
logger.info(f"[npc-stability] Created {created} Settlers replacement base(s)")
return {"created": created, "target_per_galaxy": target}
def _npc_colony_count_in_galaxy(db: Session, user_id: int, galaxy_id: int) -> int:
return (
db.query(Colony)
.join(Planet, Colony.planet_id == Planet.id)
.join(StarSystem, Planet.system_id == StarSystem.id)
.join(Region, StarSystem.region_id == Region.id)
.filter(Colony.user_id == user_id, Region.galaxy_id == galaxy_id)
.count()
)
def create_bot_accounts(db: Session, count: int = 4, galaxy_id: int = None, npc_type: str = "settlers"):
"""Create NPC bases under one shared faction account.
If galaxy_id is provided, count is treated as the target number of bases
for that NPC faction in that galaxy.
"""
created = []
faction_key = normalize_npc_type(npc_type)
faction = NPC_FACTIONS[faction_key]
user = get_or_create_npc_account(db, faction_key)
target_count = max(0, int(count or 0))
if galaxy_id:
existing_count = _npc_colony_count_in_galaxy(db, user.id, galaxy_id)
create_count = max(0, target_count - existing_count)
else:
create_count = target_count
for _ in range(create_count):
base = _assign_homeworld_in_galaxy(
user,
db,
galaxy_id,
base_name_prefix=faction["base_prefix"],
)
if not base:
break
db.flush()
created.append({
"account_id": user.id,
"account": user.username,
"npc_type": faction_key,
"base_id": base.id,
"base_name": base.name,
"planet_id": base.planet_id,
"galaxy_id": galaxy_id,
})
logger.info(f"[bot] Created NPC base: {base.name} ({user.username}) galaxy={galaxy_id}")
db.commit()
return created
def create_simulated_bot_accounts(db: Session, count: int = 10, galaxy_id: int = None):
"""Create classic simulated player bots, one account per bot/base."""
created = []
strategies = ["balanced", "builder", "military"]
for _ in range(max(0, int(count or 0))):
for _attempt in range(50):
name = f"{random.choice(BOT_FIRST)}{random.choice(BOT_LAST)}{random.randint(1, 999)}"
existing = db.query(User).filter(User.username == name).first()
if not existing:
break
else:
continue
strategy = random.choice(strategies)
user = User(
username=name,
email=f"{name.lower()}@bot.local",
hashed_password=hash_password(f"bot_{name}_{random.randint(10000, 99999)}"),
is_bot=True,
bot_strategy=strategy,
credits=500.0,
)
db.add(user)
seed_starting_resources(user) # multi-resource economies: starting stash
db.flush()
base = _assign_homeworld_in_galaxy(user, db, galaxy_id)
if not base:
db.delete(user)
continue
db.flush()
created.append({
"id": user.id,
"account_id": user.id,
"account": user.username,
"name": user.username,
"strategy": strategy,
"npc_type": "simulated",
"base_id": base.id,
"base_name": base.name,
"planet_id": base.planet_id,
"galaxy_id": galaxy_id,
})
logger.info(f"[bot] Created simulated bot: {name} ({strategy}) galaxy={galaxy_id}")
db.commit()
return created
def _assign_homeworld_in_galaxy(user, db, galaxy_id=None, base_name_prefix=None):
"""Assign an NPC base within a specific galaxy, or anywhere if no galaxy is given."""
from models import Planet, StarSystem, Region, Colony, Building, Defense, Research, Fleet
from specs import BUILDING_SPECS, RESEARCH_SPECS, DEFENSE_SPECS
# Prefer available 3rd-orbit Earthly planets, matching normal homeworld placement.
query = (
db.query(Planet)
.join(StarSystem, Planet.system_id == StarSystem.id)
.join(Region, StarSystem.region_id == Region.id)
.filter(
Planet.is_colonized == False,
Planet.planet_type == "earthly",
Planet.orbit_position == 3,
)
)
if galaxy_id:
query = query.filter(Region.galaxy_id == galaxy_id)
candidates = query.all()
if not candidates:
# Fallback: any uncolonized planet in this galaxy.
query = (
db.query(Planet)
.join(StarSystem, Planet.system_id == StarSystem.id)
.join(Region, StarSystem.region_id == Region.id)
.filter(
Planet.is_colonized == False,
)
)
if galaxy_id:
query = query.filter(Region.galaxy_id == galaxy_id)
candidates = query.all()
if not candidates:
# No planets available in this galaxy at all — skip
logger.warning(f"[bot] No available planets in galaxy {galaxy_id} for {user.username}")
return None
planet = random.choice(candidates)
planet.is_colonized = True
base_name = f"{base_name_prefix} {planet.name}" if base_name_prefix else f"{user.username}'s Homeworld"
base = Colony(planet_id=planet.id, user_id=user.id, name=base_name[:50])
db.add(base)
db.flush()
_initialize_npc_base_state(db, user, base)
# Starter buildings — same as players: only Urban Structures Lv1
# Guard against duplicates: only add if colony has no buildings yet
existing_buildings = db.query(Building).filter(Building.colony_id == base.id).count()
if existing_buildings == 0:
for bt, bspec in BUILDING_SPECS.items():
db.add(Building(colony_id=base.id, building_type=bt, level=bspec.get("start_level", 0)))
# Initialize defenses
existing_defenses = db.query(Defense).filter(Defense.colony_id == base.id).count()
if existing_defenses == 0:
for dt in DEFENSE_SPECS.keys():
db.add(Defense(colony_id=base.id, defense_type=dt, level=0))
# Initialize research
for tt in RESEARCH_SPECS.keys():
existing = db.query(Research).filter(Research.user_id == user.id, Research.tech_type == tt).first()
if not existing:
db.add(Research(user_id=user.id, tech_type=tt, level=0))
# Starter fleet
db.add(Fleet(name="Home Fleet", user_id=user.id, base_id=base.id))
user.score += 10
user.bases_founded_peak = max(getattr(user, "bases_founded_peak", 0) or 0, len(user.colonies))
return base
def _bot_wealth(bot: User) -> float:
"""A scalar proxy for a bot's spendable wealth that works for both single-
and multi-resource economies (sum of all resource balances). Bot strategy
thresholds/spend-percentages are scalar by nature, so they compare against
this; the actual transactions use can_afford/deduct_cost (which preserve
per-resource costs)."""
return total_cost_value(get_user_resources(bot))
def _roster_order(specs, classic_order, tiers, keep):
"""Build a bot priority order for the ACTIVE roster: classic entries that
still exist (preserving the tuned classic strategy), then every other roster
key cost-sorted and escalated across `tiers`. On the classic roster the
extras are empty; on a different ruleset the classic keys don't exist, so the
order becomes fully roster-derived — which is what lets bots play any
definition instead of going inert."""
existing = set(specs.keys())
in_classic = {k for k, _ in classic_order}
out = [(k, lvl) for (k, lvl) in classic_order if k in existing]
def _cost(k):
s = specs.get(k, {})
return total_cost_value(s.get("base_cost", s.get("cost", 1)) or 1)
extras = sorted((k for k in existing if k not in in_classic and keep(k)), key=_cost)
for t in tiers:
out.extend((k, t) for k in extras)
return out
def _effective_build_order(db, classic_order):
return _roster_order(get_all_building_specs(db), classic_order,
(2, 4, 6, 8, 10, 12, 16), lambda k: not is_building_disabled(db, k))
def _effective_research_order(db, classic_order):
return _roster_order(get_all_research_specs(db), classic_order,
(2, 4, 6, 8, 10, 12), lambda k: not is_research_disabled(db, k))
def _effective_defense_order(db, classic_order):
return _roster_order(get_all_defense_specs(db), classic_order,
(3, 6, 10, 20), lambda k: not is_defense_disabled(db, k))
def tick_bots(db: Session, include_stats: bool = False):
"""Run one AI tick for all bot accounts.
Call this periodically (e.g., every 30-60 seconds) from a background task.
Each bot: collects resources, checks completions, queues next build/research, builds ships.
"""
game_speed = get_config_float(db, "game_speed", 1.0)
now = datetime.utcnow()
bots = db.query(User).filter(User.is_bot == True).all()
for bot in bots:
try:
_tick_single_bot(bot, db, game_speed, now)
except Exception as e:
logger.error(f"[bot] Error ticking {bot.username}: {e}")
db.commit()
if include_stats:
return collect_bot_stats(db)
return None
def collect_bot_stats(db: Session):
"""Return lightweight aggregate stats for the current bot population."""
bots = db.query(User).filter(User.is_bot == True).all()
total_colonies = 0
total_fleets = 0
moving_fleets = 0
orbiting_fleets = 0
staged_attacks = 0
total_credits = 0.0
total_combat_power = 0
strategies = {"settlers": 0, "raiders": 0, "balanced": 0, "builder": 0, "military": 0, "other": 0}
top_bot = None
for bot in bots:
total_colonies += len(bot.colonies)
total_credits += _bot_wealth(bot)
strategy = bot.bot_strategy or "other"
if strategy not in strategies:
strategy = "other"
strategies[strategy] += 1
if top_bot is None or (bot.score or 0) > (top_bot.score or 0):
top_bot = bot
for fleet in bot.fleets:
total_fleets += 1
if fleet.is_moving:
moving_fleets += 1
if fleet.location_planet_id and not fleet.base_id:
orbiting_fleets += 1
planet = db.query(Planet).filter(Planet.id == fleet.location_planet_id).first()
if planet and getattr(planet, "colony", None) and planet.colony.user_id != bot.id:
staged_attacks += 1
total_combat_power += _fleet_combat_power(fleet, db)
return {
"bots": len(bots),
"colonies": total_colonies,
"avg_colonies": round(total_colonies / len(bots), 2) if bots else 0,
"fleets": total_fleets,
"moving_fleets": moving_fleets,
"orbiting_fleets": orbiting_fleets,
"staged_attacks": staged_attacks,
"total_credits": round(total_credits),
"total_combat_power": round(total_combat_power),
"strategies": strategies,
"top_bot": (
{
"username": top_bot.username,
"score": round(top_bot.score or 0),
"bases": len(top_bot.colonies),
}
if top_bot else None
),
}
def _tick_single_bot(bot: User, db: Session, game_speed: float, now: datetime):
"""AI logic for a single bot account."""
# 1. Collect resources, check completions, process ship/fleet arrivals
collect_resources(bot, db, game_speed)
_process_ship_queues(bot, db, game_speed)
_process_fleet_arrivals(bot, db)
if (bot.bot_strategy or "") in NPC_STRATEGIES:
return
# 2. For each colony, try to queue construction
strategy_name = bot.bot_strategy or "balanced"
build_order, research_order, defense_order = STRATEGIES.get(strategy_name, STRATEGIES["balanced"])
# Extend build/research orders with Phase 2, then resolve against the ACTIVE
# roster (classic items that exist + roster-derived extras) so bots play any
# ruleset, not just the classic one.
full_build_order = _effective_build_order(db, list(build_order) + BUILD_ORDER_PHASE2)
full_research_order = _effective_research_order(db, list(research_order) + RESEARCH_ORDER_PHASE2)
full_defense_order = _effective_defense_order(db, defense_order)
for colony in bot.colonies:
_bot_try_construct(bot, colony, db, game_speed, full_build_order, now)
# 3. Try to queue research
_bot_try_research(bot, db, game_speed, full_research_order, now)
# 4. Build defenses on each colony
for colony in bot.colonies:
_bot_try_build_defenses(bot, colony, db, game_speed, full_defense_order, now)
# 5. Build ships if shipyard is high enough and we have credits
for colony in bot.colonies:
_bot_try_build_ships(bot, colony, db, game_speed, now)
# 6. Colonize new planets if a colonizer ship is available and below colony limit.
_bot_try_colonize(bot, db, game_speed, now, strategy_name)
# 7. If a combat fleet is already staged over an enemy planet, attack immediately.
if _bot_try_attack(bot, db, game_speed, now, launch_only=False):
return
# 8. Otherwise, sometimes launch a new attack wave.
if random.random() < 0.1: # 10% chance per tick
_bot_try_attack(bot, db, game_speed, now, launch_only=True)
def _noncombat_ship_keys(db: Session) -> set:
"""Ship keys that are support units (colonizer / recycler / scout), resolved
from the active roster's capabilities rather than hard-coded keys. Used to
exclude them from combat-power and fleet-size estimates so the bot AI works
on any roster, not just the classic one."""
keys = set()
for cap in ("can_colonize", "can_recycle", "can_autoscout"):
keys.update(ships_with_capability(db, cap))
return keys
def _fleet_combat_power(fleet, db: Session):
"""Cheap fleet power estimate for bot targeting decisions."""
power = 0
noncombat = _noncombat_ship_keys(db)
for st, count in fleet.get_all_ship_counts().items():
if count > 0 and st not in noncombat:
spec = get_effective_ship_spec(db, st)
power += count * spec.get("attack", 0)
return power
def _estimate_colony_defense_power(colony: Colony, db: Session):
"""Rough colony defense+fleet strength estimate for bot caution checks."""
def_power = 0
for d in colony.defenses:
if d.level > 0:
dspec = get_effective_defense_spec(db, d.defense_type)
def_power += d.level * dspec.get("attack", 0)
def_fleets = db.query(Fleet).filter(
Fleet.base_id == colony.id,
Fleet.is_moving == False,
Fleet.user_id == colony.user_id,
).all()
for df in def_fleets:
def_power += _fleet_combat_power(df, db)
return def_power
def _bot_try_construct(bot: User, colony: Colony, db: Session, game_speed: float,
build_order: list, now: datetime):
"""Try to queue the next building upgrade for a bot's colony."""
# Check queue size
queue = (db.query(ConstructionQueue)
.filter(ConstructionQueue.colony_id == colony.id,
ConstructionQueue.user_id == bot.id)
.order_by(ConstructionQueue.position).all())
if len(queue) >= 3: # Bots only use 3 of 5 queue slots
return
stats = calc_base_stats(colony, bot, game_speed)
# Find next building to upgrade from the build order
for building_type, target_level in build_order:
if is_building_disabled(db, building_type):
continue
building = next((b for b in colony.buildings if b.building_type == building_type), None)
if not building:
continue
# Get effective level including queued items
effective_level = building.level
for q in queue:
if q.item_category == 'building' and q.item_type == building_type:
effective_level = q.target_level
if effective_level >= target_level:
continue # Already at or past target
spec = get_effective_building_spec(db, building_type)
if not spec:
continue
max_lv = spec.get("max_level", 0)
if max_lv > 0 and effective_level >= max_lv:
continue
# Skip buildings that depend on planet resources the planet doesn't have
planet = colony.planet
if building_type == "crystal_mines" and planet.crystal <= 0:
continue
if building_type == "solar_plants" and planet.solar <= 0:
continue
if building_type == "gas_plants" and planet.gas <= 0:
continue
if building_type == "metal_refineries" and planet.metal <= 0:
continue
# Check tech requirements
tech_ok = True
for tech, level_needed in spec.get("tech_req", {}).items():
if get_tech_level(bot, tech) < level_needed:
tech_ok = False
break
if not tech_ok:
continue
# Smart resource check: project resources after queued items complete
projected = project_resources_after_queue(colony, bot, queue, db)
energy_req = spec.get("energy_req", 0)
pop_req = spec.get("pop_req", 0)
area_req = spec.get("area_req", 0)
if energy_req > 0 and projected["energy"] - projected["energy_used"] < energy_req:
continue
if pop_req > 0 and projected["population"] - projected["pop_used"] < pop_req:
continue
if area_req > 0 and projected["area"] - projected["area_used"] < area_req:
continue
# Calculate cost
cost, build_time = calc_building_cost(db, building_type, effective_level, stats, game_speed)
if not can_afford(bot, cost):
continue # Not enough resources, try next
# Queue it — only deduct cost for position 0 (active item)
# Queued items get charged when they become active in _advance_construction_queue
position = len(queue)
if position == 0:
deduct_cost(bot, cost)
if position == 0:
building.is_constructing = True
building.construction_end = now + timedelta(seconds=build_time)
finish_at = building.construction_end
started_at = now
else:
finish_at = None
started_at = None
qi = ConstructionQueue(
colony_id=colony.id, user_id=bot.id, position=position,
item_category='building', item_type=building_type,
target_level=effective_level + 1, cost=cost, build_time=build_time,
started_at=started_at, finish_at=finish_at
)
db.add(qi)
queue.append(qi)
if len(queue) >= 3:
break # Queue is full enough
def _bot_try_research(bot: User, db: Session, game_speed: float,
research_order: list, now: datetime):
"""Try to queue the next research for a bot. Uses best research base."""
# Pick the best research base (highest lab level)
best_base = max(bot.colonies, key=lambda c: get_building_level(c, "research_labs"), default=None)
if not best_base or get_building_level(best_base, "research_labs") <= 0:
return
queue = (db.query(ResearchQueue)
.filter(ResearchQueue.user_id == bot.id,
ResearchQueue.colony_id == best_base.id)
.order_by(ResearchQueue.position).all())
if len(queue) >= 3: # Bots use 3 of 6 slots
return
base_lab_level = get_building_level(best_base, "research_labs")
base_lab_capacity = calc_base_stats(best_base, bot, game_speed).get("research", 0)
if base_lab_capacity <= 0:
return
# Get all actively researching techs across all bases
active_techs = set()
active_items = db.query(ResearchQueue.tech_type).filter(
ResearchQueue.user_id == bot.id,
ResearchQueue.position == 0,
ResearchQueue.finish_at != None,
).all()
for row in active_items:
active_techs.add(row[0])
# If the bot already has a shipyard, grab the fighter unlock quickly so fleets
# start existing earlier in a fresh simulation.
if get_building_level(best_base, "shipyard") >= 1 and get_tech_level(bot, "laser") < 1:
queued_laser = db.query(ResearchQueue).filter(
ResearchQueue.user_id == bot.id,
ResearchQueue.tech_type == "laser",
).first()
if not queued_laser:
research_order = [("laser", 1)] + list(research_order)
for tech_type, target_level in research_order:
if is_research_disabled(db, tech_type):
continue
r = next((r for r in bot.research if r.tech_type == tech_type), None)
if not r:
continue
# Get effective level including queued across all bases
effective_level = r.level
all_queued = (db.query(ResearchQueue)
.filter(ResearchQueue.user_id == bot.id,
ResearchQueue.tech_type == tech_type)
.order_by(ResearchQueue.target_level.desc()).first())
if all_queued:
effective_level = all_queued.target_level
if effective_level >= target_level:
continue
spec = get_effective_research_spec(db, tech_type)
if not spec:
continue
# Check prerequisites
prereqs_ok = True
for prereq_tech, prereq_level in spec.get("prereqs", {}).items():
if get_tech_level(bot, prereq_tech) < prereq_level:
prereqs_ok = False
break
if not prereqs_ok:
continue
# Check lab requirement against this base
if base_lab_level < spec.get("lab_req", 1):
continue
cost, research_time = calc_research_cost(db, tech_type, effective_level, game_speed, base_lab_capacity, colony_id=best_base.id)
if not can_afford(bot, cost):
continue
position = len(queue)
# Check tech conflict for position 0
can_start = True
if position == 0 and tech_type in active_techs:
can_start = False
if position == 0 and can_start:
deduct_cost(bot, cost)
r.is_researching = True
r.research_end = now + timedelta(seconds=research_time)
finish_at = r.research_end
started_at = now
else:
finish_at = None
started_at = None
qi = ResearchQueue(
user_id=bot.id, colony_id=best_base.id, position=position,
tech_type=tech_type, target_level=effective_level + 1,
cost=cost, research_time=research_time,
started_at=started_at, finish_at=finish_at
)
db.add(qi)
queue.append(qi)
if len(queue) >= 3:
break
def _bot_try_build_ships(bot: User, colony: Colony, db: Session,
game_speed: float, now: datetime):
"""Build ships via the production queue (same as players)."""
sy_level = get_building_level(colony, "shipyard")
if sy_level < 1:
return
# Skip if this base already has an active ship queue
existing = db.query(ShipQueue).filter(ShipQueue.colony_id == colony.id).first()
if existing and existing.built < existing.count:
return