add proper gameplay with cars moving and lights changing colours (intersection functionality added later)

This commit is contained in:
casualhonk 2026-02-20 17:04:26 +11:00
parent 503833918c
commit 160ba18e83
3 changed files with 121 additions and 1 deletions

113
main.py
View file

@ -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()