简体   繁体   中英

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()

I'm very new to programming and I'm just trying out a few basic things with PyGame. The screen remains black and no smiley faces appear. I am trying to make the faces appear on the black background, and change to another random place every 3 seconds, 5 times and then quit.

You are missing a call to pygame.display.flip() to actually update the window contents- put it just before your time.sleep call.

My advice at this early stage of experimenting with Python and the pygame API would be to try stuff at the interactive console..

first of all, it needs to be in a while loop (at least if you are going to do much more) also, you are missing the background. this should work:

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM