gpt4 book ai didi

python - Sprite 在pygame中不会移动

转载 作者:行者123 更新时间:2023-12-01 07:10:24 29 4
gpt4 key购买 nike

此代码中的“行星” Sprite 不会左右移动,也不会动画。错误在哪里?实际上,该列表来自 Google Play 的应用程序“Programming Hero”,该应用程序的作者一步步指导学生使用 Python 完成视频游戏制作过程...

import pygame

screen_size = [360,640]
screen = pygame.display.set_mode(screen_size)
background = pygame.image.load('background.png')
planet = pygame.image.load('one.png')
spaceship = pygame.image.load('spaceship.png')
bullet = pygame.image.load('bullet.png')


keep_alive = True
planet_x = 140 # I've edited this
move_direction = 'right' # out of the loop, too

# according to the same logic "I've saved the planet" to go infinitely right
# thanx

while keep_alive:
pygame.event.get()
keys = pygame.key.get_pressed()
if keys[pygame.K_SPACE] == True:
print('Space key pressed')

screen.blit(background, [0,0])
screen.blit(bullet,[180,500])
screen.blit(spaceship,[160,500])

# I put this out off loop: planet_x = 140
# wrong, must go out of a loop, too: move_direction = 'right'

if move_direction == 'right':
planet_x = planet_x + 5
if planet_x == 270:
move_direction = 'left'
else:
planet_x = planet_x - 5
if planet_x == 0:
move_direction = 'right'

screen.blit(planet, [planet_x, 50])
pygame.display.update()

最佳答案

行星的位置 (planet_x) 在每一帧中都会重新初始化:

while keep_alive:
# [...]

planet_x = 140

if move_direction == 'right':
planet_x = planet_x + 5

# [...]

screen.blit(planet, [planet_x, 50])

planet_x的初始化移至主应用程序循环之前:

planet_x = 140
while keep_alive:

# [...]

if move_direction == 'right':
planet_x = planet_x + 5

# [...]

screen.blit(planet, [planet_x, 50])

关于python - Sprite 在pygame中不会移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58251306/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com