python - python pygame如何合并循环?
问题描述
我拍了一张吃豆人的照片,并试图让它在屏幕上向右移动。到目前为止,这是我的代码。我有 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)
解决方案
您必须添加一个应用程序循环。主应用程序循环必须:
- 通过
pygame.event.pump()
或处理事件pygame.event.get()
。 - 根据输入事件和时间(分别为帧)更新对象的游戏状态和位置
- 清除整个显示或绘制背景
- 绘制整个场景(绘制 pacman)
- 通过
pygame.display.update()
或更新显示pygame.display.flip()
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()
推荐阅读
- android - 从 LifeCycleService 观察 LiveData
- android - 将可绘制文件夹从“大”重构为“sw123dp”
- sql - convert existing local datetime entries to UTC
- ios - Undefined symbols for architecture x86_64: in Xcode 9.4
- python - 如何在条件下从数据框中删除选定的行
- git - Rundeck:使用 ssh 在远程服务器中运行命令
- python - 索引在熊猫中未被识别
- excel - 数据透视表切片器的报表连接不显示所有数据透视表?
- arangodb - slurm sbatch 提交后,ArangoDB 保持沉默
- java - Groovy DexArchiveBuilderException