首页 > 解决方案 > 为什么我收到 NameError: 'Wolf' is not defined

问题描述

我只是在下面进行了编辑以简化并更新我的问题状态。

我制作了一个简单的敌人类,称为“狼”。在我将此文本提取到一个新文件之前,我的主文件运行没有错误。

如果我尝试只导入 WOLF:

from Enemy Import Wolf

我得到以下信息: ImportError: cannot import name 'Wolf' from 'Enemy'

以下是我所有的文件。

当我运行我的主程序时,游戏运行但当我关闭它时崩溃并给我一个错误。

敌人.py

import pygame
import random
import Colors

    
class Wolf(pygame.sprite.Sprite):    
        def __init__(self, color, width, height):
            super().__init__()
            self.image = pygame.Surface([width, height])
            self.image.fill(color)
            self.rect = self.image.get_rect()

Main_Game_File.py

import pygame
import random
import Colors
import Player
import Enemy
        
# Initialize Pygame
pygame.init()

# Set the height and width of the screen
screen_width  = 800
screen_height = 600
screen = pygame.display.set_mode([screen_width, screen_height])

#SPRITE LIST CREATIONS
wolf_list = pygame.sprite.Group()
poison_wolf_list = pygame.sprite.Group()
# This is a list of every sprite. 
# All blocks and the player block as well.
all_sprites_list = pygame.sprite.Group()
 
for i in range(50):
    # This represents a single block
    wolf = Wolf(Colors.GREEN, 20, 15)
    # Set a random location for the block
    wolf.rect.x = random.randrange(screen_width)
    wolf.rect.y = random.randrange(screen_height)
    # Add the block to the list of objects
    wolf_list.add(wolf)
    all_sprites_list.add(wolf)
    
for i in range(50):
    # This represents a single block
    wolf = Wolf(Colors.RED, 20, 15)
    # Set a random location for the block
    wolf.rect.x = random.randrange(screen_width)
    wolf.rect.y = random.randrange(screen_height)
    # Add the block to the list of objects
    poison_wolf_list.add(wolf)
    all_sprites_list.add(wolf)
    #Since this will repeat 50 times, you will create 50 red blocks
    #This adds all 50 blocks to the bad_block_list, and the all_sprites_list.
 
# Create a RED player block
player = Player.Player(100, 100)
all_sprites_list.add(player)
 
# Loop until the user clicks the close button.
done = False
 
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
 
score = 0
 
# -------- Main Program Loop -----------
while not done:
    for event in pygame.event.get(): 
        if event.type == pygame.QUIT: 
            done = True

        # Set the speed based on the key pressed
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_a:
                player.changespeed(-3, 0)
            elif event.key == pygame.K_d:
                player.changespeed(3, 0)
            elif event.key == pygame.K_w:
                player.changespeed(0, -3)
            elif event.key == pygame.K_s:
                player.changespeed(0, 3)
 
        # Reset speed when key goes up
        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_a:
                player.changespeed(3, 0)
            elif event.key == pygame.K_d:
                player.changespeed(-3, 0)
            elif event.key == pygame.K_w:
                player.changespeed(0, 3)
            elif event.key == pygame.K_s:
                player.changespeed(0, -3)

    # Clear the screen
    screen.fill(Colors.WHITE)
 
    # Game Logic
    all_sprites_list.update()

 
    # See if the player block has collided with anything.
    wolf_list = pygame.sprite.spritecollide(player, wolf_list, True)
    poison_wolf_list = pygame.sprite.spritecollide(player, poison_wolf_list, True)
    # Check the list of collisions.
    for block in wolf_list:
        score += 1
        print(score)
    for block in poison_wolf_list:
        score -= 1
        print(score) 
    # Draw all the spites
    all_sprites_list.draw(screen)
 
    # Go ahead and update the screen with what we've drawn.
    pygame.display.flip()
 
    # Limit to 60 frames per second
    clock.tick(60)
 
pygame.quit()

播放器.py

import pygame
import random
import Colors

class Player(pygame.sprite.Sprite):
    """ The class is the player-controlled sprite. """
 
    # -- Methods
    def __init__(self, x, y):
        """Constructor function"""
        # Call the parent's constructor
        super().__init__()
 
        # Set height, width
        self.image = pygame.Surface([15, 15])
        self.image.fill(Colors.BLUE)
 
        # Make our top-left corner the passed-in location.
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
 
        # -- Attributes
        # Set speed vector
        self.change_x = 0
        self.change_y = 0
 
    def changespeed(self, x, y):
        """ Change the speed of the player"""
        self.change_x += x
        self.change_y += y
 
    def update(self):
        """ Find a new position for the player"""
        self.rect.x += self.change_x
        self.rect.y += self.change_y

颜色

# Colors
BLACK = (  0,   0,   0)
WHITE = (255, 255, 255)
RED   = (255,   0,   0)
GREEN = (  0, 225,   0)
BLUE  = (  0,   0, 225)

标签: pythonpython-3.xclassmodule

解决方案


您只需在它前面加上模块导入名称。

import Enemy
        
# [...]

mr_wolf = Enemy.Wolf(Colors.GREEN, 20, 15)   # <-- HERE

或使用import *符号:

from Enemy import *                    # <-- HERE
        
# [...]

mr_wolf = Wolf(Colors.GREEN, 20, 15)   # (no change)

模块的导入方式改变了命名范围。

或者当然,您也只能 Wolf从以下位置导入Enemy

from Enemy import Wolf                 # <-- HERE
        
# [...]

mr_wolf = Wolf(Colors.GREEN, 20, 15)   # (no change)

编辑:示例文件:

Enemy.py~

import pygame

class Wolf(pygame.sprite.Sprite):
    def __init__(self, color, width, height):
        super().__init__()
        self.image = pygame.Surface([width, height])
        self.image.fill(color)
        self.rect = self.image.get_rect()

    def __str__( self ):
        return "Wolf at (%d,%d) size %dx%d" % ( self.rect.x, self.rect.y, self.rect.width, self.rect.height ) 

main.py~

import Enemy

YELLOW = ( 255, 255, 0 )

mr_wolf = Enemy.Wolf( YELLOW, 10, 10)

print( str( mr_wolf ) )

这使:

# python3 ./main.py
pygame 1.9.4.post1
Hello from the pygame community. https://www.pygame.org/contribute.html
Wolf at (0,0) size 10x10

推荐阅读