Python:显示俄罗斯方块游戏的形状

0 投票
2 回答
1101 浏览
提问于 2025-04-17 11:01

我正在尝试写一段代码,让一个俄罗斯方块的形状在一个棋盘上显示出来。但是我一直遇到一个错误,不知道该怎么解决:

类型错误:未绑定的方法 can_move() 必须用 O_shape 实例作为第一个参数(而我却用的是 Board 实例)

这是我的代码:

class Board():

    def __init__(self, win, width, height):
        self.width = width
        self.height = height

        # create a canvas to draw the tetris shapes on
        self.canvas = CanvasFrame(win, self.width * Block.BLOCK_SIZE + Block.OUTLINE_WIDTH,
                                        self.height * Block.BLOCK_SIZE + Block.OUTLINE_WIDTH)
        self.canvas.setBackground('light gray')

        # create an empty dictionary
        # currently we have no shapes on the board
        self.grid = {}

    def draw_shape(self, shape):
        ''' Parameters: shape - type: Shape
            Return value: type: bool

            draws the shape on the board if there is space for it
            and returns True, otherwise it returns False
        '''
        if shape.can_move(self, 0, 0):
            shape.draw(self.canvas)
            return True
        return False

class Tetris():

    SHAPES = [I_shape, J_shape, L_shape, O_shape, S_shape, T_shape, Z_shape]
    DIRECTION = {'Left':(-1, 0), 'Right':(1, 0), 'Down':(0, 1)}
    BOARD_WIDTH = 10
    BOARD_HEIGHT = 20

    def __init__(self, win):
        self.board = Board(win, self.BOARD_WIDTH, self.BOARD_HEIGHT)
        self.win = win
        self.delay = 1000 #ms

        # sets up the keyboard events
        # when a key is called the method key_pressed will be called
        self.win.bind_all('<Key>', self.key_pressed)

        # set the current shape to a random new shape
        self.current_shape = self.create_new_shape()

        # Draw the current_shape oan the board 
        self.board.draw_shape(self.current_shape)


    def create_new_shape(self):
        ''' Return value: type: Shape

            Create a random new shape that is centered
             at y = 0 and x = int(self.BOARD_WIDTH/2)
            return the shape
        '''

        # YOUR CODE HERE
        y = 0
        x = int(self.BOARD_WIDTH/2)
        the_shape = random.choice(self.SHAPES)
        return the_shape

2 个回答

1

你忘记创建你的形状类的实例了。

SHAPES = [I_shape(), J_shape(), L_shape(), O_shape(), S_shape(), T_shape(), Z_shape()]

不过你应该只需要一个 Shape 类,通过传入参数来生成不同的形状。

3

你没有贴出相关方法的代码(can_move())。
另外,错误信息已经很清楚了,它期待一个类型为 O_shape 的参数,但你却调用这个方法时传了一个 Board

def draw_shape(self, shape):
''' Parameters: shape - type: Shape
    Return value: type: bool

    draws the shape on the board if there is space for it
    and returns True, otherwise it returns False
'''
  if shape.can_move(self, 0, 0): # <-- you probably meant to call shape.can_move(0,0)
    shape.draw(self.canvas)
    return True
  return False

和类绑定的方法,实例会隐式地作为第一个参数传入。

撰写回答