PYGAME - 创建时钟并每隔一段时间执行操作



我正在制作一个游戏,其中屏幕顶部的移动立方体会以一定的间隔向屏幕发射一个立方体。我该怎么做。例如,我希望每 1 秒移动立方体就会向玩家图标发射一枚弹丸,当它到达屏幕时,它会在移动立方体所在的位置重生并能够再次发射。

这就是我目前所拥有的。

import pygame
pygame.init()
screen = pygame.display.set_mode((280, 800))
pygame.display.set_caption("Cube Run")
icon = pygame.image.load("cube.png")
pygame.display.set_icon(icon)
player_icon = pygame.image.load("cursor.png")
player_x = 128
player_y = 750
player_x_change = 0
cube_1 = pygame.image.load("rectangle.png")
cube1_x = 128
cube1_y = 0
cube1_x_change = 0.8
cube_fire = pygame.image.load("rectangle.png")
cube_fire_x = 0
cube_fire_y = 0
cube_y_change = 1.5
cube_fire_state = "ready"
def player(player_x, player_y):
screen.blit(player_icon, (player_x, player_y))
def cube(cube1_x, cube1_y):
screen.blit(cube_1, (cube1_x, cube1_y))
def cube_enemy(cube_fire_x, cube_fire_y):
screen.blit(cube_fire, (cube_fire_x, cube_fire_y))
running = True
while running:
screen.fill((255, 255, 255))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
player_x_change += 0.7
if event.key == pygame.K_LEFT:
player_x_change -= 0.7
if event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT or pygame.K_LEFT:
player_x_change = 0
player_x += player_x_change
if player_x < 0:
player_x = 0
elif player_x > 280-32:
player_x = 280-32
cube1_x += cube1_x_change
if cube1_x > 248:
cube1_x_change = -1
cube1_x += cube1_x_change
elif cube1_x < 0:
cube1_x_change = 1
cube1_x += cube1_x_change
cube_fire_x += cube1_x
cube_enemy(cube_fire_x, cube_fire_y)
player(player_x, player_y)
cube(cube1_x, cube1_y)
pygame.display.update()

您可以使用pygame.time.set_timer注册事件。创建一个新事件,并设置触发该事件之前应经过的毫秒数。然后,此事件将以设置的间隔显示。

FIRE_EVENT  = pygame.USEREVENT + 1  # This is just a integer.
OTHER_EVENT = pygame.USEREVENT + 2  # This is how you define more events.
pygame.time.set_timer(FIRE_EVENT, 1000)  # 1000 milliseconds is 1 seconds.

然后在事件循环中,检查此事件并执行任何操作。

for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
elif event.type == FIRE_EVENT:  # Will appear once every second.
make_square_fire()

如果要禁用该事件,只需将间隔设置为 0。

pygame.time.set_timer(FIRE_EVENT, 0)

在你的代码中,你没有包含任何类型的时间管理器——这意味着你的代码将尽可能快地运行,你无法真正控制它的速度,它实际上取决于它正在工作的机器和 CPU 负载等。

基本上,您希望故意在程序中等待恰到好处的时间,以便可以动态适应执行速度。你可以自己实现它(这并不难,而且有很多教程),但要先看一眼,你可以使用pygame.Clock: 首先,创建一个带有clock = pygame.Clock()的时钟。 然后,在主循环中,调用eta = clock.tick(FPS),其中FPS表示您希望应用程序运行的目标帧速率(如果真的不知道您希望它是什么值,您可以在程序开始时将其固定为 60),eta变量测量自上次即时报价调用以来经过的时间(以毫秒为单位)。

接下来,要让某些事情发生,比如说,每一秒,只需保留一个计数器:

counter = 1000 # in ms
clock = pygame.Clock()
while True:
# do what you want
eta = clock.tick(FPS)
counter -= eta
if counter < 0:
# trigger the event
counter += 1000
# don't set it directly like
# counter = 1000
# to keep track of margin

最新更新