gpt4 book ai didi

python - 自己制作的游戏。 Game Over 后不执行 Else 分支

转载 作者:行者123 更新时间:2023-12-01 07:10:35 25 4
gpt4 key购买 nike

我使用 Pygame Zero 和 MU IDE 创建了一个小游戏。玩家必须在一定时间内点击(收集)尽可能多的香蕉。每次收集到一根香蕉,就会在随机位置出现一根新香蕉。

时间过去后,将出现一个新屏幕,其中显示已收集多少香蕉的信息。为此,我创建了一个 If Else 语句,但程序不会执行 Else 分支(除了减少 1 秒时间并关闭游戏窗口)。我不知道为什么。有谁知道为什么 Else 分支没有执行?

from random import randint 
import time
import pygame

HEIGHT = 800
WIDTH = 800
score = 0
time_left = 10

banana = Actor("banana")
monkey = Actor("monkey")

def draw():
screen.clear()
screen.fill("white")
banana.draw()
monkey.draw()
screen.draw.text("Number of bananas collected: " + str(score), color = "black", topleft=(10,10))
screen.draw.text("Time: " + str(time_left), color = "black", topleft=(10,50))

def place_banana():
banana.x = randint(125, 790)
banana.y = randint(186, 790)
monkey.x = 50
monkey.y = 740

def on_mouse_down(pos):
global score
if banana.collidepoint(pos):
score = score + 1
place_banana()

def update_time_left():
global time_left
if time_left: # wenn Zeit > 0 Sekunden ist
time_left = time_left - 1
else:
screen.fill("pink") # code is not executed
game_over()

place_banana()
clock.schedule_interval(update_time_left, 1.0)

def game_over():
screen.fill("pink") # code is not executed
global time_left
message = ("Ende. Number of bananas collected") # code is not executed
time_left = 0
time.sleep(5.5)
quit()

最佳答案

代码当然被执行了,但是你无法在显示屏上“看到”结果,因为在 screen.fill("pink") 之后(在 time.sleep(5.5 )) 显示未更新。
您必须通过 pygame.display.update() 更新显示并通过(例如) pygame.event.pump() 处理事件当显示被填充为粉红色后。

def game_over():

screen.fill("pink")
# [...] draw something else (e.g. some text)

pygame.display.update()
pygame.event.pump()

time.sleep(5.5)
quit()

关于python - 自己制作的游戏。 Game Over 后不执行 Else 分支,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58239163/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com