Here is a part of my code for a game:
current_ship = 'player'
def main():
global current_ship
run = True
FPS = 120
clock = pg.time.Clock()
level = 0
lives = 3
main_font = pg.font.SysFont('Algerian',30)
lost_font = pg.font.SysFont('Algerian', 80)
ship_speed = 3
alien_lazer_speed = 4
lazer_speed = 7
aliens = []
wave_length = 5
alien_speed = .5
if current_ship == 'player': # Ships
player = Player(900,800)
elif current_ship ==' player1':
player = Player_1(900,800)
lost = False
lost_count = 0
def redraw_window():
WIN.blit(BG,(0,0))
level_label = main_font.render(f"Level: {level}",1,(255,255,255))
WIN.blit(level_label,(WIDTH - level_label.get_width() - 20,10))
# Here to draw the player lives
if lives == 3:
WIN.blit(player_ship_image_resize,(0,0))
WIN.blit(player_ship_image_resize, (73,0))
WIN.blit(player_ship_image_resize, (146, 0))
if lives == 2:
WIN.blit(player_ship_image_resize,(0,0))
WIN.blit(player_ship_image_resize, (73,0))
if lives == 1:
WIN.blit(player_ship_image_resize, (0, 0))
for alien in aliens:
alien.draw(WIN)
player.draw(WIN)
if lost:
lost_label = lost_font.render("Game Over" ,1,(255,0,0))
WIN.blit(lost_label,(WIDTH/2 - lost_label.get_width()/2,350))
pg.display.update()
while run:
clock.tick(FPS)
if lives <= 0 or player.health <= 0: # ERROR RIGHT HERE
lost = True
lost_count += 1
if len(aliens) == 0:
level += 1
level_up.play()
wave_length += 5
for i in range(wave_length):
#Right here
alien = Alien(random.randrange(50,WIDTH-100),random.randrange(-2500,-100),random.choice(["red","yellow","gray"]))
aliens.append(alien)
for event in pg.event.get():
if event.type == pg.QUIT:
quit()
keys = pg.key.get_pressed()
if keys[pg.K_a] and player.x - ship_speed > 0:
player.x -= ship_speed
if keys[pg.K_d] and player.x + ship_speed + player.get_width() < WIDTH:
player.x += ship_speed
if keys[pg.K_w] and player.y - ship_speed > 0:
player.y -= ship_speed
if keys[pg.K_s] and player.y + ship_speed + player.get_height() < HEIGHT:
player.y += ship_speed
# player lazer
if keys[pg.K_SPACE]:
player.shoot()
pew_1.play()
for alien in aliens[:]:
alien.move(alien_speed)
alien.move_lazers(alien_lazer_speed,player)
if random.randrange(0,3*120) == 1:
alien.shoot()
if collide(alien,player):
player.health -= 20
explosion_small.play()
aliens.remove(alien)
elif alien.y + alien.get_height() > HEIGHT:
lives -= 1
aliens.remove(alien)
player.move_lazers(-lazer_speed,aliens)
redraw_window()
The error is in line 68: "if lives <= 0 or player.health <= 0:", but I have no idea why that becomes an issue. The varible is defined by an if statement, I don't know if that is the correct why to do it, but the varible player here isn't defined outside the function, so why do I got an UnboundLocalError? The error dissappears when I remove the if statement, but I want the if statement to select ships for my pygame menu. Does anyone know how to solve the bug or have an idea about some other way to select ships?