因此,我在开发游戏中的太空飞船运动时遇到了一些麻烦。我检查了几次代码,但仍然找不到。该项目来自该视频https://www.youtube.com/watch?v=FfWpgLFMI7w,并且我在44:55分钟就收到了这个错误,并且我正在使用Python 3.8。这是代码。
import pygame
# Initiate pygame
pygame.init()
# Display the game window
screen = pygame.display.set_mode((800,600))
# Title and Icon
pygame.display.set_caption('Space Invaders')
icon = pygame.image.load('icon.png')
pygame.display.set_icon(icon)
# Player
playerSprite = pygame.image.load('player.png')
playerX = 370
playerY = 480
playerX_change = 0
def player(x,y):
screen.blit(playerSprite, (x, y))
# Game Loop
running = True
while running:
# Background color (RGB)
screen.fill((0, 0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# If a key is pressed, check if it's the right or left arrow key
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_change = -0.1
if event.key == pygame.K_RIGHT:
playerX_change = 0.1
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0.1
# Move the spaceship to the left or right
playerX_change += playerX
player(playerX,playerY)
pygame.display.update()
答案 0 :(得分:1)
您必须更改播放器的位置(playerX
),而不是移动距离playerX_change
:
playerX_change += playerX
playerX += playerX_change
无论如何,可以使用pygame.key.get_pressed()
来简化代码。 pygame.key.get_pressed()
返回表示每个键状态的布尔值序列:
# Game Loop
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Move the spaceship to the left or right
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
playerX -= 0.1
if keys[pygame.K_RIGHT]:
playerX += 0.1
# Background color (RGB)
screen.fill((0, 0, 0))
player(playerX,playerY)
pygame.display.update()