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

2024-09-30 05:23:48 发布

您现在位置:Python中文网/ 问答频道 /正文

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次,然后退出。在


Tags: importtimedisplaysysrandommathscreenpygame
2条回答

您缺少一个调用pygame.display.flip()来实际更新窗口内容-请将它放在time.sleep调用之前。在

在Python和pygamaapi的早期试验阶段,我的建议是在交互式控制台上尝试一些东西。。在

首先,它需要在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()

相关问题 更多 >

    热门问题