我正在尝试制作一个小游戏,但遇到一个似乎无法解决的问题。问题是在创建游戏循环和带有if
的{{1}}语句之后,我的精灵没有移动。你们能弄清楚并告诉我为什么它不起作用吗?
到目前为止,这是我的代码:
keyup
答案 0 :(得分:2)
我已经对您的主循环进行了重组以解决问题。我现在在事件循环中更改playerMovement
(速度),并使用它通过pygame.Rect.move_ip
方法更新主循环中的playerRect
。
顺便说一句,您可以将playerRect
传递到blit
以在topleft
(x, y
)坐标处使图像变白。
# The player's velocity. Define it outside of the main loop.
playerMovement = [0, 0]
while True:
# Handle events.
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.type == pygame.K_RIGHT or event.key == pygame.K_d:
playerMovement[0] = 2 # Set the x-velocity to the desired value.
if event.type == pygame.K_LEFT or event.key == pygame.K_a:
playerMovement[0] = -2
if event.type == pygame.KEYUP:
if event.type == pygame.K_RIGHT or event.key == pygame.K_d:
playerMovement[0] = 0 # Stop the player when the button is released.
if event.type == pygame.K_LEFT or event.key == pygame.K_a:
playerMovement[0] = 0
# Game logic.
playerRect.move_ip(playerMovement)
# Draw everything.
display.fill((214, 42, 78))
tileRect = []
y = 0
for row in level:
x = 0
for col in row:
if col == '2':
display.blit(grass, (x*16, y*16))
if col == '1':
display.blit(dirt, (x*16, y*16))
if col != '0':
tileRect.append(pygame.Rect(x*16,y*16,16,16))
x += 1
y += 1
display.blit(player, playerRect)
windowSurface.blit(pygame.transform.scale(display, windowSize), (0, 0))
pygame.draw.rect(windowSurface, black, playerRect)
pygame.display.update()
mainClock.tick(60)