python pygame如何合并循环?

标签 python pygame

<分区>

我制作了一张 Pacman 的图片,并试图让它在屏幕上向右移动。到目前为止,这是我的代码。我有吃 bean 人图,但它有很多形状组合在一起,我不知道如何一次移动所有形状。

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)

最佳答案

您必须添加一个应用程序循环。主应用程序循环必须:

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

此外,您必须相对于位置(xy)和方向(dir_x)绘制吃 bean 人。看例子:

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

关于python pygame如何合并循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60439616/

相关文章:

python - 如何使用 Python kazoo 库?

python - 将 3d 数组中的特定列复制到 2d 数组 [Python/Pygame]

python - 段错误: 11 when I run Pygame

python - 无法使用 pip 安装 Pygame

python - 制作一个可以捕捉到屏幕的 pygame 可调整大小的窗口

Python 和 SQLite : Can't execute query due to a syntax error

Python:打印 pandas 数据框时删除列表元素的括号

python - 为什么这个 Python 代码在 Ubuntu 上会出现段错误,但在 Windows 上却没有?

python - 使用python代码删除目录和子目录中的重复文件

python - 我可以将一条路线用于多种功能吗?