+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

Pygame NameError:赋值之前在封闭范围中引用了自由变量“丢失”

发布于2021-04-12 14:51     阅读(256)     评论(0)     点赞(17)     收藏(1)


0

1

2

3

4

我最近一直在通过Tech的Tim YouTube教程在Pygame中开发“太空侵略者”游戏,并在第111行遇到名称错误:

NameError:在封闭范围内赋值之前引用了自由变量'lost'。

链接到教程https://www.youtube.com/watch?v=Q-__8Xw9KTM&feature=youtu.be&t=1112

代码:

import pygame
import os
import time
import random
import math
import sys

WIDTH, HEIGHT = 750, 750
screen = pygame.display.set_mode((WIDTH,HEIGHT))
pygame.display.set_caption("Space Invaders")

#Game Variables 
pygame.font.init()
pygame.init()



#Ships
RED_SPACE_SHIP = pygame.image.load(os.path.join('assets','pixel_ship_red_small.png'))
GREEN_SPACE_SHIP = pygame.image.load(os.path.join('assets','pixel_ship_green_small.png'))
BLUE_SPACE_SHIP = pygame.image.load(os.path.join('assets','pixel_ship_blue_small.png'))
YELLOW_SPACE_SHIP = pygame.image.load(os.path.join('assets','pixel_ship_yellow.png'))

#Lasers
RED_LASER = pygame.image.load(os.path.join('assets','pixel_laser_red.png'))
BLUE_LASER = pygame.image.load(os.path.join('assets','pixel_laser_blue.png'))
YELLOW_LASER = pygame.image.load(os.path.join('assets','pixel_laser_yellow.png'))
GREEN_LASER = pygame.image.load(os.path.join('assets','pixel_laser_green.png'))

#Background
BG = pygame.transform.scale2x(pygame.image.load(os.path.join('assets','background-black.png')).convert_alpha())


class Ship:
    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):
        screen.blit(self.ship_img, (self.x, self.y))

    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 = YELLOW_SPACE_SHIP
        self.laser_img = YELLOW_LASER
        self.mask = pygame.mask.from_surface(self.ship_img)
        self.max_health = health
        
class Enemy(Ship):
    COLOUR_MAP = {
                 "red": (RED_SPACE_SHIP, RED_LASER),
                 "green": (GREEN_SPACE_SHIP, GREEN_LASER),
                 "blue": (BLUE_SPACE_SHIP, BLUE_LASER),
                 }
    
    def __init__(self, x, y, colour, health=100):
        super().__init__(x, y, health)
        self.ship_img, self.laser_img = self.COLOUR_MAP[colour]
        self.mask = pygame.mask.from_surface(self.ship_img)

    def move(self, vel):
        self.y += vel
        

        
def main():
    run = True
    FPS = 60
    level = 0
    lives = 5
    main_font = pygame.font.SysFont("comicsans", 50)
    lost_font = pygame.font.SysFont("comicsans", 60)

    enemies = []
    wave_length = 5
    enemy_vel = 1

    player_vel = 5

    player = Player(300, 650)

    clock = pygame.time.Clock()
    
    def redraw_window():
        screen.blit(BG, (0,0))

        lives_label = main_font.render(f'Lives: {lives}', 1, (255,255,255))
        level_label= main_font.render(f'Level: {level}', 1, (255,255,255))

        screen.blit(lives_label, (10,10))
        screen.blit(level_label, (WIDTH - level_label.get_width() - 10, 10))


        for enemy in enemies:
            enemy.draw(screen)

        player.draw(screen)

        if lost:
            lost_label = lost_font.render("You Lost!!", 1, (255,255,255))
            screen.blit(lost_label, (WIDTH/2 - lost_label.get_width()/2, 350))
            

        
        pygame.display.update()



    while True:
        clock.tick(FPS)
        redraw_window()

        if lives <= 0 or player.health <= 0:
            lost = True
            lost_count += 1

        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(["red", "blue", "green"]))
                enemies.append(enemy)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()


        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT] and player.x - player_vel > 0:
            player.x -= player_vel
        if keys[pygame.K_RIGHT] and player.x + player_vel + player.get_width() < WIDTH:
            player.x += player_vel
        if keys[pygame.K_UP] and player.y - player_vel > 0:
            player.y -= player_vel
        if keys[pygame.K_DOWN] and player.y + player_vel + player.get_height() < HEIGHT:
            player.y += player_vel

        for enemy in enemies:
            enemy.move(enemy_vel)
            if enemy.y + enemy.get_height() > HEIGHT:
                lives -= 1
                enemies.remove(enemy)
        
     

main()

解决方案


对于lostlost_count,您需要将它们标记为全局变量,因此该方法不会将它们视为局部变量:

在您的代码中,替换为:

def main():

有了这个:

lost = False
lost_count = 0
        
def main():

    # use global variables
    global lost
    global lost_count

0

1

2

3

4

5

6

7

8

9



所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接: https://www.pythonheidong.com/blog/article/936026/baa6ba0e69bf6ed97850/

来源: python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

17 0
收藏该文
已收藏

评论内容:(最多支持255个字符)