-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgame.py
More file actions
1435 lines (1192 loc) · 50.5 KB
/
game.py
File metadata and controls
1435 lines (1192 loc) · 50.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
import random
import sys
import json
import os
import glob
import csv
from dataclasses import dataclass, field, asdict
from typing import List, Optional
# Import running board functionality
from running_boards import (
RunningBoard, Trip,
create_running_board_interactive,
view_running_boards,
list_running_boards,
load_running_board,
save_running_board,
create_running_boards_from_csv,
create_running_boards_batch,
view_running_board_logs,
log_running_board_action
)
@dataclass
class Stop:
name: str
minutes_from_prev: int # Changed from distance_from_prev_km
def to_dict(self):
return asdict(self)
@staticmethod
def from_dict(data):
# Support both old and new format for backwards compatibility
if "minutes_from_prev" in data:
return Stop(name=data["name"], minutes_from_prev=data["minutes_from_prev"])
else:
# Convert old km data to minutes (assuming avg speed of 30 km/h)
minutes = int(data.get("distance_from_prev_km", 0) * 2)
return Stop(name=data["name"], minutes_from_prev=minutes)
@dataclass
class Route:
name: str
stops: List[Stop]
base_schedule_minutes: int
current_schedule_minutes: int
assigned_bus_id: Optional[int] = None
def to_dict(self):
return {
"name": self.name,
"stops": [stop.to_dict() for stop in self.stops],
"base_schedule_minutes": self.base_schedule_minutes,
"current_schedule_minutes": self.current_schedule_minutes,
"assigned_bus_id": self.assigned_bus_id,
}
@staticmethod
def from_dict(data):
stops = [Stop.from_dict(s) for s in data["stops"]]
return Route(
name=data["name"],
stops=stops,
base_schedule_minutes=data["base_schedule_minutes"],
current_schedule_minutes=data["current_schedule_minutes"],
assigned_bus_id=data.get("assigned_bus_id"),
)
@dataclass
class Bus:
bus_id: int
model: str
capacity: int
fuel_capacity: float
fuel_level: float
fuel_efficiency: float # litres/km at 50 km/h
assigned_route: Optional[str] = None
health: int = 100
purchase_price: float = 0.0
fleet_number: Optional[str] = None
dlc_source: Optional[str] = None # Track which DLC this bus came from
livery: str = "Standard" # New: Bus livery/color scheme
def consume_fuel(self, minutes, speed=30):
# Convert minutes to distance assuming average speed
distance = (minutes / 60) * speed
speed_factor = speed / 50
used = distance * self.fuel_efficiency * speed_factor
self.fuel_level = max(self.fuel_level - used, 0)
return used
def to_dict(self):
data = asdict(self)
return data
@staticmethod
def from_dict(data):
return Bus(
bus_id=data["bus_id"],
model=data["model"],
capacity=data["capacity"],
fuel_capacity=data["fuel_capacity"],
fuel_level=data["fuel_level"],
fuel_efficiency=data["fuel_efficiency"],
assigned_route=data.get("assigned_route"),
health=data.get("health", 100),
purchase_price=data.get("purchase_price", 0.0),
fleet_number=data.get("fleet_number"),
dlc_source=data.get("dlc_source"),
livery=data.get("livery", "Standard"),
)
@dataclass
class ManagerState:
company_name: str
routes: List[Route] = field(default_factory=list)
fleet: List[Bus] = field(default_factory=list)
money: float = 2500000.0
reputation: float = 50.0
day: int = 1
next_bus_id: int = 1
use_running_boards: bool = False # Toggle between static and dynamic assignment
fuel_price: float = 1.60 # Dynamic fuel price per litre (min 1.25, max 2.00)
def to_dict(self):
return {
"company_name": self.company_name,
"routes": [route.to_dict() for route in self.routes],
"fleet": [bus.to_dict() for bus in self.fleet],
"money": self.money,
"reputation": self.reputation,
"day": self.day,
"next_bus_id": self.next_bus_id,
"use_running_boards": self.use_running_boards,
"fuel_price": self.fuel_price,
}
@staticmethod
def from_dict(data):
routes = [Route.from_dict(r) for r in data["routes"]]
fleet = [Bus.from_dict(b) for b in data["fleet"]]
return ManagerState(
company_name=data["company_name"],
routes=routes,
fleet=fleet,
money=data["money"],
reputation=data["reputation"],
day=data["day"],
next_bus_id=data.get("next_bus_id", 1),
use_running_boards=data.get("use_running_boards", False),
fuel_price=data.get("fuel_price", 1.60),
)
# Available liveries for buses
AVAILABLE_LIVERIES = [
"Red & White",
"Blue & Yellow",
"Green & Cream",
"Silver & Black",
"Orange & White",
"Purple & Gold",
"All-over White",
"All-over Red",
"All-over Blue",
"All-over Green",
"Corporate Fleet",
"Heritage Classic",
"Modern Metro",
"Express Service",
"Night Service",
"Airport Special",
"City Centre",
"Suburban Route",
"Premium Service",
"Eco-Friendly Green",
]
def load_dlc_vehicles():
"""Load all vehicle DLC files from the dlcs_and_mods/ directory"""
dlc_vehicles = []
# Get the script's directory (CBMText folder)
script_dir = os.path.dirname(os.path.abspath(__file__))
dlc_folder = os.path.join(script_dir, "dlcs_and_mods")
if not os.path.exists(dlc_folder):
print(f"Note: dlcs_and_mods folder not found at {dlc_folder}")
return dlc_vehicles
# Find all JSON files in the dlcs_and_mods folder
dlc_files = glob.glob(os.path.join(dlc_folder, "*.json"))
for dlc_file in dlc_files:
try:
with open(dlc_file, 'r') as f:
data = json.load(f)
# Validate DLC format
if "dlc_name" not in data or "vehicles" not in data:
print(f"Warning: {dlc_file} missing required fields (dlc_name, vehicles). Skipping.")
continue
dlc_name = data["dlc_name"]
vehicles = data["vehicles"]
# Validate each vehicle
for vehicle in vehicles:
required_fields = ["model", "capacity", "fuel_capacity", "fuel_efficiency", "price"]
if all(field in vehicle for field in required_fields):
# Add DLC source to each vehicle
vehicle["dlc_source"] = dlc_name
dlc_vehicles.append(vehicle)
else:
print(f"Warning: Vehicle in {dlc_file} missing required fields. Skipping.")
print(f"Loaded DLC: {dlc_name} ({len(vehicles)} vehicles)")
except json.JSONDecodeError:
print(f"Warning: {dlc_file} is not valid JSON. Skipping.")
except Exception as e:
print(f"Warning: Error loading {dlc_file}: {e}. Skipping.")
return dlc_vehicles
def save_game(state: ManagerState):
# Create saves folder if it doesn't exist
script_dir = os.path.dirname(os.path.abspath(__file__))
saves_folder = os.path.join(script_dir, "saves")
if not os.path.exists(saves_folder):
os.makedirs(saves_folder)
print(f"Created saves folder at {saves_folder}")
filename = input("Enter filename to save to (e.g. my_company_save.json): ").strip()
if not filename:
print("Invalid filename. Save cancelled.")
return
# Add .json extension if not present
if not filename.endswith('.json'):
filename += '.json'
filepath = os.path.join(saves_folder, filename)
try:
with open(filepath, "w") as f:
json.dump(state.to_dict(), f, indent=2)
print(f"Game saved successfully to 'saves/{filename}'.")
except Exception as e:
print(f"Error saving game: {e}")
def load_game() -> Optional[ManagerState]:
script_dir = os.path.dirname(os.path.abspath(__file__))
saves_folder = os.path.join(script_dir, "saves")
if not os.path.exists(saves_folder):
print("No saves folder found. No saved games available.")
return None
# List available save files
save_files = [f for f in os.listdir(saves_folder) if f.endswith('.json')]
if not save_files:
print("No saved games found in saves folder.")
return None
print("\n--- Available Saved Games ---")
for i, save_file in enumerate(sorted(save_files), 1):
# Try to read company name from save
try:
filepath = os.path.join(saves_folder, save_file)
with open(filepath, "r") as f:
data = json.load(f)
company = data.get("company_name", "Unknown")
day = data.get("day", "?")
money = data.get("money", 0)
print(f"[{i}] {save_file} - {company} (Day {day}, £{money:,.2f})")
except:
print(f"[{i}] {save_file}")
print("\nEnter save number to load, or type filename directly (or 0 to cancel):")
choice = input("> ").strip()
if choice == "0":
print("Load cancelled.")
return None
# Check if it's a number (selecting from list)
try:
choice_num = int(choice)
if 1 <= choice_num <= len(save_files):
filename = sorted(save_files)[choice_num - 1]
else:
print("Invalid selection.")
return None
except ValueError:
# It's a filename
filename = choice
if not filename.endswith('.json'):
filename += '.json'
if filename not in save_files:
print(f"Save file '{filename}' not found.")
return None
filepath = os.path.join(saves_folder, filename)
try:
with open(filepath, "r") as f:
data = json.load(f)
state = ManagerState.from_dict(data)
print(f"Game loaded successfully from 'saves/{filename}'.")
return state
except FileNotFoundError:
print(f"File '{filename}' not found.")
except Exception as e:
print(f"Error loading game: {e}")
def export_visualization_data(state: ManagerState):
"""Export game data to JSON for visualization in visualization.js"""
script_dir = os.path.dirname(os.path.abspath(__file__))
# Prepare routes data
routes_data = []
for route in state.routes:
route_dict = {
"name": route.name,
"stops": [{"name": stop.name, "minutes_from_prev": stop.minutes_from_prev} for stop in route.stops],
"base_schedule_minutes": route.base_schedule_minutes,
"current_schedule_minutes": route.current_schedule_minutes,
"assigned_bus_id": route.assigned_bus_id
}
routes_data.append(route_dict)
# Prepare fleet data
fleet_data = []
for bus in state.fleet:
bus_dict = {
"id": bus.bus_id,
"bus_id": bus.bus_id,
"model": bus.model,
"capacity": bus.capacity,
"status": "active" if bus.assigned_route else "idle",
"route": bus.assigned_route,
"health": bus.health,
"fuel_level": bus.fuel_level,
"fuel_capacity": bus.fuel_capacity
}
fleet_data.append(bus_dict)
# Prepare statistics
stats = {
"routes": len(state.routes),
"stops": sum(len(r.stops) for r in state.routes),
"buses": len(state.fleet),
"active_buses": sum(1 for b in state.fleet if b.assigned_route),
"money": state.money,
"reputation": state.reputation,
"day": state.day
}
# Combine all data
viz_data = {
"company_name": state.company_name,
"routes": routes_data,
"fleet": fleet_data,
"stats": stats
}
# Export to web_data.json in the project root
output_path = os.path.join(script_dir, "web_data.json")
try:
with open(output_path, "w") as f:
json.dump(viz_data, f, indent=2)
print(f"Visualization data exported to 'web_data.json'.")
print(f"Open visualization.html in a browser to view the data.")
print(f"\nData summary:")
print(f" - Routes: {stats['routes']}")
print(f" - Total Stops: {stats['stops']}")
print(f" - Fleet: {stats['buses']} buses ({stats['active_buses']} active)")
except Exception as e:
print(f"Error exporting visualization data: {e}")
return None
# ============================================================================
# HOME SCREEN & MAIN MENU
# ============================================================================
def print_main_menu(state: ManagerState):
mode = "Running Boards" if state.use_running_boards else "Static Routes"
print(f"\n===== City Bus Manager – {state.company_name} [Mode: {mode}] =====")
print(f"Fuel Price: £{state.fuel_price:.2f}/L")
print("\n1) View Information")
print("2) Route Management")
print("3) Fleet Management")
print("4) Operations")
print("5) Game Management")
print("6) Quit")
def print_view_information_menu():
print("\n--- VIEW INFORMATION ---")
print("1) View Routes")
print("2) View Fleet")
print("3) View Company Status")
print("4) View Fuel Price Details")
print("5) Back to Main Menu")
def print_route_management_menu():
print("\n--- ROUTE MANAGEMENT ---")
print("1) Assign Bus to Route")
print("2) Change Route Schedule")
print("3) Add New Route (Costs £500 per stop)")
print("4) Delete Route")
print("5) Back to Main Menu")
def print_fleet_management_menu():
print("\n--- FLEET MANAGEMENT ---")
print("1) Buy New Bus")
print("2) Import Fleet from CSV")
print("3) Back to Main Menu")
def print_operations_menu():
print("\n--- OPERATIONS ---")
print("1) Run Day Simulation")
print("2) Running Board Management")
print("3) Back to Main Menu")
def print_game_management_menu():
print("\n--- GAME MANAGEMENT ---")
print("1) Save Game")
print("2) Load Game")
print("3) Toggle Assignment Mode")
print("4) Export Data for Visualization")
print("5) Back to Main Menu")
# ============================================================================
# ROUTE MANAGEMENT
# ============================================================================
def view_routes(state: ManagerState):
if not state.routes:
print("\nNo routes available yet.")
return
print("\n--- Routes ---")
for i, route in enumerate(state.routes, 1):
assigned_bus = next((b.model for b in state.fleet if b.bus_id == route.assigned_bus_id), "None")
total_time = sum(stop.minutes_from_prev for stop in route.stops[1:])
print(f"[{i}] {route.name} | Journey Time: {total_time} mins | Schedule: {route.current_schedule_minutes} mins | Bus: {assigned_bus}")
def view_fleet(state: ManagerState):
if not state.fleet:
print("\nNo buses in fleet yet.")
return
while True:
print("\n--- Fleet ---")
for bus in state.fleet:
route_name = next((r.name for r in state.routes if r.assigned_bus_id == bus.bus_id), "None")
fn = bus.fleet_number if bus.fleet_number else "N/A"
dlc_tag = f" [{bus.dlc_source}]" if bus.dlc_source else ""
# Check running board assignments
rb_assignments = []
if state.use_running_boards:
for board_name in list_running_boards():
board = load_running_board(board_name)
if board and board.assigned_bus_id == bus.bus_id:
rb_assignments.append(board.name)
assignment_info = f"Route: {route_name}"
if rb_assignments:
assignment_info = f"Running Boards: {', '.join(rb_assignments)}"
print(f"[{bus.bus_id}] {bus.model}{dlc_tag} (Fleet No: {fn}) | Livery: {bus.livery} | Capacity: {bus.capacity} | Fuel: {bus.fuel_level:.1f}L | Health: {bus.health} | {assignment_info}")
print("\nOptions: [E] Edit Fleet Number, [L] Change Livery, [Q] Return to Main Menu")
choice = input("> ").strip().lower()
if choice == 'e':
edit_fleet_number(state)
elif choice == 'l':
change_bus_livery(state)
elif choice == 'q':
break
else:
print("Invalid option, try again.")
# ============================================================================
# FLEET MANAGEMENT
# ============================================================================
def edit_fleet_number(state: ManagerState):
if not state.fleet:
print("\nNo buses in fleet to edit.")
return
print("\n--- Edit Fleet Number ---")
print("Current fleet:")
for bus in state.fleet:
fn = bus.fleet_number if bus.fleet_number else "N/A"
print(f"[{bus.bus_id}] {bus.model} (Fleet No: {fn})")
print("Enter bus ID to edit fleet number (or 0 to cancel):")
try:
bus_id = int(input("> "))
except ValueError:
print("Invalid input.")
return
if bus_id == 0:
print("Edit cancelled.")
return
bus = next((b for b in state.fleet if b.bus_id == bus_id), None)
if not bus:
print("Bus ID not found.")
return
print(f"Current fleet number: {bus.fleet_number if bus.fleet_number else 'N/A'}")
print("Enter new fleet number (or leave blank to cancel):")
new_number = input("> ").strip()
if new_number == "":
print("Edit cancelled.")
return
if any(b.fleet_number == new_number and b.bus_id != bus.bus_id for b in state.fleet):
print(f"Fleet number '{new_number}' already in use by another bus. Edit cancelled.")
return
bus.fleet_number = new_number
print(f"Fleet number updated to '{new_number}' for bus ID {bus.bus_id}.")
def change_bus_livery(state: ManagerState):
"""Allow player to change the livery of a bus"""
if not state.fleet:
print("\nNo buses in fleet to edit.")
return
print("\n--- Change Bus Livery ---")
print("Current fleet:")
for bus in state.fleet:
fn = bus.fleet_number if bus.fleet_number else "N/A"
print(f"[{bus.bus_id}] {bus.model} (Fleet No: {fn}) - Current Livery: {bus.livery}")
print("\nEnter bus ID to change livery (or 0 to cancel):")
try:
bus_id = int(input("> "))
except ValueError:
print("Invalid input.")
return
if bus_id == 0:
print("Livery change cancelled.")
return
bus = next((b for b in state.fleet if b.bus_id == bus_id), None)
if not bus:
print("Bus ID not found.")
return
print(f"\n--- Available Liveries for {bus.model} (Fleet No: {bus.fleet_number if bus.fleet_number else 'N/A'}) ---")
print(f"Current livery: {bus.livery}")
print("\nChoose a new livery:")
for i, livery in enumerate(AVAILABLE_LIVERIES, 1):
current_marker = " (CURRENT)" if livery == bus.livery else ""
print(f"[{i}] {livery}{current_marker}")
print("\nEnter livery number (or 0 to cancel):")
try:
livery_choice = int(input("> "))
except ValueError:
print("Invalid input.")
return
if livery_choice == 0:
print("Livery change cancelled.")
return
if not (1 <= livery_choice <= len(AVAILABLE_LIVERIES)):
print("Invalid livery number.")
return
new_livery = AVAILABLE_LIVERIES[livery_choice - 1]
if new_livery == bus.livery:
print(f"Bus already has the '{new_livery}' livery.")
return
# Cost to change livery
livery_cost = 500.0
print(f"\nChanging livery to '{new_livery}' will cost £{livery_cost:.2f}")
print(f"Current balance: £{state.money:.2f}")
confirm = input("Proceed with livery change? (y/n): ").strip().lower()
if confirm != 'y':
print("Livery change cancelled.")
return
if state.money < livery_cost:
print("You don't have enough money to change the livery!")
return
old_livery = bus.livery
bus.livery = new_livery
state.money -= livery_cost
print(f"\n✓ Livery successfully changed!")
print(f" Bus: {bus.model} (Fleet No: {bus.fleet_number if bus.fleet_number else 'N/A'})")
print(f" Old livery: {old_livery}")
print(f" New livery: {new_livery}")
print(f" Cost: £{livery_cost:.2f}")
print(f" Remaining balance: £{state.money:.2f}")
# ============================================================================
# BUS ASSIGNMENT
# ============================================================================
def assign_bus_to_route(state: ManagerState):
if state.use_running_boards:
print("\nYou are in Running Board mode. Use Running Board Management (option 12) to assign buses.")
return
if not state.fleet:
print("\nNo buses available. Buy some first.")
return
if not state.routes:
print("\nNo routes available. Add some first.")
return
print("\nSelect Bus to assign:")
for bus in state.fleet:
fn = bus.fleet_number if bus.fleet_number else "N/A"
print(f"[{bus.bus_id}] {bus.model} (Fleet No: {fn}, Capacity: {bus.capacity})")
try:
bus_id = int(input("> "))
except ValueError:
print("Invalid input.")
return
bus = next((b for b in state.fleet if b.bus_id == bus_id), None)
if not bus:
print("Bus not found.")
return
print("\nSelect Route:")
for i, route in enumerate(state.routes, 1):
print(f"[{i}] {route.name}")
try:
route_idx = int(input("> ")) - 1
except ValueError:
print("Invalid input.")
return
if not (0 <= route_idx < len(state.routes)):
print("Invalid route number.")
return
route = state.routes[route_idx]
for r in state.routes:
if r.assigned_bus_id == bus.bus_id:
r.assigned_bus_id = None
route.assigned_bus_id = bus.bus_id
bus.assigned_route = route.name
print(f"Assigned {bus.model} (Fleet No: {bus.fleet_number if bus.fleet_number else 'N/A'}) to {route.name}")
def change_route_schedule(state: ManagerState):
if not state.routes:
print("\nNo routes available to edit.")
return
print("\nSelect Route to edit schedule:")
for i, route in enumerate(state.routes, 1):
print(f"[{i}] {route.name} | Current Schedule: {route.current_schedule_minutes} mins")
try:
route_idx = int(input("> ")) - 1
except ValueError:
print("Invalid input.")
return
if not (0 <= route_idx < len(state.routes)):
print("Invalid route number.")
return
route = state.routes[route_idx]
print(f"Enter new schedule time in minutes for {route.name} (base is {route.base_schedule_minutes}):")
try:
new_time = int(input("> "))
if new_time < route.base_schedule_minutes // 2:
print("Schedule too short! Aborting.")
return
except ValueError:
print("Invalid input.")
return
route.current_schedule_minutes = new_time
print(f"Schedule updated: {route.name} now runs in {new_time} minutes.")
# ============================================================================
# DAY SIMULATION
# ============================================================================
def run_day_simulation_static(state: ManagerState):
"""Original static route simulation"""
if not state.routes:
print("\nNo routes available to run.")
return
if not state.fleet:
print("\nNo buses available to run routes.")
return
print(f"\n--- Running Day Simulation (Static Mode): Day {state.day} ---")
total_earnings = 0.0
total_fuel_cost = 0.0
reputation_change = 0.0
for route in state.routes:
bus = next((b for b in state.fleet if b.bus_id == route.assigned_bus_id), None)
if not bus:
print(f"Route '{route.name}' has no bus assigned! No service today.")
reputation_change -= 5
continue
print(f"\nRoute: {route.name}")
print(f"Bus: {bus.model} (Fleet No: {bus.fleet_number if bus.fleet_number else 'N/A'}) [Livery: {bus.livery}] (Capacity: {bus.capacity})")
print(f"Schedule time: {route.current_schedule_minutes} mins")
total_time = sum(stop.minutes_from_prev for stop in route.stops[1:])
ticket_price = 2.50
# Base demand on route length (more stops/time = more passengers)
avg_demand = int(total_time * 1.5)
passengers = min(bus.capacity, random.randint(max(0, avg_demand - 5), avg_demand + 5))
earnings = passengers * ticket_price
fuel_used = bus.consume_fuel(total_time)
fuel_cost = fuel_used * state.fuel_price
if random.random() < 0.2:
event = random.choice(["flat tyre", "engine trouble", "heavy traffic"])
print(f"** Event: {event}! Delays the route and costs £200 to fix. **")
reputation_change -= 3
state.money -= 200
else:
reputation_change += 1
if route.current_schedule_minutes < route.base_schedule_minutes:
if random.random() < 0.3:
print("Tight schedule caused delays and made passengers unhappy!")
reputation_change -= 2
else:
reputation_change += 1
else:
reputation_change += 1
total_earnings += earnings
total_fuel_cost += fuel_cost
print(f"Passengers carried: {passengers}")
print(f"Fare income: £{earnings:.2f}")
print(f"Fuel used: {fuel_used:.2f}L costing £{fuel_cost:.2f}")
net_profit = total_earnings - total_fuel_cost
state.money += net_profit
state.reputation = max(0.0, min(100.0, state.reputation + reputation_change))
# Update fuel price for next day
update_fuel_price(state)
state.day += 1
print(f"\nDay {state.day-1} summary:")
print(f"Total fare income: £{total_earnings:.2f}")
print(f"Total fuel cost: £{total_fuel_cost:.2f}")
print(f"Net profit: £{net_profit:.2f}")
print(f"Reputation change: {reputation_change:+.1f}")
print(f"New reputation: {state.reputation:.1f}/100")
print(f"Fuel price for Day {state.day}: £{state.fuel_price:.2f}/L")
print(f"Money available: £{state.money:.2f}")
def run_day_simulation_running_boards(state: ManagerState):
"""New dynamic simulation using running boards"""
boards = []
for board_name in list_running_boards():
board = load_running_board(board_name)
if board and board.assigned_bus_id:
boards.append(board)
if not boards:
print("\nNo running boards with assigned buses available.")
print("Use Running Board Management (option 12) to create and assign running boards.")
return
print(f"\n--- Running Day Simulation (Running Board Mode): Day {state.day} ---")
print(f"Operating {len(boards)} running board(s)...\n")
total_earnings = 0.0
total_fuel_cost = 0.0
reputation_change = 0.0
for board in boards:
bus = next((b for b in state.fleet if b.bus_id == board.assigned_bus_id), None)
if not bus:
print(f"Running board '{board.name}' has invalid bus assignment! Skipping.")
continue
print(f"\n--- Running Board: {board.name} ---")
print(f"Bus: {bus.model} (Fleet No: {bus.fleet_number if bus.fleet_number else 'N/A'}) [Livery: {bus.livery}]")
print(f"Total trips: {len(board.trips)}")
board_earnings = 0.0
board_fuel = 0.0
trips_completed = 0
for trip in board.trips:
route = next((r for r in state.routes if r.name == trip.route_name), None)
if not route:
print(f" {trip.departure_time} - {trip.route_name}: Route not found! Skipping.")
reputation_change -= 2
continue
total_time = sum(stop.minutes_from_prev for stop in route.stops[1:])
# Check if bus has enough fuel
fuel_needed = total_time / 60 * 30 * bus.fuel_efficiency # Estimate based on time
if bus.fuel_level < fuel_needed:
print(f" {trip.departure_time} - {trip.route_name}: ⚠ Insufficient fuel! Trip cancelled.")
reputation_change -= 5
continue
ticket_price = 2.50
avg_demand = int(total_time * 1.5)
passengers = min(bus.capacity, random.randint(max(0, avg_demand - 5), avg_demand + 5))
earnings = passengers * ticket_price
fuel_used = bus.consume_fuel(total_time)
fuel_cost = fuel_used * state.fuel_price
# Random events
if random.random() < 0.10:
event = random.choice(["minor delay", "passenger incident", "route deviation"])
reputation_change -= 1
else:
reputation_change += 0.5
board_earnings += earnings
board_fuel += fuel_cost
trips_completed += 1
print(f" {trip.departure_time} - {trip.route_name} to {trip.destination}: {passengers} pax, £{earnings:.2f}")
total_earnings += board_earnings
total_fuel_cost += board_fuel
print(f" Board summary: {trips_completed}/{len(board.trips)} trips, £{board_earnings:.2f} income, £{board_fuel:.2f} fuel")
net_profit = total_earnings - total_fuel_cost
state.money += net_profit
state.reputation = max(0.0, min(100.0, state.reputation + reputation_change))
# Update fuel price for next day
update_fuel_price(state)
state.day += 1
print(f"\n--- Day {state.day-1} Summary ---")
print(f"Total fare income: £{total_earnings:.2f}")
print(f"Total fuel cost: £{total_fuel_cost:.2f}")
print(f"Net profit: £{net_profit:.2f}")
print(f"Reputation change: {reputation_change:+.1f}")
print(f"New reputation: {state.reputation:.1f}/100")
print(f"Fuel price for Day {state.day}: £{state.fuel_price:.2f}/L")
print(f"Money available: £{state.money:.2f}")
def run_day_simulation(state: ManagerState):
"""Route to appropriate simulation based on mode"""
if state.use_running_boards:
run_day_simulation_running_boards(state)
else:
run_day_simulation_static(state)
# ============================================================================
# FLEET OPERATIONS
# ============================================================================
def import_fleet_from_csv(state: ManagerState):
"""Import buses from a CSV file"""
script_dir = os.path.dirname(os.path.abspath(__file__))
print("\n--- Import Fleet from CSV ---")
print("Place your CSV file in the CBMText folder.")
print("CSV format should have headers: model,capacity,fuel_capacity,fuel_efficiency,purchase_price,fleet_number,livery")
print("\nExample:")
print("model,capacity,fuel_capacity,fuel_efficiency,purchase_price,fleet_number,livery")
print("ADL Enviro200,40,160.0,0.26,90000,FL-001,Red & White")
filename = input("\nEnter CSV filename (or 0 to cancel): ").strip()
if filename == "0":
print("Import cancelled.")
return
if not filename.endswith('.csv'):
filename += '.csv'
filepath = os.path.join(script_dir, filename)
if not os.path.exists(filepath):
print(f"File '{filename}' not found in {script_dir}")
return
try:
imported_count = 0
skipped_count = 0
total_cost = 0.0
with open(filepath, 'r') as f:
reader = csv.DictReader(f)
if not reader.fieldnames:
print("CSV file is empty.")
return
required_fields = {'model', 'capacity', 'fuel_capacity', 'fuel_efficiency'}
# Check required fields exist
if not required_fields.issubset(set(reader.fieldnames)):
print(f"CSV must contain columns: {', '.join(required_fields)}")
return
for row_num, row in enumerate(reader, start=2): # start=2 because row 1 is header
try:
model = row.get('model', '').strip()
capacity = int(row.get('capacity', 0))
fuel_capacity = float(row.get('fuel_capacity', 0))
fuel_efficiency = float(row.get('fuel_efficiency', 0))
purchase_price = float(row.get('purchase_price', 0))
fleet_number = row.get('fleet_number', '').strip()
livery = row.get('livery', 'Standard').strip()
# Validate required data
if not model or capacity <= 0 or fuel_capacity <= 0 or fuel_efficiency <= 0:
print(f"Row {row_num}: Skipping - missing or invalid required fields")
skipped_count += 1
continue
# Check if fleet number already exists
if fleet_number and any(bus.fleet_number == fleet_number for bus in state.fleet):
print(f"Row {row_num}: Skipping '{model}' - fleet number {fleet_number} already in use")
skipped_count += 1
continue
# Auto-assign fleet number if not provided
if not fleet_number:
existing_numbers = {bus.fleet_number for bus in state.fleet if bus.fleet_number}
n = 1
while str(n) in existing_numbers:
n += 1
fleet_number = str(n)
# Validate livery
if livery not in AVAILABLE_LIVERIES:
livery = "Standard"
# Create bus
bus_id = state.next_bus_id
state.next_bus_id += 1
new_bus = Bus(
bus_id=bus_id,
model=model,
capacity=capacity,
fuel_capacity=fuel_capacity,
fuel_level=fuel_capacity, # Start with full tank
fuel_efficiency=fuel_efficiency,
purchase_price=purchase_price,
fleet_number=fleet_number,
livery=livery
)
state.fleet.append(new_bus)