如何解决在 Pygame 中制作一个每 2 秒改变一次颜色的红绿灯
我的目标是创造:
我的代码:
import pygame
pygame.init()
# def color
white = (255,255,255)
green = (0,0)
red = (0,0)
# screen
screen_w = 640
screen_h = 480
screenSize = (screen_w,screen_h)
screen = pygame.display.set_mode((300,400))
pygame.display.set_caption("white light and red light")
# create button
clock = pygame.time.Clock()
image = pygame.image.load('pngtree-vector-play-icon-png-image_924817.jpg')
screen.blit(image,(80,440)) #how to add text next to the imgage?
# draw circles
pygame.draw.circle(screen,red,(320,240),240)
pygame.draw.circle(screen,white,120)
pygame.draw.circle(screen,green,120)
# 2 second color change rule
running = True
while running:
clock.tick(2)
pygame.display.flip()
pygame.quit()
我对编程很陌生,所以请不要犯愚蠢的错误。
解决方法
创建一个颜色列表和一个存储当前颜色索引的变量:
colors = [white,green,red]
current_index = 0
在 pygame 中存在一个计时器事件。使用 pygame.time.set_timer()
在事件队列中重复创建 USEREVENT
。时间必须以毫秒为单位设置。例如:
timer_interval = 2000 # 2.0 seconds
timer_event = pygame.USEREVENT + 1
pygame.time.set_timer(timer_event,timer_interval)
注意,在 pygame 中可以定义客户事件。每个事件都需要一个唯一的 ID。用户事件的 ID 必须介于 pygame.USEREVENT
(24) 和 pygame.NUMEVENTS
(32) 之间。在这种情况下,pygame.USEREVENT+1
是计时器事件的事件 ID。
在事件发生时更改颜色索引:
for event in pygame.event.get():
if event.type == timer_event:
current_index += 1
if current_index >= len(colors):
current_index = 0
在应用程序循环中用当前颜色画一个圆圈:
while running:
# [...]
pygame.draw.circle(screen,colors[current_index],(150,200),120)
完整示例:
import pygame
pygame.init()
white = (255,255,255)
green = (0,0)
red = (255,0)
screen = pygame.display.set_mode((300,400))
pygame.display.set_caption("white light and red light")
clock = pygame.time.Clock()
colors = [white,red]
current_index = 0
timer_interval = 2000 # 2.0 seconds
timer_event = pygame.USEREVENT + 1
pygame.time.set_timer(timer_event,timer_interval)
running = True
while running:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == timer_event:#
current_index += 1
if current_index >= len(colors):
current_index = 0
screen.fill(0)
pygame.draw.circle(screen,120)
pygame.display.flip()
pygame.quit()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。