我和我的熟人正在努力创建一个加载条,需要永远加载的乐趣。然而,当制作这个加载杆时,它似乎会在头一两秒钟内崩溃。代码如下:
import pygame
import time
import random
pygame.init()
progress = 0
black = [0, 0, 0]
white = [255, 255, 255]
green = [0, 255, 0]
screenWidth = 600
screenHeigth = 800
size = [screenWidth, screenHeigth]
font = pygame.font.SysFont("Comic Sans MS", 25)
clock = pygame.time.Clock()
screen = pygame.display.set_mode(size)
pygame.display.set_caption('Loading...')
def textObjecte(text, color, size):
if size == "small":
textsuraface = font.render(text, True, color)
return textsuraface, textsuraface.get_rect()
def loading(progress):
if progress < 100:
text = font.render("loading: " + str(int(progress)) + "%", True, green)
screen.blit(text, (300, 100))
def message_to_screen(msg, color, y_displace, size="small"):
textSurf, textRect = textObjecte(msg, color, size)
textRect.center = (screenWidth/2), (screenHeigth/2) + y_displace
screen.blit(textSurf, textRect)
while progress/2 < 100:
timeCount = random.randint(15, 30)
increase = random.randint(1, 7)
progress += increase
screen.fill(black)
pygame.draw.rect(screen, white, [300, 50, 200, 50])
pygame.draw.rect(screen, black, [301, 51, 198, 48])
if (progress/2) > 100:
pygame.draw.rect(screen, white, [302, 52, 196, 46])
else:
pygame.draw.rect(screen, white, [302, 52, progress, 46])
loading(progress/2)
pygame.display.flip()
time.sleep(timeCount)
任何代码方面的帮助都将不胜感激
有两件事需要改变:
您必须在每一帧处理事件(清空事件队列),否则窗口将变得无响应。调用^{} 或添加事件循环
for event in pygame.event.get():
必须删除
time.sleep
调用,因为它会阻塞程序,无法处理事件,窗口也会冻结(在指定的时间内)我不确定您想用
time.sleep
实现什么,但很可能有更好的方法你的问题是TextSurf是在一个函数中定义的,然后你试图在破坏它的函数之外使用它
您希望它缩进
$ screen.blit(textSurf, textRect)
,以便它位于函数内部相关问题 更多 >
编程相关推荐