Friday, February 10, 2023

Before and After

 I have been asked about removing things in pygame. One uses the built-in Sprite class.

Below, from an geeksforgeeks example:

https://www.geeksforgeeks.org/pygame-creating-sprites/


mport pygame
import random

# GLOBAL VARIABLES ARE CAPITALIZED
COLOR = (255, 100, 98)
SURFACE_COLOR = (167, 255, 100)
WIDTH = 500
HEIGHT = 500

# Creation of Object class. Where object color is the same as surface color,
# the pixels will be transparent
class Sprite(pygame.sprite.Sprite):
def __init__(self, color, height, width):
super().__init__()

self.image = pygame.Surface([width, height])
self.image.fill(SURFACE_COLOR)
self.image.set_colorkey(COLOR)

pygame.draw.rect(self.image, color, pygame.Rect(0, 0, width, height))

self.rect = self.image.get_rect()

#Starting an actual game. It is a good idea to call quit on pygame before exit on the OS.
pygame.init()

RED = (255, 0, 0)

size = (WIDTH, HEIGHT)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Creating Sprite")

all_sprites_list = pygame.sprite.Group()

object_ = Sprite(RED, 20, 30)
object_.rect.x = 200
object_.rect.y = 300

all_sprites_list.add(object_)

exit = True
clock = pygame.time.Clock()

#Removing an individual sprite from its sprite group removes it from the game.
while exit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
all_sprites_list.remove(object_)

all_sprites_list.update()
screen.fill(SURFACE_COLOR)
all_sprites_list.draw(screen)
pygame.display.flip()
clock.tick(60)

pygame.quit()
Before clicking any keys:

                                                                      

After clicking the Left Key:

                                                                                

                                                          *     *     *

Pygame is decidedly OOP, and works with classes. Game objects are class instances.

Below, two examples of objects made to disappear on terms defined by their respective

class constructors. With the explicitly named 'kill' funcrtion. Remove is used for removal

from one group; kill for removal from all groups.


The first, on condition that the rectangle reaches the bottom of the window. The second,

on a timer.


No comments: