程序崩溃不确定原因

时间:2014-03-02 12:07:20

标签: python-3.x pygame

您好我正在尝试制作一个简单的程序来更改按键时的背景颜色,但它只是崩溃了。这与我的循环有关,但我真的不明白它崩溃的原因。

谢谢

import sys, pygame, random, time
from threading import Thread
pygame.init()

black = (0, 0, 0)
white = (255, 255, 255)
green = (0, 100, 0)
red = (255, 0, 0)
Colour = (0,0,0)
size = width, height = 350, 350
screen = pygame.display.set_mode(size)

Running = True
while True:
    key = pygame.key.get_pressed()

    if key[pygame.K_ESCAPE]: # Escape key
        Running = False
    elif key[pygame.K_DOWN]: # down key
        print("down")
        Colour = red

    elif key[pygame.K_UP]: # up key
        print("h")
        Colour = black

    elif key[pygame.K_RIGHT]: # right key
        Colour = green

        print("h")
    elif key[pygame.K_LEFT]: # left key       
        Colour = white

        print("h")

    pygame.draw.rect(screen, Colour, pygame.Rect(0, 0, width, height))       
    pygame.display.update()
    pygame.display.flip()

2 个答案:

答案 0 :(得分:1)

你错过了pygame知道你是否想要退出窗口的方法。而不是key = pygame.key.get_pressed()使用:

for event in pygame.event.get():
    if event.type == QUIT:
        pygame.quit()
        sys.exit()
    if event.type == KEYDOWN:
        if event.key == K_ESCAPE:
            pygame.quit()
            sys.exit 
        if event.key == K_UP:
            Colour = black
        if event.key == K_DOWN:
            Colour = red
        if event.key == K_LEFT:
            Colour = white
        if event.key == K_RIGHT:
            Colour = green

您还需要一种程序来处理时间,例如没跑得比你看得快。您可以通过在代码顶部设置此变量来执行此操作:

clock = pygame.time.Clock()

并在while循环的最后运行:

clock.tick(FPS)

您可以将FPS设置为等于每秒所需帧数的数字。

您也可以从程序中删除Running = True变量。这应该是让它运行所需的一切。祝好运!提出以下问题。

答案 1 :(得分:0)

两件事:

你有一个错误:while循环,因为你正在测试while True而不是while Running。您可以更改为while Running或在测试转义密钥后,您可以break退出while循环。

此外,我刚才查找的所有pygame示例都有一个事件检查器。没有它,pygame会冻结。如果你添加它,一切都很顺利。

以下是两个更正的内容:

import sys, pygame, time
pygame.init()

size = 350, 350
screen = pygame.display.set_mode(size)

Running = True
while Running:  # <----- changed this from True to Running
    time.sleep(0.03)  # avoid blasting the CPU. I think pygame.time.Clock also exists

    # this makes pygame responsive
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            Running = False  # <---- or you could just break

    # from here is as you originally wrote
    key = pygame.key.get_pressed()
    if key[pygame.K_ESCAPE]:
        print('exit')
        Running = False  # <---- or you could just break

pygame.quit()
sys.exit()