120 likes | 275 Views
Objects in Pygame. Lecture 07. Making an Object for Games. class Entity(): def __ init __ ( self ): pass. Entity. The most basic object to be drawn on screen We will use inheritance in the game to create player and enemy classes from it. Creating the Entity in Pygame.
E N D
Objects in Pygame Lecture 07
Making an Object for Games class Entity(): def__init__(self): pass
Entity The most basic object to be drawn on screen We will use inheritance in the game to create player and enemy classes from it.
Creating the Entity in Pygame The class should be defined before the pygame.init() class Entity(): def__init__(self, size, colour): self.rect = pygame.Rect(0,0,size,size) self.dx = 0 self.dy = 0 self.distance = 0
Draw method We will use the basic Pygame drawing function def draw(self, screen): self.draw.rect(screen, red, self.rect)
Actually Drawing The Entity object needs to be instantiated Then the draw method must be called.
Move method def move(self): self.rect.x += self.dx self.rect.y += self.dy
Actually Moving The move method must be called from within the main loop. dude.move()
Bouncing off walls Let’s do a little bounds checking def move(self): if (self.rect.x<0orself.rect.right> WIDTH): self.dx*= -1 if (self.rect.y<0orself.rect.bottom> HEIGHT): self.dy*= -1 self.rect.x += self.dx self.rect.y += self.dy
Changing the Colour The colour defaults to red but can be changed def__init__(self, size): self.rect = pygame.Rect(0,0,size,size) self.dx = 0 self.dy = 0 self.colour = red self.distance = 0