如何更改太空入侵者计划中的图像?
Posted
技术标签:
【中文标题】如何更改太空入侵者计划中的图像?【英文标题】:How to Change Images in Space Invaders Program? 【发布时间】:2022-01-15 09:53:55 【问题描述】:语言:Python
不久前,我关注了一个关于太空入侵者的教程,比如来自 youtube 的游戏,并希望将代码重用于我正在做的项目并只是更改图像,但是当我去更改图像时,代码没有处理错误:
Traceback (most recent call last):
File "/Users/carolinerongen/Desktop/ListGames/ListGame.py", line 277, in <module>
main_menu()
File "/Users/carolinerongen/Desktop/ListGames/ListGame.py", line 273, in main_menu
main()
File "/Users/carolinerongen/Desktop/ListGames/ListGame.py", line 207, in main
enemy = Enemy(random.randrange(50, WIDTH-100), random.randrange(-1500, -100), random.choice(["llama1", "llama2", "llama3"]))
File "/Users/carolinerongen/Desktop/ListGames/ListGame.py", line 133, in __init__
self.ship_img, self.laser_img = self.COLOR_MAP[color]
KeyError: 'llama1'
>>>
当我运行代码时会显示背景图像,但我放置的所有其他新图像都不起作用或显示。我如何让他们出现/我做错了什么?
这是我的代码:
import pygame
import pygame as pg
import os
import time
import random
pg.font.init()
WIDTH, HEIGHT = 750, 750
WIN = pg.display.set_mode((WIDTH, HEIGHT))
pg.display.set_caption("Llamas!")
llama1 = pg.image.load(os.path.join("assets", "llama.png"))
llama2 = pg.image.load(os.path.join("assets", "llama.png"))
llama3 = pg.image.load(os.path.join("assets", "llama.png"))
llama4 = pg.image.load(os.path.join("assets", "llama.png"))
playerss = pg.image.load(os.path.join("assets", "pixel_ship_yellow.png"))
playerl = pg.image.load(os.path.join("assets", "pixel_laser_yellow.png"))
redl = pg.image.load(os.path.join("assets", "pixel_laser_red.png"))
greenl = pg.image.load(os.path.join("assets", "pixel_laser_green.png"))
bluel = pg.image.load(os.path.join("assets", "pixel_laser_blue.png"))
background = pg.transform.scale(pg.image.load(os.path.join("assets", "sand.png")), (WIDTH, HEIGHT))
class Laser:
def __init__(self, x, y, img):
self.x = x
self.y = y
self.img = img
self.mask = pygame.mask.from_surface(self.img)
def draw(self, window):
window.blit(self.img, (self.x, self.y))
def move(self, vel):
self.y += vel
def off_screen(self, height):
return not(self.y <= height and self.y >= 0)
def collision(self, obj):
return collide(self, obj)
class Ship:
COOLDOWN = 30
def __init__(self, x, y, health=100):
self.x = x
self.y = y
self.health = health
self.ship_img = None
self.laser_img = None
self.lasers = []
self.cool_down_counter = 0
def draw(self, window):
window.blit(self.ship_img, (self.x, self.y))
for laser in self.lasers:
laser.draw(window)
def move_lasers(self, vel, obj):
self.cooldown()
for laser in self.lasers:
laser.move(vel)
if laser.off_screen(HEIGHT):
self.lasers.remove(laser)
elif laser.collision(obj):
obj.health -= 10
self.lasers.remove(laser)
def cooldown(self):
if self.cool_down_counter >= self.COOLDOWN:
self.cool_down_counter = 0
elif self.cool_down_counter > 0:
self.cool_down_counter += 1
def shoot(self):
if self.cool_down_counter == 0:
laser = Laser(self.x, self.y, self.laser_img)
self.lasers.append(laser)
self.cool_down_counter = 1
def get_width(self):
return self.ship_img.get_width()
def get_height(self):
return self.ship_img.get_height()
class Player(Ship):
def __init__(self, x, y, health=100):
super().__init__(x, y, health)
self.ship_img = playerss
self.laser_img = playerl
self.mask = pygame.mask.from_surface(self.ship_img)
self.max_health = health
def move_lasers(self, vel, objs):
self.cooldown()
for laser in self.lasers:
laser.move(vel)
if laser.off_screen(HEIGHT):
self.lasers.remove(laser)
else:
for obj in objs:
if laser.collision(obj):
objs.remove(obj)
if laser in self.lasers:
self.lasers.remove(laser)
def draw(self, window):
super().draw(window)
self.healthbar(window)
def healthbar(self, window):
pg.draw.rect(window, (255,0,0), (self.x, self.y + self.ship_img.get_height() + 10, self.ship_img.get_width(), 10))
pg.draw.rect(window, (0,255,0), (self.x, self.y + self.ship_img.get_height() + 10, self.ship_img.get_width() * (self.health/self.max_health), 10))
class Enemy(Ship):
COLOR_MAP =
"l1": (llama1, bluel),
"l2": (llama2, bluel),
"l3": (llama3, bluel),
"l4": (llama4, bluel)
def __init__(self, x, y, color, health=100):
super().__init__(x, y, health)
self.ship_img, self.laser_img = self.COLOR_MAP[color]
self.mask = pg.mask.from_surface(self.ship_img)
def move(self, vel):
self.y += vel
def shoot(self):
if self.cool_down_counter == 0:
laser = Laser(self.x-20, self.y, self.laser_img)
self.lasers.append(laser)
self.cool_down_counter = 1
def collide(obj1, obj2):
offset_x = obj2.x - obj1.x
offset_y = obj2.y - obj1.y
return obj1.mask.overlap(obj2.mask, (offset_x, offset_y)) != None
def main():
run = True
FPS = 60
level = 0
lives = 5
main_font = pg.font.SysFont("comicsans", 50)
lost_font = pg.font.SysFont("comicsans", 60)
enemies = []
wave_length = 5
enemy_vel = 1
player_vel = 5
laser_vel = 5
player = Player(300, 630)
clock = pg.time.Clock()
lost = False
lost_count = 0
def redraw_window():
WIN.blit(background, (0,0))
# draw text
lives_label = main_font.render(f"Lives: lives", 1, (255,255,255))
level_label = main_font.render(f"Level: level", 1, (255,255,255))
WIN.blit(lives_label, (10, 10))
WIN.blit(level_label, (WIDTH - level_label.get_width() - 10, 10))
for enemy in enemies:
enemy.draw(WIN)
player.draw(WIN)
if lost:
lost_label = lost_font.render("You Lost!!", 1, (255,255,255))
WIN.blit(lost_label, (WIDTH/2 - lost_label.get_width()/2, 350))
pg.display.update()
while run:
clock.tick(FPS)
redraw_window()
if lives <= 0 or player.health <= 0:
lost = True
lost_count += 1
if lost:
if lost_count > FPS * 3:
run = False
else:
continue
if len(enemies) == 0:
level += 1
wave_length += 5
for i in range(wave_length):
enemy = Enemy(random.randrange(50, WIDTH-100), random.randrange(-1500, -100), random.choice(["llama1", "llama2", "llama3"]))
enemies.append(enemy)
for event in pg.event.get():
if event.type == pg.QUIT:
quit()
keys = pg.key.get_pressed()
if (keys[pg.K_a] or keys[pg.K_LEFT])and player.x - player_vel > 0: # left
player.x -= player_vel
if (keys[pg.K_d] or keys[pg.K_RIGHT]) and player.x + player_vel + player.get_width() < WIDTH: # right
player.x += player_vel
if (keys[pg.K_w] or keys[pg.K_UP]) and player.y - player_vel > 0: # up
player.y -= player_vel
if (keys[pg.K_s] or keys[pg.K_DOWN]) and player.y + player_vel + player.get_height() + 15 < HEIGHT: # down
player.y += player_vel
if keys[pg.K_SPACE]:
player.shoot()
for enemy in enemies[:]:
enemy.move(enemy_vel)
enemy.move_lasers(laser_vel, player)
if random.randrange(0, 2*60) == 1:
enemy.shoot()
if collide(enemy, player):
player.health -= 10
enemies.remove(enemy)
elif enemy.y + enemy.get_height() > HEIGHT:
lives -= 1
enemies.remove(enemy)
player.move_lasers(-laser_vel, enemies)
def main_menu():
title_font = pg.font.SysFont("comicsans", 70)
directions_font = pg.font.SysFont("comicsans", 50)
cwhite = 255,255,255
cother = 176, 0, 155
run = True
while run:
WIN.blit(background, (0,0))
title_label = title_font.render("Press the mouse to begin...", 1, (cwhite))
directions_label = directions_font.render("SPACE:shoot W/UP:up S/DOWN:down", 1, (cother))
directions2_label = directions_font.render("A/LEFT-ARROW:left ", 1, (cother))
directions3_label = directions_font.render("D/RIGHT-ARROW:right ", 1, (cother))
directions4_label = directions_font.render("You can move all around the screen, ", 1, (cother))
directions5_label = directions_font.render("but if you gethit by a laser or ", 1, (cother))
directions6_label = directions_font.render("spaceship your helth is decreased ", 1, (cother))
directions7_label = directions_font.render("if a ship pases beyond the screen ", 1, (cother))
directions8_label = directions_font.render("you lose a life(shown in right corner).", 1, (cother))
WIN.blit(title_label, (WIDTH/2 - title_label.get_width()/2, 200))
WIN.blit(directions_label, (WIDTH/2 - directions_label.get_width()/2, 300))
WIN.blit(directions2_label, (WIDTH/2 - directions_label.get_width()/2, 350))
WIN.blit(directions3_label, (WIDTH/2 - directions_label.get_width()/2, 400))
WIN.blit(directions4_label, (WIDTH/2 - directions_label.get_width()/2, 450))
WIN.blit(directions5_label, (WIDTH/2 - directions_label.get_width()/2, 500))
WIN.blit(directions6_label, (WIDTH/2 - directions_label.get_width()/2, 550))
WIN.blit(directions7_label, (WIDTH/2 - directions_label.get_width()/2, 600))
WIN.blit(directions8_label, (WIDTH/2 - directions_label.get_width()/2, 650))
pg.display.update()
for event in pg.event.get():
if event.type == pg.QUIT:
run = False
if event.type == pg.MOUSEBUTTONDOWN:
main()
pg.quit()
main_menu()
【问题讨论】:
请修剪您的代码,以便更容易找到您的问题。请按照以下指南创建minimal reproducible example。 【参考方案1】:COLORMAP
正在使用字符串 "l1"
、"l2"
、"l3"
。因此,您应该在它们之间进行选择并使用random.choice(["l1", "l2", "l3"])
。
【讨论】:
以上是关于如何更改太空入侵者计划中的图像?的主要内容,如果未能解决你的问题,请参考以下文章