User Tools

Site Tools


bullet_game

This is an old revision of the document!


Bullet Game

Bullet Game is our near-end stage pygame 2d game framework example. We've already done at least 6 or 7 other games using pygame. So this will document the patterns we have learned.

We began by “just writing” a game, then the second part was refactoring the game. I wanted to make refactoring it's own project. What are the goals of this refactoring?

  • Refactoring
    • Encapsulation

The primary goal is encapsulation. So, we're going to break up the old main into several new classes.

Screen and Window

The first thing we always do is have a Screen class and a Window class. The Screen class defines things like WIDTH and HEIGHT, and the Window class holds the pygame screen and other pygame initialization.

Initially, this code would appear at the start of a main.py. Later we moved it into class Game's init. However, to keep things clean we made it into it's own class.

class Screen:


class Window:

def __init__

This calls pygame.init(). See main

full code

import pygame

class Window:
    def __init__(self):
        pygame.init()

    def setLogo(self, filename):
        self.logo = pygame.image.load(filename)
        pygame.display.set_icon(self.logo)
        return self.logo

    def setCaption(self, cap):
        pygame.display.set_caption(cap)

    def setSize(self, width, height):
        self.width = width
        self.height = height
        self.size = (width, height)
        self.screen = pygame.display.set_mode(self.size)
        return self.screen

    def setFont(self, filename, size):
        pygame.font.init()
        self.font = pygame.font.Font(filename, size)

        font_width, font_height = self.font.size("@")
        self.fontwidth = font_width
        self.fontheight = size

        return self.font
bullet_game.1725068826.txt.gz · Last modified: 2024/08/31 01:47 by appledog

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki