为什么这段代码不起作用? (Python和PyGame)

时间:2013-04-01 20:27:02

标签: python image time pygame blit

import math, sys, os, pygame, random, time

pygame.init()
screen = pygame.display.set_mode((500,500))
pygame.display.set_caption('Tester.')
pygame.mouse.set_visible(0)


def smileMove():
    smiley = pygame.image.load('smiley.png')
    random.seed()
    xMove = random.randrange(1,501)
    yMove = random.randrange(1,501)

    screen.blit(smiley,(xMove,yMove))


c = 0

while c <5:
    smileMove()
    time.sleep(3)
    c = c + 1

pygame.quit()

我对编程非常陌生,我只是尝试使用PyGame做一些基本的事情。 屏幕保持黑色,不显示笑脸。我试图使面部出现在黑色背景上,并每3秒更换一个随机位置,5次然后退出。

2 个答案:

答案 0 :(得分:1)

您错过了对pygame.display.flip()的实际更新窗口内容的电话 - 将其放在time.sleep来电之前。

我在Python和pygame API实验的早期阶段的建议是在交互式控制台上尝试一些东西..

答案 1 :(得分:0)

首先,它需要在一个while循环中(至少如果你要做更多的事情),你也错过了背景。这应该有效:

import math, sys, os, pygame, random, time

pygame.init()
screen = pygame.display.set_mode((500,500))
pygame.display.set_caption('Tester.')
pygame.mouse.set_visible(0)
white = ( 255, 255, 255)

def smileMove():
    screen.fill(white)
    smiley = pygame.image.load('smiley.png')
    random.seed()
    xMove = random.randrange(1,501)
    yMove = random.randrange(1,501)

    screen.blit(smiley,(xMove,yMove))

c = 0
done = False
while done==False:
    for event in pygame.event.get(): # User did something
        if event.type == pygame.QUIT: # If user clicked close
            done=True # Flag that we are done so we exit this loop

    screen.fill(white)
    while c <5:
        smileMove()
        pygame.display.flip()
        c = c + 1
        time.sleep(3)
pygame.quit()