【发布时间】:2021-02-04 08:21:11
【问题描述】:
我正在 python 速成课程中练习 python,我正在做第一个项目,即外星人入侵。 我仍然处于它的开始部分,您开始从左到右移动船,并且在 keydown 和 keyup 上它工作正常。对于左键,它只是一直向左移动,不会停止移动。我已经完全按照书中所说的写了,我在这里和谷歌上看了看是否有其他人也有这个错误,但似乎找不到任何可以帮助我的东西。
外星人入侵.py
import pygame
from settings import Settings
from ship import Ship
import game_functions as gf
def run_game():
# Initialize game and create a screen object.
pygame.init()
ai_settings = Settings()
screen = pygame.display.set_mode(
(ai_settings.screen_width, ai_settings.screen_height))
pygame.display.set_caption("Alien Invasion")
# Make a ship
ship = Ship(screen)
# Start the main loop for the game.
while True:
gf.check_events(ship)
ship.update()
gf.update_screen(ai_settings, screen, ship)
run_game()
game_functions.py
import sys
import pygame
def check_events(ship):
"""Respond to keypresses and mouse events"""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
ship.moving_right = True
elif event.key == pygame.K_LEFT:
ship.moving_left = True
elif event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT:
ship.moving_right = False
elif event.key == pygame.K_LEFT:
ship.moving_left == False
def update_screen(ai_settings, screen, ship):
"""Update images on the screen and flip to the new screen."""
# Redraw the screen during each pass through the loop.
screen.fill(ai_settings.bg_color)
ship.blitme()
# make the most recently drawn screen visible.
pygame.display.flip()
ship.py 导入pygame
class Ship():
def __init__(self, screen):
"""Initialize the ship and set its starting position."""
self.screen = screen
# Load the ship image and get its rect.
self.image = pygame.image.load('img/ship.bmp')
self.rect = self.image.get_rect()
self.screen_rect = screen.get_rect()
# Start each new ship at the bottom center of the screen.
self.rect.centerx = self.screen_rect.centerx
self.rect.bottom = self.screen_rect.bottom
# Movement flags
self.moving_right = False
self.moving_left = False
def update(self):
"""Update the ships's position based on the movement flag"""
if self.moving_right:
self.rect.centerx += 1
if self.moving_left:
self.rect.centerx -= 1
def blitme(self):
"""Draw the ship at its current location"""
self.screen.blit(self.image, self.rect)
【问题讨论】: