一、设置帧率
clock = pygame.time.Clock()
clock.tick(60)
二、自定义事件
定时新增自定义事件
pygame.time.set_timer(MOVE, 100)
自定义事件监听
event.type == MOVE:
关闭定时器
pygame.time.set_timer(MOVE, 0)
三、完整代码演示
import pygame
import random
import time
pygame.init()
pygame.display.set_caption('物体的移动')
WIDTH = 750
HEIGHT = 450
x = 0
y = 0
w = 100
h = 80
clock = pygame.time.Clock()
#自定义事件埋点
MOVE = 101
pygame.time.set_timer(MOVE, 1000)
screen = pygame.display.set_mode((WIDTH, HEIGHT))
while True:
clock.tick(60)
screen.fill((255, 255, 255))
pygame.draw.rect(screen, (150, 0, 0), (x, y, w, h))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
#自定义事件判断
if event.type == MOVE:
x = random.randint(0, WIDTH - w)
y = random.randint(0, HEIGHT - h)