0

This code has two classes, it looks like the class Player() have the same code as Block(), I want to minimalize the code, so I don't repeat the spell-like that, and the way to do that is the instances the class, the Player() is an instance of the Block(), how?

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

After looking for an answer from you guys, the code just like this:

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 

Is that code true? When I'm running the program, it works.

pppery
  • 3,731
  • 22
  • 33
  • 46

2 Answers2

0

Just like Player and Block inherit from pygame.sprite.Sprite, you can have Player instead inherit from Block:

class Player(Block):

Then, call super().__init__() to use Block's constructor (which in turn will also call pygame.sprite.Sprite's constructor):

class Player(Block):
    def __init__(self, x, y):
        super().__init__()

Then under that, add all the code specific to Player.

Bancho
  • 116
  • 4
  • Im just thinking, when i change the parameters from Player(x, y) to Player(color, width, height, x, y) and then in code `class Player(Block):` after that im added `Block.__init__(self, color, width, height)` and it is works, is that call instance right ? – Rifqi Muttaqin May 28 '18 at 02:55
-1

add a middle Class:

class Middle(pygame.sprite.Sprite):

    super().__init__()

    self.image = pygame.Surface([20, 15])
    self.image.fill(BLUE)

    self.rect = self.image.get_rect()

then class Block and class Player inherit from the Middle class

Xiaoyu Xu
  • 858
  • 6
  • 5