这个简单的程序没有明显的原因冻结

时间:2017-03-07 23:55:43

标签: python pygame

我刚开始用Python编程。我一直在阅读这本名为“#34;使用Python制作游戏”的书。 Pygame的"到目前为止,它一直非常有用,但我找不到这个简单程序冻结的原因。它应该显示一个图像,然后向左或向右按​​下它。这很奇怪,因为它运作正常 - 我没有改变任何东西。我已经尝试了所有的东西,所以我非常感谢你的帮助!提前谢谢!

import pygame, sys 
from pygame import *

# VARIABLES
x_res = 400
y_res = 300
DISPLAYSURF = 0
event = 0
person = 0
posx = 50
posy = 50

pygame.init()
DISPLAYSURF = pygame.display.set_mode((x_res, y_res))
pygame.display.set_caption("Test")

person = pygame.image.load("Person.png")

while True: # main game loop
    DISPLAYSURF.blit(person, (posx, posy))

    if event in pygame.event.get():
        if event.type == KEYUP and event.key == K_RIGHT:
            posx = posx + 5
            DISPLAYSURF.fill((0,0,0))
        if event.type == KEYUP and event.key == K_LEFT:
            posx = posx - 5
            DISPLAYSURF.fill((0,0,0))
        if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE):
            pygame.quit()
            sys.exit()

    pygame.display.update()

3 个答案:

答案 0 :(得分:0)

我不确定你的意思"冷冻"在这种情况下,但我想这个问题是因为你没有一个名为"Person.png"的图像,因为当我在我的文件系统上没有图像"Person.png"的情况下试用你的代码时,它也冻结了并且给了我关于IDLE的错误:

Traceback (most recent call last):
  File "/Users/me/Desktop/your_program.py", line 17, in <module>
    person = pygame.image.load("Person.png")
pygame.error: Couldn't open Person.png

相反,如果我有一个名为"Person.png"的图像,它可以正常工作。

答案 1 :(得分:-1)

我之前从未使用pygame,但只要我冻结了应用,就会因为无限制的循环而没有限制。

我猜你的while循环没有任何东西暂停处理,因此程序尽可能快地在while循环中运行代码 - 不允许时间更新。

尝试根据所需的帧速率在while循环结束时添加睡眠。示例time.sleep()实现:

import time
time.sleep(5) # delays for 5 seconds (you probably don't want 5 seconds...)

答案 2 :(得分:-4)

尝试写“(wilst)true”而不是while? :)