python pygame how to incorporate loops?

conyieie :

I made a picture of Pacman and I am trying to make it move to the right across the screen. This is my code so far. I have the Pacman drawing but it is many shapes combined together and I don't know how to move all of them at once.

import os
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d, %d" %(20, 20)
import pygame
pygame.init()
BLACK = (0,0,0)
YELLOW = (255, 245, 59)
WHITE = (242, 242, 242)   
SIZE = (500, 500)                
screen = pygame.display.set_mode(SIZE)

# Fill background
pygame.draw.rect(screen, WHITE, (0,0, 500, 500))
pygame.draw.circle(screen, YELLOW, (250,250), 100,)
pygame.draw.circle(screen, BLACK, (250,250), 100, 3)
pygame.draw.circle(screen, BLACK, (260,200), 10,)
pygame.draw.polygon(screen, WHITE, ((250,250),(500,500),(500,100)))
pygame.draw.line(screen, BLACK, (250, 250), (334, 198), 3)
pygame.draw.line(screen, BLACK, (250, 250), (315, 318), 3)     
pygame.display.flip()
pygame.time.wait(5000)
Rabbid76 :

You have to add an application loop. The main application loop has to:

clock = pygame.time.Clock()
run = True
while run:
    clock.tick(60)

    # event loop
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    # update position
    # [...] 

    # clear the display
    screen.fill(WHITE)

    # draw the scene   
    pacman(px, py, dir_x) 

    # update the display
    pygame.display.flip()

Furthermore you have to draw pacman relative to a position (x, y) and a direction (dir_x). See the example:

import pygame
pygame.init()

BLACK = (0,0,0)
YELLOW = (255, 245, 59)
WHITE = (242, 242, 242)
SIZE = (500, 500)

screen = pygame.display.set_mode(SIZE)

def pacman(x, y, dir_x):
    sign_x = -1 if dir_x < 0 else 1  
    pygame.draw.circle(screen, YELLOW, (x, y), 100,)
    pygame.draw.circle(screen, BLACK, (x, y), 100, 3)
    pygame.draw.circle(screen, BLACK, (x+10*sign_x, y-50), 10,)
    pygame.draw.polygon(screen, WHITE, ((x, y),(x+250*sign_x, y+250),(x+250*sign_x, y-150)))
    pygame.draw.line(screen, BLACK, (x, y), (x+84*sign_x, y-52), 3)
    pygame.draw.line(screen, BLACK, (x, y), (x+65*sign_x, y+68), 3)     


px, py, dir_x = 250, 250, 1 

clock = pygame.time.Clock()
run = True
while run:
    clock.tick(60)

    # event loop
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    px += dir_x
    if px > 300 or px < 200:
         dir_x *= -1

    # clear the display
    screen.fill(WHITE)

    # draw the scene   
    pacman(px, py, dir_x) 

    # update the display
    pygame.display.flip()

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=13793&siteId=1