python绘制根据时间变化的红绿灯图像代码
时间: 2023-08-01 15:05:57 浏览: 132
带时间显示的红绿灯
以下是一个简单的Python代码,可以绘制一个根据时间变化的红绿灯图像:
```
import pygame
from pygame.locals import *
# 初始化Pygame
pygame.init()
# 设置窗口尺寸
window_size = (200, 400)
screen = pygame.display.set_mode(window_size)
# 定义红绿灯颜色
red = (255, 0, 0)
yellow = (255, 255, 0)
green = (0, 255, 0)
# 定义灯的半径和间隔
radius = 50
gap = 20
# 定义当前灯的状态,0为绿灯,1为黄灯,2为红灯
light_state = 0
# 定义计时器
timer = 0
# 游戏循环
while True:
# 处理事件
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
# 计时器增加
timer += 1
# 根据时间变化改变灯的状态
if timer < 60:
light_state = 0
elif timer < 80:
light_state = 1
else:
light_state = 2
timer = 0
# 填充背景色
screen.fill((255, 255, 255))
# 绘制红灯
if light_state == 2:
pygame.draw.circle(screen, red, (window_size[0] // 2, radius + gap), radius)
else:
pygame.draw.circle(screen, (128, 0, 0), (window_size[0] // 2, radius + gap), radius)
# 绘制黄灯
if light_state == 1:
pygame.draw.circle(screen, yellow, (window_size[0] // 2, radius * 2 + gap * 2), radius)
else:
pygame.draw.circle(screen, (128, 128, 0), (window_size[0] // 2, radius * 2 + gap * 2), radius)
# 绘制绿灯
if light_state == 0:
pygame.draw.circle(screen, green, (window_size[0] // 2, radius * 3 + gap * 3), radius)
else:
pygame.draw.circle(screen, (0, 128, 0), (window_size[0] // 2, radius * 3 + gap * 3), radius)
# 更新屏幕
pygame.display.update()
```
这个代码使用了Pygame库来进行窗口绘制,根据计时器的变化来改变灯的状态,并且绘制不同颜色的圆形来表示红、黄、绿灯的状态。你可以根据需要进行调整,比如改变计时器的时间间隔,改变灯的尺寸和颜色等。
阅读全文