2️⃣

4.2 - Object Class

4.2 Object Class

So far, we’ve been working with rectangles individually, but we can encapsulate them in a class with attributes such as size, speed, and image, and methods such as draw and move. Because our example for this chapter, the tank game, requires us to check collisions, we can also have a check_collision method in our class. Luckily for us, we’ve been doing most of these things in previous chapters, so we can quickly write up a class.
class Game_obj: def __init__(self, picture: str, **kwargs) -> None: """ A basic game object class. It handles collisions, the basic drawing method, the move and moveto methods, and the check_out_of_screen method. Arguments: picture:str - the location of the picture that will be displayed on the screen for this object Valid keyword arguments: "size":tuple(x,y) - a specific size that you want to have the object be. The picture will be scaled to that size and the hitbox will be updated accordingly. "position":tuple(x,y) - the tuple at which the top left of the object should be positioned at "speed":tuple(x,y) - the tuple that represents the object's speed. """ self.name = "" # used with the __str__ method for debugging # self.image will be a pygame.Surface class # if a given size is provided, then scale the picture to that size # else, keep the image as it is self.image = pygame.image.load(picture) self.image = ( pygame.transform.scale( self.image, (kwargs["size"][0], kwargs["size"][1]) ) if "size" in kwargs else self.image ) self.rect = ( self.image.get_rect() ) # self.rect will be of pygame.Rect class self.size = self.rect.size # will be a tuple of (sizex, sizey) if "position" in kwargs: self.moveto(kwargs["position"]) # if a speed was given, initialize self.speed to those speeds # else, assume that it is not moving (x and y speeds are 0) self.speed = ( {"x": kwargs["speed"][0], "y": kwargs["speed"][1]} if "speed" in kwargs else {"x": 0, "y": 0} ) def check_collision(self, other: object) -> bool: if not isinstance(other, Game_obj): raise TypeError( "Invalid type; need a game_obj or a child class of game_obj" ) # the rect class's colliderect method returns 1 if there is # a collision and 0 if there isn't a collision return self.rect.colliderect(other.rect) == 1 def draw(self, screen: pygame.Surface, color: tuple) -> None: pygame.draw.rect(screen, color, self.rect, 0) screen.blit(self.image, self.rect) def move(self) -> None: """ Moves the object according to it's current speed. """ self.rect = self.rect.move(self.speed["x"], self.speed["y"]) # self.draw(screen, color) def set_speed(self, new_speed: tuple) -> None: """ Sets the object's speed to the provided tuple Arguments: new_speed (tuple(x,y)) - a tuple containing the desired speed for the object to have. """ self.speed["x"], self.speed["y"] = new_speed[0], new_speed[1] def moveto(self, position: tuple) -> None: """ A helper function that moves the rectangle to the desired position. Arguments: position (tuple) - the x and y coordinates of where you want the rectangle's top left to be moved to. """ self.rect = self.rect.move( position[0] - self.rect.topleft[0], position[1] - self.rect.topleft[1], ) def check_out_of_screen(self, screen_size: tuple) -> bool: """ Checks whether or not the object is completely outside of the screen. Returns True or False accordingly. Arguments: screen_size (tuple) - the size of the screen (x,y) """ if ( self.rect.bottom > screen_size[1] or self.rect.top < 0 or self.rect.left < 0 or self.rect.right > screen_size[0] ): return True return False def __str__(self): return ( f"{self.name} object located at the position {self.rect.topleft}" )
You’ll notice that we utilize the pygame.Rect class a lot and thus have it saved as the attribute self.rect. This is because pygame’s Rect class provides many useful methods, such as size(), which retrieves the size, and colliderect() which checks whether the rectangle collided with another rectangle.
 
⚖️
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.