我不知道为什么,但是我的PyGame游戏在启动game()
函数时冻结了。
我试图逐行删除功能中的问题,并且在所有尝试中游戏仍然停滞。
给我带来问题的函数是:
def game():
global Bone1_pos
global Bone2_pos
global Bone1_y
global Bone2_y
Bone1_x = 500
Bone2_x = 1100
clock.tick(FPS)
#Pos 1
if Bone1_pos == 1:
Bone1_y = -80
if Bone2_pos == 1:
Bone2_y = -80
#Pos 2
if Bone1_pos == 2:
Bone1_y = -40
if Bone2_pos == 2:
Bone2_y = -40
#Pos 3
if Bone1_pos == 3:
Bone1_y = 25
if Bone2_pos == 3:
Bone2 = 25
pygame.event.get()
BoneUp1.rect = pygame.Rect(Bone1_x, Bone1_y, 75, 173)
BoneDown1.rect = pygame.Rect(Bone1_x, Bone1_y + 450, 75, 173)
BoneUp2.rect = pygame.Rect(Bone2_x, Bone2_y, 75, 173)
BoneDown2.rect = pygame.Rect(Bone2_x, Bone2_y + 450, 75, 173)
#Sprite blit
screen.blit(background, (0, 0))
screen.blit(BoneDown1.image, (Bone1_x, Bone1_y + 400))
screen.blit(BoneUp1.image, (Bone1_x, Bone1_y))
screen.blit(BoneDown2.image, (Bone2_x, Bone2_y + 400))
screen.blit(BoneUp2.image, (Bone2_x, Bone2_y))
screen.blit(spikeUp0.image, (0, 0))
screen.blit(spikeDown0.image, (0, 436))
screen.blit(Dog.image, (Dog.rect.topleft))
if pygame.key.get_pressed()[K_UP]: # Up
Dog.rect.y -= 1
pygame.time.delay(2)
else: # Down
Dog.rect.y += 1
pygame.time.delay(2)
if pygame.key.get_pressed() [K_LEFT]: # Left
Dog.rect.x -= 1
pygame.time.delay(2)
if pygame.key.get_pressed() [K_RIGHT]: # Right
Dog.rect.x += 1
pygame.time.delay(2)
# Barrier
if Dog.rect.x < 0:
Dog.rect.x = 0
elif Dog.rect.x > 822:
Dog.rect.x = 822
# Collison
for s in [spikeUp0, spikeDown0, BoneUp1, BoneDown1, BoneUp2, BoneDown2]:
if pygame.sprite.collide_rect(Dog, s):
pygame.quit()
sys.exit()
pygame.display.update()
Bone1_x -= 1
Bone2_x -= 1
if Bone1_x <= -40 :
Bone1_pos = random.randint(1,3)
Bone1_x = 1100
if Bone2_x <= -40:
Bone2_pos = random.randint(1,3)
Bone2_x = 1100
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
答案 0 :(得分:3)
问题是pygame.event.get()
被两次调用:
def game(): # [...] clock.tick(FPS) # [...] pygame.event.get() # [...] for event in pygame.event.get(): if event.type == pygame.QUIT: # [...]
请注意,pygame.event.get()
获取所有消息并将其从队列中删除。因此,第一个呼叫将获取消息,将其删除并将其放置在任何地方。第二次通话根本没有任何消息。
至少您必须在pygame.event.get()
(例如clock.tick(FPS)
)的调用之间进行“延迟”。
删除pygame.event.get()
的第一个调用,并将事件循环移至game
的开头:
def game():
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
# [...]
请注意,呼叫pygame.quit()
之后再呼叫pygame.display.update()
没有任何意义。 pygame.quit()
未初始化所有pygame模块,并导致所有对pygame操作的进一步调用均崩溃。
不要忘记通过pygame.display.update()
或pygame.display.flip()
更新游戏循环中的显示。
向函数game
添加一个返回值。当游戏循环应该继续时返回True
,当应用程序应该停止时返回False
:
def game():
returnCode = True
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
returnCode = False
# [...]
for s in [spikeUp0, spikeDown0, BoneUp1, BoneDown1, BoneUp2, BoneDown2]:
if pygame.sprite.collide_rect(Dog, s):
returnCode = False
# [...]
return returnCode
run = True
while run:
run = game()
pygame.display.update()
pygame.quit()
sys.exit()