我无法弄清楚这一点,我还在学习python和pygame,所以 这里的代码。这段代码有两个类,看起来像Player()类与Block()有相同的代码,我想最小化代码,所以我不要重复这样的咒语,而这样做的方法就是类的实例, Player()是Block()的实例,怎么样?
class Block(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()
class Player(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
self.image = pygame.Surface([20, 15])
self.image.fill(BLUE)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.change_x = 0
self.change_y = 0
def changespeed(self, x, y):
self.change_x += x
self.change_y += y
def update(self):
self.rect.x += self.change_x
self.rect.y += self.change_y
在找到你们的答案后,代码就像这样
class Block(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()
class Player(Block):
def __init__(self, color, width, height, x, y):
Block.__init__(self, color, width, height)
self.rect.x = x
self.rect.y = y
self.change_x = 0
self.change_y = 0
def changespeed(self, x, y):
self.change_x += x
self.change_y += y
def update(self):
self.rect.x += self.change_x
self.rect.y += self.change_y
代码是真的吗?当我运行该程序时,它的工作原理
答案 0 :(得分:0)
就像来自pygame.sprite.Sprite
的玩家和阻止继承一样,您可以让玩家代替继承来阻止
class Player(Block):
然后,调用super().__init__()
使用Block的构造函数(反过来也将调用pygame.sprite.Sprite
的构造函数):
class Player(Block):
def __init__(self, x, y):
super().__init__()
然后在此之下,添加特定于Player的所有代码。
答案 1 :(得分:-1)
添加一个中间类:
class Middle(pygame.sprite.Sprite):
super().__init__()
self.image = pygame.Surface([20, 15])
self.image.fill(BLUE)
self.rect = self.image.get_rect()
然后类Block和类Player继承自Middle class