一、实现过程
1. 导入必要的库和初始化Pygame
2. 定义颜色和屏幕尺寸
3. 创建交通信号灯、行人和车辆类
- TrafficLight类:包含一个change_color方法,用于模拟交通信号灯的颜色变化。
- Pedestrian类:包含一个move方法,用于模拟行人的移动。
- Car类:包含一个move方法,用于模拟车辆的移动。
4. 定义绘制函数draw
5. 实例化交通信号灯、行人和车辆对象
- 创建TrafficLight、Pedestrian和Car对象。
6. 创建并启动线程
- 使用threading库创建并启动交通信号灯、行人和车辆的线程。
7. 游戏循环
- 在游戏循环中,检测退出事件并调用draw函数更新屏幕。
二、代码
import pygame
import time
import threading
# 初始化Pygame
pygame.init()
# 设置屏幕尺寸
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Traffic Simulator")
# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
YELLOW = (255, 255, 0)
# 交通信号灯类
class TrafficLight:
def __init__(self):
self.color = GREEN
def change_color(self):
while True:
self.color = RED
time.sleep(5) # 红灯持续5秒
self.color = GREEN
time.sleep(5) # 绿灯持续5秒
# 行人类
class Pedestrian:
def __init__(self):
self.position = (100, 300) # 初始位置
def move(self):
while True:
# 行人移动逻辑
time.sleep(2)
# 车辆类
class Car:
def __init__(self):
self.position = (700, 300) # 初始位置
def move(self):
while True:
# 车辆移动逻辑
time.sleep(1)
# 绘制函数
def draw():
screen.fill(WHITE)
pygame.draw.circle(screen, traffic_light.color, (SCREEN_WIDTH
pygame.draw.rect(screen, BLACK, (pedestrian.position[0], pedestrian.position[1], 20, 20)) # 画行人
pygame.draw.rect(screen, BLACK, (car.position[0], car.position[1], 40, 20)) # 画车辆
pygame.display.flip()
# 实例化交通信号灯、行人和车辆对象
traffic_light = TrafficLight()
pedestrian = Pedestrian()
car = Car()
# 创建并启动线程
traffic_thread = threading.Thread(target=traffic_light.change_color)
pedestrian_thread = threading.Thread(target=pedestrian.move)
car_thread = threading.Thread(target=car.move)
traffic_thread.start()
pedestrian_thread.start()
car_thread.start()
# 游戏循环
clock = pygame.time.Clock()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
draw()
clock.tick(60)
pygame.quit()