问题描述
我刚刚开始学习 PyGame,现在我正在尝试为我的视图设置动画,但出乎意料的是,它只会在我移动鼠标时发生。我不知道为什么会这样。你知道是什么原因造成的吗?
代码如下:
import pygame,sys,random
pygame.init()
screenWidth = 1280
screenHeight = 720
screen = pygame.display.set_mode((screenWidth,screenHeight))
clock = pygame.time.Clock()
wood_bg = pygame.image.load('my_pic.jpg') # Background
land_bg = pygame.image.load('archive/Land_BG.png') # Animated
land_pos = 650
land_dir = "UP"
water_bg = pygame.image.load('archive/Water_BG.png') # Animated
water_pos = 630
water_dir = "UP"
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
screen.blit(wood_bg,(0,0))
screen.blit(land_bg,land_pos))
screen.blit(water_bg,water_pos))
# Animate water and land
if land_pos <= 520:
land_dir = "DOWN"
elif land_pos >= 620:
land_dir = "UP"
if land_dir == 'UP':
land_pos -= 2
else:
land_pos += 2
if water_pos <= 630:
water_dir = "DOWN"
elif water_pos >= 680:
water_dir = "UP"
if water_dir == 'UP':
water_pos -= 1
else:
water_pos += 1
pygame.display.update()
clock.tick(120)
解决方法
这是一个小的缩进错误。您拥有其余代码(在 for loop
之后:for event in pygame.event.get():
嵌套在此 for loop
下。这意味着下面的代码仅在收到 event
时才运行。为什么它仅在您的鼠标移动时移动,因为每次 event
都是您的鼠标移动事件。如果您的鼠标静止不动,则不会调用任何事件。
以下是修改后的代码供参考:
import pygame,sys,random
pygame.init()
screenWidth = 1280
screenHeight = 720
screen = pygame.display.set_mode((screenWidth,screenHeight))
clock = pygame.time.Clock()
wood_bg = pygame.image.load('my_pic.jpg') # Background
land_bg = pygame.image.load('archive/Land_BG.png') # Animated
land_pos = 650
land_dir = "UP"
water_bg = pygame.image.load('archive/Water_BG.png') # Animated
water_pos = 630
water_dir = "UP"
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# >>> All this code below had an extra indent,thus running under the "for loop" above
screen.blit(wood_bg,(0,0))
screen.blit(land_bg,land_pos))
screen.blit(water_bg,water_pos))
# Animate water and land
if land_pos <= 520:
land_dir = "DOWN"
elif land_pos >= 620:
land_dir = "UP"
if land_dir == 'UP':
land_pos -= 2
else:
land_pos += 2
if water_pos <= 630:
water_dir = "DOWN"
elif water_pos >= 680:
water_dir = "UP"
if water_dir == 'UP':
water_pos -= 1
else:
water_pos += 1
pygame.display.update()
clock.tick(120)
,
这是Indentation的问题。您必须在应用程序循环而不是事件循环中绘制场景并更新显示:
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# INDENTATION
#<--|
screen.blit(wood_bg,water_pos))
# Animate water and land
if land_pos <= 520:
land_dir = "DOWN"
elif land_pos >= 620:
land_dir = "UP"
if land_dir == 'UP':
land_pos -= 2
else:
land_pos += 2
if water_pos <= 630:
water_dir = "DOWN"
elif water_pos >= 680:
water_dir = "UP"
if water_dir == 'UP':
water_pos -= 1
else:
water_pos += 1
pygame.display.update()
clock.tick(120)