【Python全栈】Python实现交通信号灯

一、实现过程

1. 导入必要的库和初始化Pygame

  • 导入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//2, SCREEN_HEIGHT//2 - 100), 50)  # 画交通信号灯
    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()
  • 16
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值