Difference between revisions of "Using classes"

From TRCCompSci - AQA Computer Science
Jump to: navigation, search
(Created page with "==Sprite Classes== We can create a new class for a player by creating a sub-class of Sprite. We will then inherit all of the functions of the sprite class. We have also create...")
 
Line 17: Line 17:
 
</syntaxhighlight>
 
</syntaxhighlight>
  
We will also need to have an update method which can be run to update the sprite during the game
+
We will also need to create an instance of the class:
 +
 
 +
<syntaxhighlight lang=python>
 +
pos = [0,0]
 +
h = HeroSprite
 +
h.__init__(h, pos)
 +
</syntaxhighlight>

Revision as of 15:38, 12 March 2018

Sprite Classes

We can create a new class for a player by creating a sub-class of Sprite. We will then inherit all of the functions of the sprite class. We have also created an init method which must be passed the inital_position of the sprite.

class HeroSprite(pygame.sprite.Sprite):
    image = None

    def __init__(self, initial_position):
        pygame.sprite.Sprite.__init__(self) # run the init for the base class
        if HeroSprite.image is None:
            HeroSprite.image = pygame.image.load("hero.png") # load image for sprite
        self.image = HeroSprite.image # set image for the sprite
        self.rect = self.image.get_rect() # set rectangle for sprite
        self.rect.topleft = initial_position # set position to value passed into method
        self.going_down = True # Start going downwards
        self.next_update_time = 0 # update() hasn’t been called yet.

We will also need to create an instance of the class:

pos = [0,0]
h = HeroSprite
h.__init__(h, pos)