python - 在 pygame 空间入侵者的按键上交换船舶图像
问题描述
我想在使用 pygame 的太空侵略者游戏中拥有替代角色。如果我按 1,我希望游戏将船舶切换到船舶 1,如果我按 2,我希望游戏切换到船舶 2,依此类推。
我曾尝试在我的 ship.py 文件中更改 self.image,以便:
for event in pygame.event.get():
if event.type == pygame.K_1:
self.image = pygame.image.load('images/ship1.bmp')
self.image.get_rect()
elif event.type == pygame.K_2:
self.image == pygame.image.load('images/ship2.bmp')
self.image.get_rect()
但这会在我的主要外星人入侵程序中返回一些关于船级的错误。
下面是我加载的静态图像的工作代码,这也是我尝试使用 if 和 elif 语句更改的代码。任何建议将不胜感激。如果它有帮助,我是一个非常笨拙的编码器。
class Ship(Sprite):
"""A class to manage the ship."""
def __init__(self, ai_game):
"""Initialize the ship and set its starting position."""
super().__init__()
self.screen = ai_game.screen
self.settings = ai_game.settings
self.screen_rect = ai_game.screen.get_rect()
# Load the ship image and get its rect.
self.image = pygame.image.load('images/ship.bmp')
self.rect = self.image.get_rect()
解决方案
首先加载不在循环中的图像。
image1 = pygame.image.load('image1')
image2 = pygame.image.load('image2')
#replace image 1 with your image
#in the event loop
screen.blit(image1, (Your wish dimensions))
#note that I took screen.blit because I made my screen in a variable called screen.
#If you variable is display take display.blit
if event.type == pygame.KEYDOWN:
if pygame.key == pygame.K_RIGHT:
image1 = image 2
推荐阅读
- sql-server - 当 SQL Server 中的字符串太长时,如何添加破折号来分隔字符串?我需要编写脚本,而不是硬编码...谢谢
- reactjs - 使用反应引导的网格
- javascript - 我可以在 javascript .click 函数上启动一系列事件吗?
- vba - 打开具有基于表单 A 的子表单的表单 B
- java - 为什么 HotSpot ExecutionSample 事件总是返回 STATE_RUNNABLE?
- git - 要求 git 提交来自 *@mydomain.com
- php - 我在我的 laravel 项目中找不到 layout.blade.php
- excel - Excel:IF ISBLANK 函数将 6 个附加行视为已填充
- ruby-on-rails - ActiveModel:: Accounts::RetreatsController#create 中缺少属性错误
- netlogo - rnd:weighted-one-of-list work 不会返回我认为应该的分布