-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
435 lines (371 loc) · 16 KB
/
main.py
File metadata and controls
435 lines (371 loc) · 16 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
#!/usr/bin/env python3
"""
Traffic Simulation - OS Scheduling Concepts Demo
Main entry point for the traffic simulation that demonstrates
operating system scheduling algorithms through vehicle traffic management.
"""
import pygame
import sys
import os
from controllers.scheduler import Scheduler
from controllers.traffic_light import TrafficLightController
from controllers.synchronization import SynchronizationManager
from controllers.problem_scenarios import ProblemScenarioManager
from entities.vehicle import Vehicle, VehicleType
from entities.lane import Lane, Direction
from entities.vehicle_sprites import VehicleSpriteManager
from entities.vehicle_storage import VehicleStorage
from ui.dashboard import Dashboard
from ui.menu import Menu
from ui.background import ModernBackground
from ui.theme import theme, graphics
from ui.audio import audio_manager
class TrafficSimulation:
"""Main simulation class that orchestrates all components."""
def __init__(self):
pygame.init()
# Display settings
self.WIDTH = 1200
self.HEIGHT = 800
self.screen = pygame.display.set_mode((self.WIDTH, self.HEIGHT))
pygame.display.set_caption("Traffic Simulation - OS Scheduling Demo")
# Window state
self.is_fullscreen = False
self.is_minimized = False
# Clock for FPS control
self.clock = pygame.time.Clock()
self.FPS = 60
# Simulation state
self.running = True
self.paused = False
# Initialize components
self.sync_manager = SynchronizationManager()
self.scheduler = Scheduler(self.sync_manager)
self.traffic_light = TrafficLightController(self.scheduler)
self.dashboard = Dashboard(self.WIDTH, self.HEIGHT)
self.menu = Menu(self.WIDTH, self.HEIGHT)
self.problem_manager = ProblemScenarioManager()
self.vehicle_sprites = VehicleSpriteManager("colored")
# Create lanes
self.lanes = self._create_lanes()
# Vehicle management
self.vehicles = pygame.sprite.Group()
self.vehicle_counter = 0
self.vehicles_passed = 0
self.vehicle_storage = VehicleStorage(self.WIDTH, self.HEIGHT)
# Spawning
self.spawn_timer = 0
self.spawn_interval = 2000 # milliseconds
# Audio
self.last_vehicles_passed = 0
self.last_light_state = None
# Modern background system
self.background = ModernBackground(self.WIDTH, self.HEIGHT, theme)
def _create_lanes(self):
"""Create the four lanes for the intersection."""
lanes = {}
# Calculate intersection center - properly centered considering dashboard width
dashboard_width = 300
available_width = self.WIDTH - dashboard_width
center_x = available_width // 2
center_y = self.HEIGHT // 2
# Lane dimensions
lane_width = 60
lane_length = 200
# North lane (top)
lanes[Direction.NORTH] = Lane(
Direction.NORTH,
center_x - lane_width//2,
center_y - lane_length - 50,
lane_width,
lane_length
)
# South lane (bottom)
lanes[Direction.SOUTH] = Lane(
Direction.SOUTH,
center_x - lane_width//2,
center_y + 50,
lane_width,
lane_length
)
# East lane (right)
lanes[Direction.EAST] = Lane(
Direction.EAST,
center_x + 50,
center_y - lane_width//2,
lane_length,
lane_width
)
# West lane (left)
lanes[Direction.WEST] = Lane(
Direction.WEST,
center_x - lane_length - 50,
center_y - lane_width//2,
lane_length,
lane_width
)
return lanes
def _create_background(self):
"""Create the road background - now handled by ModernBackground."""
# This method is now replaced by ModernBackground
# Keep for compatibility but return a simple surface
background = pygame.Surface((self.WIDTH, self.HEIGHT))
background.fill(theme.get_color('bg_primary'))
return background
def spawn_vehicle(self):
"""Spawn a new vehicle at a random lane."""
import random
direction = random.choice(list(Direction))
lane = self.lanes[direction]
# Random vehicle type
vehicle_types = [VehicleType.CAR, VehicleType.BUS, VehicleType.BIKE, VehicleType.AMBULANCE]
weights = [0.4, 0.2, 0.3, 0.1] # Ambulance less frequent
vehicle_type = random.choices(vehicle_types, weights=weights)[0]
# Get spawn position
spawn_position = lane.get_spawn_position()
# Create vehicle
vehicle = Vehicle(
f"P{self.vehicle_counter}",
vehicle_type,
direction,
spawn_position,
self.vehicle_sprites
)
# Try to place vehicle using storage system
if self.vehicle_storage.place_vehicle(vehicle, spawn_position):
self.vehicles.add(vehicle)
self.vehicle_counter += 1
# Add to lane queue
lane.add_vehicle(vehicle)
else:
# If can't place, try to find alternative position
alternative_position = self.vehicle_storage._find_nearby_position(direction, spawn_position)
if self.vehicle_storage.place_vehicle(vehicle, alternative_position):
self.vehicles.add(vehicle)
self.vehicle_counter += 1
lane.add_vehicle(vehicle)
def update(self, dt):
"""Update simulation state."""
if self.paused:
return
# Update problem scenarios
self.problem_manager.update(self)
# Update traffic light
self.traffic_light.update(dt)
# Update scheduler
self.scheduler.update(dt, self.lanes)
# Update vehicles
for vehicle in self.vehicles:
old_position = (vehicle.x, vehicle.y)
vehicle.update(dt, self.traffic_light, self.lanes)
new_position = (vehicle.x, vehicle.y)
# Update position in storage if it changed
if old_position != new_position:
self.vehicle_storage.update_vehicle_position(vehicle, new_position)
# Remove vehicles that have passed through
if vehicle.has_passed():
self.vehicle_storage.remove_vehicle(vehicle)
self.vehicles.remove(vehicle)
self.vehicles_passed += 1
# Spawn new vehicles
self.spawn_timer += dt
if self.spawn_timer >= self.spawn_interval:
self.spawn_vehicle()
self.spawn_timer = 0
# Update background animations
self.background.update(dt)
# Update audio effects
self._update_audio_effects()
# Update dashboard
current_problem = self.problem_manager.get_current_scenario()
self.dashboard.update(
self.scheduler.get_current_algorithm(),
{direction: lane.get_queue_length() for direction, lane in self.lanes.items()},
self.vehicles_passed,
self.scheduler.get_congestion_level(),
current_problem
)
def handle_events(self):
"""Handle pygame events."""
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.running = False
elif event.type == pygame.KEYDOWN:
# Enhanced keyboard shortcuts
if event.key == pygame.K_ESCAPE:
if self.menu.is_menu_visible():
self.running = False
else:
self.menu.show_menu_again()
elif event.key == pygame.K_SPACE:
self.paused = not self.paused
elif event.key == pygame.K_1:
self.scheduler.set_algorithm("FCFS")
elif event.key == pygame.K_2:
self.scheduler.set_algorithm("Round Robin")
elif event.key == pygame.K_3:
self.scheduler.set_algorithm("Priority")
elif event.key == pygame.K_4:
self.scheduler.set_algorithm("Dynamic")
elif event.key == pygame.K_m:
self.menu.show_menu_again()
elif event.key == pygame.K_F11 or event.key == pygame.K_f:
self.toggle_fullscreen()
elif event.key == pygame.K_F12:
self.toggle_minimize()
elif event.key == pygame.K_r:
# Reset simulation
self.vehicles.empty()
self.vehicles_passed = 0
for lane in self.lanes.values():
lane.vehicles.clear()
elif event.key == pygame.K_PLUS or event.key == pygame.K_EQUALS:
# Increase simulation speed
self.spawn_interval = max(500, self.spawn_interval - 200)
elif event.key == pygame.K_UNDERSCORE:
# Decrease simulation speed
self.spawn_interval = min(5000, self.spawn_interval + 200)
elif event.key == pygame.K_h:
# Show help
self._show_help()
elif event.key == pygame.K_s:
# Toggle sound
audio_manager.toggle_sound()
elif event.key == pygame.K_a:
# Toggle ambient audio
if audio_manager.music_playing:
audio_manager.stop_ambient_traffic()
else:
audio_manager.start_ambient_traffic()
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1: # Left click
if not self.menu.is_menu_visible():
# Handle dashboard clicks
result = self.dashboard.handle_click(event.pos)
if result == "back_to_menu":
self.menu.show_menu_again()
elif result == "minimize":
self.toggle_minimize()
elif result == "fullscreen":
self.toggle_fullscreen()
# Handle menu events
if self.menu.is_menu_visible():
result = self.menu.handle_event(event)
if result == "start_simulation":
self.menu.hide_menu()
elif result == "exit":
self.running = False
elif result == "algorithm_selected":
algorithm = self.menu.get_selected_algorithm()
self.scheduler.set_algorithm(algorithm)
elif result == "problem_selected":
problem = self.menu.get_selected_problem()
self.problem_manager.activate_scenario(problem)
elif result == "vehicle_style_selected":
style = self.menu.get_selected_vehicle_style()
self.vehicle_sprites.set_style(style)
def render(self):
"""Render the simulation."""
if self.menu.is_menu_visible():
# Draw menu
self.menu.draw(self.screen)
else:
# Draw modern simulation
self.background.draw(self.screen)
# Draw lanes
for lane in self.lanes.values():
lane.draw(self.screen)
# Draw traffic lights
self.traffic_light.draw(self.screen)
# Draw vehicles
self.vehicles.draw(self.screen)
# Draw dashboard
self.dashboard.draw(self.screen)
# Draw problem scenario info
self._draw_problem_info()
# Update display
pygame.display.flip()
def _draw_problem_info(self):
"""Draw current problem scenario information."""
scenario_info = self.problem_manager.get_scenario_info()
if scenario_info and scenario_info["active"]:
font = pygame.font.Font(None, 24)
text = f"Problem: {scenario_info['name']}"
text_surface = font.render(text, True, (255, 100, 100))
self.screen.blit(text_surface, (10, 10))
def toggle_fullscreen(self):
"""Toggle fullscreen mode."""
self.is_fullscreen = not self.is_fullscreen
if self.is_fullscreen:
self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
self.WIDTH, self.HEIGHT = self.screen.get_size()
else:
self.screen = pygame.display.set_mode((self.WIDTH, self.HEIGHT))
# Recreate components with new dimensions
self.dashboard = Dashboard(self.WIDTH, self.HEIGHT)
self.menu = Menu(self.WIDTH, self.HEIGHT)
self.lanes = self._create_lanes()
self.background = ModernBackground(self.WIDTH, self.HEIGHT, theme)
def toggle_minimize(self):
"""Toggle minimize state."""
self.is_minimized = not self.is_minimized
if self.is_minimized:
pygame.display.iconify()
else:
pygame.display.set_mode((self.WIDTH, self.HEIGHT))
def run(self):
"""Main simulation loop."""
print("Traffic Simulation Started!")
print("Controls:")
print(" SPACE - Pause/Resume")
print(" 1 - FCFS Algorithm")
print(" 2 - Round Robin Algorithm")
print(" 3 - Priority Algorithm")
print(" 4 - Dynamic Algorithm")
print(" ESC - Quit")
while self.running:
dt = self.clock.tick(self.FPS)
self.handle_events()
self.update(dt)
self.render()
pygame.quit()
sys.exit()
def _show_help(self):
"""Show help information."""
print("\n" + "="*50)
print("TRAFFIC SIMULATION - KEYBOARD SHORTCUTS")
print("="*50)
print("SPACE - Pause/Resume simulation")
print("1-4 - Switch algorithms (FCFS, Round Robin, Priority, Dynamic)")
print("F / F11 - Toggle fullscreen")
print("F12 - Minimize window")
print("M - Show main menu")
print("R - Reset simulation")
print("+ / = - Increase simulation speed")
print("- - Decrease simulation speed")
print("H - Show this help")
print("S - Toggle sound effects")
print("A - Toggle ambient audio")
print("ESC - Quit application")
print("="*50)
def _update_audio_effects(self):
"""Update audio effects based on simulation state."""
# Play sound for vehicles passing through
if self.vehicles_passed > self.last_vehicles_passed:
audio_manager.play_vehicle_pass()
self.last_vehicles_passed = self.vehicles_passed
# Play sound for traffic light changes
current_light_state = self.traffic_light.get_all_states()
if current_light_state != self.last_light_state:
audio_manager.play_light_change()
self.last_light_state = current_light_state.copy()
# Play congestion alert
congestion_level = self.scheduler.get_congestion_level()
if congestion_level == "High":
# Play alert occasionally
import random
if random.random() < 0.01: # 1% chance per frame
audio_manager.play_congestion_alert()
if __name__ == "__main__":
simulation = TrafficSimulation()
simulation.run()