Professional Documents
Culture Documents
Show the proper way to organize a game using the a game class.
import pygame
import random
SCREEN_WIDTH = 700
SCREEN_HEIGHT = 500
class Block(pygame.sprite.Sprite):
""" This class represents a simple block the player collects. """
def __init__(self):
""" Constructor, create the image of the block. """
super().__init__()
self.image = pygame.Surface([20, 20])
self.image.fill(BLACK)
self.rect = self.image.get_rect()
def reset_pos(self):
""" Called when the block is 'collected' or falls off
the screen. """
self.rect.y = random.randrange(-300, -20)
self.rect.x = random.randrange(SCREEN_WIDTH)
def update(self):
""" Automatically called when we need to move the block. """
self.rect.y += 1
class Player(pygame.sprite.Sprite):
""" This class represents the player. """
def __init__(self):
super().__init__()
self.image = pygame.Surface([20, 20])
self.image.fill(RED)
self.rect = self.image.get_rect()
def update(self):
""" Update the player location. """
pos = pygame.mouse.get_pos()
self.rect.x = pos[0]
self.rect.y = pos[1]
class Game(object):
""" This class represents an instance of the game. If we need to
reset the game we'd just need to create a new instance of this
class. """
def __init__(self):
""" Constructor. Create all our attributes and initialize
the game. """
self.score = 0
self.game_over = False
block.rect.x = random.randrange(SCREEN_WIDTH)
block.rect.y = random.randrange(-300, SCREEN_HEIGHT)
self.block_list.add(block)
self.all_sprites_list.add(block)
def process_events(self):
""" Process all of the events. Return a "True" if we need
to close the window. """
return False
def run_logic(self):
"""
This method is run each time through the frame. It
updates positions and checks for collisions.
"""
if not self.game_over:
# Move all the sprites
self.all_sprites_list.update()
if len(self.block_list) == 0:
self.game_over = True
if self.game_over:
# font = pygame.font.Font("Serif", 25)
font = pygame.font.SysFont("serif", 25)
text = font.render("Game Over, click to restart", True, BLACK)
center_x = (SCREEN_WIDTH // 2) - (text.get_width() // 2)
center_y = (SCREEN_HEIGHT // 2) - (text.get_height() // 2)
screen.blit(text, [center_x, center_y])
if not self.game_over:
self.all_sprites_list.draw(screen)
pygame.display.flip()
def main():
""" Main program function. """
# Initialize Pygame and set up the window
pygame.init()
pygame.display.set_caption("My Game")
pygame.mouse.set_visible(False)