Python Pygame如何加入循环?

3

我制作了一个 Pacman 的图片,现在想让它向右移动屏幕。目前的代码是这样的,虽然已经完成了 Pacman 的绘制,但是它由多个图形组合而成,不知道如何同时移动所有部分。

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)

每次清除屏幕并重新绘制。或者,更好的方法是使用具有透明度的图像。 - Maximouse
1个回答

3
你需要添加一个应用程序循环。主应用程序循环必须:
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()

此外,您需要根据位置(x, y)和方向(dir_x)来绘制Pacman。请参考以下示例:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接