Pygame Player精灵错误:未定义名称“播放器”

时间:2017-11-18 17:33:23

标签: python class pygame game-development

我有两个文件: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

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

1 个答案:

答案 0 :(得分:1)

public class Car { [HiddenInput(DisplayValue = false)] public int CarID { get; set; } public string ModelName { get; set; } public int ManufacturerID { get; set; } public int Year { get; set; } public decimal Mpg { get; set; } } 中的问题是from test import * - 有循环导入有时会产生问题

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

<强> test.py

sprite.py

<强> sprites.py

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()