Adding Player Object to the RPG Game

We will add a player which will be controlled by us to the game. In the previous post, we created the structure of our game code primarily. If we come to the main point, we are going to type a Player class for the main character. In pygame, there is a sprite class that provides useful features like update, draw, etc. So basically, the Sprite class is the parent class for our player object and other game objects. 

Let's created Player class in file named player.py. The Player class inherits from the Sprite class:
import pygame

class Player(pygame.sprite.Sprite):
    def __init__(self, pos, dim, col):
        pygame.sprite.Sprite.__init__(self)

        self.image = pygame.Surface([w,h])
        self.image.fill(col)

        self.rect = self.image.get_rect()
        self.rect.center = (x,y)
pygame.sprite.Sprite.__init__(self), we are going to call constructor of inherited class which is Sprite. The image attribute is object's surface and it's actually view of object. The rect attribute is rectangle object that created from the image attribute. We can control position of the object via the rect attribute. 

The important stage is how to add this object to the game. Pygame provides a nice feature called sprite groups for this. Sprite group gives us to managment multiple objects from one point. This group is a container.
...

screen = pygame.display.set_mode((640, 480))

sprites_group = pygame.sprite.Group()

def main():
    ...
So, We are going to update Player sprite class like this:
import pygame

class Player(pygame.sprite.Sprite):
    def __init__(self, sprites_group, pos, dim, col):
        self.groups = sprites_group
        pygame.sprite.Sprite.__init__(self, self.groups)

        self.image = pygame.Surface([w,h])
        self.image.fill(col)

        self.rect = self.image.get_rect()
        self.rect.center = (x,y)
We are going to create our player character with Player class and draw it via sprites group:
import pygame
import random

from player import Player

...

sprites_group = pygame.sprite.Group()

player = Player(sprites_group, screen.get_rect().center, (25,25), (0,0,255))

def main():
    running = True
    # the game loop
    while running:
        ...
        
        screen.fill((255,255,255))
        sprites_group.draw(screen)
        
        # update
        pygame.display.flip()

if __name__ == "__main__":
    main()

pygame.quit()
The result of the our game is: 
Adding player object to the game


This tutorial's source code on the Github.

No comments:

Post a Comment