簡體   English   中英

為什么此代碼不起作用? (Python和PyGame)

[英]Why does this code not work? (Python and PyGame)

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次更改到另一個隨機位置,然后退出。

您缺少對pygame.display.flip()的調用,而該調用實際上未更新窗口內容-將其放在time.sleep調用之前。

在試驗Python和pygame API的早期階段,我的建議是在交互式控制台上嘗試一些東西。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM