ImportError:无法导入名称块

时间:2020-04-02 07:26:50

标签: python python-3.x oop pygame importerror

我开始使用OOP在Pygame中制作俄罗斯方块,并将其他文件导入主程序。首先,一切正常,但是在我关闭所有内容之后,再次打开并运行它,这给了我一个错误:

ImportError: cannot import name block

我不知道为什么会这样,因为所有文件都放在一个文件夹中。 这是我的主要任务:

import pygame
from block import Block
from shape import Shape

block = Block(290,0)
shape = Shape(290,0)
pygame.init()

screen = pygame.display.set_mode((500,800))
pygame.display.set_caption('Tetris')

turning = False
running = True

color = 'green'

clock = pygame.time.Clock()

while running:
    clock.tick(5)
    screen.fill((0,0,0))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                block.Left()
                turning = True
            if event.key == pygame.K_RIGHT:
                block.Right()
                turning = True

    if not turning:
        block.yvel += 20

    block.draw(color, screen)

    turning = False

    pygame.display.update()

这是我要导入的文件:

import pygame
from shapes import Shape

class Block(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super(Block, self).__init__()
        self.xvel = x
        self.yvel = y

        self.orange = pygame.image.load(["orange.png"])
        self.green = pygame.image.load(["green.png"])
        self.blue = pygame.image.load(["blue.png"])
        self.red = pygame.image.load(["red.png"])
        self.pink = pygame.image.load(["pink.png"])
        self.cyan = pygame.image.load(["cyan.png"])
        self.yellow = pygame.image.load(["yellow.png"])

    def Left(self):
        self.xvel -= 20

    def Right(self):
        self.xvel += 20

    def draw(self, color, screen):
        if color == 'orange':
            self.image = self.orange
        if color == 'blue':
            self.image = self.blue
        if color == 'green':
            self.image = self.green
        if color == 'pink':
            self.image = self.pink
        if color == 'cyan':
            self.image = self.cyan
        if color == 'yellow':
            self.image = self.yellow
        if color == 'red':
            self.image = self.red

        screen.blit(self.image, (self.xvel, self.yvel))

第二个(你不必读这个。如果我解决了第一个问题,我肯定不能处理第二个):

import pygame
from block import Block

class Shape(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super(Shape, self).__init__()
        self.x = x
        self.y = y

    def shape1(self):
        self.shapes = [(x,y), (x+20,y), (x-20,y)]

    def shape2(self):
        self.shapes = [(x,y), (x,y+20), (x-20,y)]

    def shape3(self):
        self.shapes = [(x,y), (x,y+20), (x+20,y),(x-20,y)]

    def shape4(self):
        self.shapes = [(x,y), (x+20,y)]

    def shape5(self):
        self.shapes = [(x,y), (x,y+20), (x-20,y), (x-20, y-20)]

1 个答案:

答案 0 :(得分:0)

好吧,一件事就是您导入:

from shapes import Shape

在一个文件中,在另一个文件中

from shape import Shape

因此,您删除了:从形状中导入来自Block.py的形状