python间隔5毫秒for_在Python中在pygame中每隔x(毫秒)做一些事情

在Python Pygame项目中,玩家希望每0.25秒移动一次蛇,而不影响其他功能。通过使用pygame.time.set_timer()函数创建一个定时事件,可以在指定间隔执行特定任务,例如移动蛇。给出的示例代码演示了如何设置一个事件队列,每250毫秒触发一次蛇的移动。
摘要由CSDN通过智能技术生成

我正在学习

Python和Pygame,而我正在做的第一件事是一个简单的Snake游戏.我试图让蛇每0.25秒移动一次.这是我的代码循环的一部分:

while True:

check_for_quit()

clear_screen()

draw_snake()

draw_food()

check_for_direction_change()

move_snake() #How do I make it so that this loop runs at normal speed, but move_snake() only executes once every 0.25 seconds?

pygame.display.update()

我希望所有其他函数正常运行,但move_snake()只发生一次0.25秒.我查了一下并找到了一些答案,但对于那些制作他们的第一个Python脚本的人来说,它们看起来都太复杂了.

是否有可能真正得到我的代码应该是什么样子的例子,而不仅仅是告诉我需要使用哪个函数?谢谢!

有几种方法,如跟踪系统时间或使用时钟和计数滴答.

但最简单的方法是使用事件队列并使用pygame.time.set_timer()每隔x ms创建一个事件:

pygame.time.set_timer()

repeatedly create an event on the event queue

set_timer(eventid, milliseconds) -> None

Set an event type to appear on the event queue every given number of milliseconds. The first event will not appear until the amount of time has passed.

Every event type can have a separate timer attached to it. It is best to use the value between pygame.USEREVENT and pygame.NUMEVENTS.

To disable the timer for an event, set the milliseconds argument to 0.

这是一个小的,运行的例子,蛇每250毫秒移动一次:

import pygame

pygame.init()

screen = pygame.display.set_mode((300, 300))

player, dir, size = pygame.Rect(100,100,20,20), (0, 0), 20

MOVEEVENT, t, trail = pygame.USEREVENT+1, 250, []

pygame.time.set_timer(MOVEEVENT, t)

while True:

keys = pygame.key.get_pressed()

if keys[pygame.K_w]: dir = 0, -1

if keys[pygame.K_a]: dir = -1, 0

if keys[pygame.K_s]: dir = 0, 1

if keys[pygame.K_d]: dir = 1, 0

if pygame.event.get(pygame.QUIT): break

for e in pygame.event.get():

if e.type == MOVEEVENT: # is called every 't' milliseconds

trail.append(player.inflate((-10, -10)))

trail = trail[-5:]

player.move_ip(*[v*size for v in dir])

screen.fill((0,120,0))

for t in trail:

pygame.draw.rect(screen, (255,0,0), t)

pygame.draw.rect(screen, (255,0,0), player)

pygame.display.flip()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值