Pygame Player Sprite错误:名称'Player'未定义[重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

我有两个文件:sprites.pytest.py。在sprites.py,我做了一个Player课程。我使用main将所有内容导入test.py文件(from player import *)。

sprites.py

import pygame
from test import *

class Player(pygame.sprite.Sprite):
    # ...
    pass

test.py

import pygame
from sprites import *

# ...

all_sprites = pygame.sprite.Group()
player = Player()                       #  <-- line 28, NameError
all_sprites.add(player)

我收到此错误:

Traceback (most recent call last):
  File "test.py", line 2, in <module>
    from sprites import *
  File "C:\Users\Adam\Desktop\PYthon Test\sprites.py", line 2, in <module>
    from test import *
  File "C:\Users\Adam\Desktop\PYthon Test\test.py", line 28, in <module>
    player = Player()
NameError: name 'Player' is not defined

我已经确保我拼写正确的一切。这个错误可能来自哪里?

python class pygame game-development
1个回答
1
投票

问题是在from test import *sprite.py - 有循环导入有时会产生问题

我的版本有一些其他修改。

test.朋友

import pygame
from sprites import *

# --- constants --- (UPPER_CASE_NAMES)

WHITE = (255,255,255)
BLACK = (0,0,0)

WIDTH = 900
HEIGHT = 450

# --- main ---

# - init -

pygame.init()
#pygame.mixer.init() # pygame.init() should init mixer too
screen = pygame.display.set_mode((WIDTH,HEIGHT))
pygame.display.set_caption('game')

# - objects -

all_sprites = pygame.sprite.Group()
player = Player()
all_sprites.add(player)

# - mainloop -

clock = pygame.time.Clock()
running = True

while running:

    # - events -

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                running = False
        player.handle_event(event)

    # - updates - 

    all_sprites.update()

    # - draw -

    screen.fill(WHITE)
    all_sprites.draw(screen)
    pygame.display.flip()

    # - FPS -

    clock.tick(30)

# - end -

pygame.quit()

sprites.朋友

import pygame

class Player(pygame.sprite.Sprite):

    def __init__(self):
        super().__init__()

        # use Surface to create image
        self.image = pygame.Surface([40,40])
        #self.image.fill((0,0,0)) # surface is black as default so it don't have to be fill with black
        # `group.draw()` needs `self.image` and `self.rect`
        self.rect = self.image.get_rect(x=450, y=225)

        self.velocity = 9
        self.gravitiy = 3
        self.speedy = 0
        self.speedx = 0
        self.on_ground = True

    def handle_event(self, event):
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                self.speedx = -5
            elif event.key == pygame.K_RIGHT:
                self.speedx = 5
        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT:
                self.speedx = 0
            elif event.key == pygame.K_RIGHT:
                self.speedx = 0

    def update(self):
        self.rect.x += self.speedx
© www.soinside.com 2019 - 2024. All rights reserved.