Reputation: 341
I recently have started to learn classes, I am pretty new to classes, so my question is, am I using it correctly and also what are the advantages of using a class because I'm not sure if I need them but I feel like without it my code will feel lengthy and messy, if you could show me an example of how you used classes, I would appreciate it, if you could include a complex and simple class example please I think that would help me understand,thank you! quick note about this code, this is based on my other code but this one is using classes instead.
import pygame
import sys
from pygame.locals import *
pygame.init()
display_w = 800
display_h = 600
window = pygame.display.set_mode((display_w, display_h), HWSURFACE | DOUBLEBUF | RESIZABLE)
pygame.display.set_icon(pygame.image.load("game_icon.png"))
pygame.display.set_caption("Work in progress")
clock = pygame.time.Clock()
background = pygame.image.load("background.png")
class Player(object):
"""The controllable player in game"""
def __init__(self, x, y, width, height, speed):
self.x = x
self.y = y
self.width = width
self.height = height
self.image = pygame.image.load("sprite_sheet.png")
self.speed = speed
def draw(self):
self.sprite = (self.image.subsurface(pygame.Rect(0, 100, 50, 50)))
window.blit(self.sprite, (self.x, self.y))
def movement(self):
self.keys = pygame.key.get_pressed()
if self.keys[pygame.K_LEFT]:
self.x -= self.speed
if self.keys[pygame.K_RIGHT]:
self.x += self.speed
if self.keys[pygame.K_UP]:
self.y -= self.speed
if self.keys[pygame.K_DOWN]:
self.y += self.speed
player = Player(400, 300, 50, 50, 5)
running = True
while running:
window.blit(background, (0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == VIDEORESIZE:
screen = pygame.display.set_mode((event.w, event.h), RESIZABLE)
player.draw()
player.movement()
clock.tick(60)
pygame.display.flip()
Upvotes: 0
Views: 452
Reputation: 2790
That seems a good start.
If you are working in pygame, you should like look at using Sprites and Sprite Groups. You would make your player a subclass of Sprite.
See here for the docs. It is a little more to learn how to use and you need to understand inheritance in classes, but it is worth the effort. I would start using it before you get going to far.
Also you should use pygames Rect
class instead of keeping separate x, y, height and width attributes. The Rect
class is very useful in a lot of ways and often simplifies the code. It also has built in collision routines. Also many pygame calls expect a Rect
argument. See here for the docs.
There are some examples of using Sprites in pygame here.
Upvotes: 1