diff --git a/.idea/PythonProject.iml b/.idea/PythonProject.iml index 57b39d8..77489aa 100644 --- a/.idea/PythonProject.iml +++ b/.idea/PythonProject.iml @@ -4,7 +4,7 @@ - + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..6a440ae --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,7 @@ + + + + + + \ No newline at end of file diff --git a/main.py b/main.py index c6849d9..dc354ba 100644 --- a/main.py +++ b/main.py @@ -44,4 +44,117 @@ class TrafficLight: colour = GREEN if self.current == "green" else YELLOW if self.current == "yellow" else RED pygame.draw.circle(surf, colour, (self.x, self.y), 12) +#Vehicle Class +class Vehicle: + def __init__(self, x, y, speed=2): + self.x = x + self.y = y + self.speed = speed + self.wait = 0 + def update(self, lights): + #check if light ahead + + for light in lights: + if abs(self.x - light.x) < 10 and self.y < light.y < self.y + 40: + if light.current != "green": + self.wait += 1 + return + + self.y += self.speed + + def draw(self, surf): + pygame.draw.rect(surf, CAR, (self.x - 10, self.y - 20, 20, 40)) + + + + +#sim state +vehicles = [] +lights = [] +intersections = [] + +spawn_timer = 0 +SPAWN_RATE = 60 #every second spawn one + + +placing_mode = "intersection" + +#loop + +running = True +while running: + clock.tick(FPS) + screen.fill((40, 140, 40)) + + #event handling + for event in pygame.event.get(): + if event.type == pygame.QUIT: + running = False + pygame.quit() + sys.exit() + + if event.type == pygame.MOUSEBUTTONDOWN: + mx, my = pygame.mouse.get_pos() + + if mx < 800: #sim area + + if placing_mode == "intersection": + intersections.append((mx, my)) + elif placing_mode == "light": + lights.append(TrafficLight(mx, my)) + + #switch placing mode + if event.type == pygame.KEYDOWN: + if event.key == pygame.K_1: + placing_mode = "intersection" + if event.key == pygame.K_2: + placing_mode = "light" + + + #roads + pygame.draw.rect(screen, ROAD, (380, 0, 240, HEIGHT)) + + #veichles + spawn_timer += 1 + if spawn_timer > SPAWN_RATE: + spawn_timer = 0 + vehicles.append(Vehicle(500, -20)) + + #update lights + for light in lights: + light.update() + light.draw(screen) + + #update vehicles + for v in vehicles: + v.update(lights) + v.draw(screen) + + #draw intersections + for x, y in intersections: + pygame.draw.rect(screen, WHITE, (x - 20, y - 20, 40, 40), 2) + + #ui + pygame.draw.rect(screen, UI_BG, (800, 0, 200, HEIGHT)) + font = pygame.font.SysFont(None, 28) + + ui_text = [ + "Placement Mode:", + f"{placing_mode.upper()}", + "", + "Press 1: Intersection", + "Press 2: Traffic Light", + "", + f"Cars: {len(vehicles)}", + f"Lights: {len(lights)}", + f"Intersections: {len(intersections)}", + ] + + y_offset = 20 + for line in ui_text: + txt = font.render(line, True, WHITE) + screen.blit(txt, (820, y_offset)) + y_offset += 30 + + pygame.display.flip() \ No newline at end of file