每次我在窗口中点击时,Pygame都会崩溃

时间:2015-10-20 04:07:41

标签: python pygame

以下是代码:

import pygame, time

pygame.init()

white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
green = (0,155,0)
blue = (0,0,255)

def button(x,y,w,h,action=None):
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()
    if x+w > mouse[0] > x and y+h > mouse[1] > y:
        if click [0] == 1 and action != None:
            if action == "exit":
                pygame.quit()
                quit()

gameDisplay = pygame.display.set_mode((800,600))
pygame.display.set_caption("Game")
clock = pygame.time.Clock()

gameExit = False
menu1 = True
menu2 = True
gameloop = True

while not gameExit:   
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            gameExit = True

    while menu1:
        logo1 = pygame.image.load('logo.jpg')
        gameDisplay.blit(logo1, (1, 1))
        time.sleep(2)
        pygame.display.update()

        while menu2:
            logo2 = pygame.image.load("logo2.jpg")
            gameDisplay.blit(logo2, (0, 0))
            time.sleep(2)
            pygame.display.update()
            time.sleep(2)

            while gameloop:
                gameDisplay.fill(white)
                button(0, 0, 10,10,"exit")
                pygame.draw.rect(gameDisplay, red, (0, 0, 10, 10))
                pygame.display.update()
    clock.tick(15)
pygame.quit()
quit()

我假设它的所有while循环,我想创建一个2个徽标的幻灯片放映,每个徽标播放2秒(这是有效的)但是一旦我通过幻灯片放映,我点击关闭,它崩溃了。我尝试添加一个快速按钮(右上角的红色方块),它也崩溃了。我完全难过,看了一切,做了很多改变,但它崩溃了......请帮助,提前谢谢。

1 个答案:

答案 0 :(得分:0)

您的while循环 导致您的问题,因为您永远不会突破它们。

就我个人而言,我认为您应该使用当前的pygame.time.get_ticks()来为您的活动计时。这是一个例子:

# Code above here is unchanged

gameExit = False

logo1 = pygame.image.load('logo.png')  # Don't load these in a loop!
logo2 = pygame.image.load('logo2.png') # Only need to load them once.

# Make sure you record start_time here! Because the timer actually
# started several seconds before the display is ready.

start_time = pygame.time.get_ticks() / 1000

while not gameExit:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            gameExit = True

    time = pygame.time.get_ticks() / 1000
    elapsed = time - start_time

    gameDisplay.fill(black)

    if elapsed > 4:
        gameDisplay.fill(white)
        button(0, 0, 10, 10, 'exit')
        pygame.draw.rect(gameDisplay, red, (0, 0, 10, 10))
    elif elapsed > 2:
        gameDisplay.blit(logo2, (0, 0))
    elif elapsed > 0:
        gameDisplay.blit(logo1, (1, 1))

    pygame.display.update()
    clock.tick(15)

pygame.quit()
quit()

我所做的是检查elapsed时间是否大于4秒。如果是这样,请显示红色方块。如果没有,我们去下一个。是2秒后的时间吗?如果是,请显示logo2。最后,如果时间是> 0,它在开头是正确的,我们会显示logo1。它们以相反的顺序设置,因为if / elif的工作方式:它只捕获第一个True。随着时间的推移,越来越高的选项变为True

这有意义吗?