p5bg:bullet_game
Differences
This shows you the differences between two versions of the page.
| Both sides previous revisionPrevious revisionNext revision | Previous revision | ||
| p5bg:bullet_game [2024/08/31 01:52] – appledog | p5bg:bullet_game [2024/09/11 06:42] (current) – removed appledog | ||
|---|---|---|---|
| Line 1: | Line 1: | ||
| - | = 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" | ||
| - | |||
| - | * Refactoring | ||
| - | ** Encapsulation | ||
| - | ** Light Commentary (code commentary) ex. IN and OUT for functions. | ||
| - | |||
| - | 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]] | | ||
| - | | setLogo | this sets the little icon in the corner of the screen. It's the icon for the desktop, usually. Normally we don't care about this. | | ||
| - | | setCaption | This will set the title of the window. Usually the name of the program or game. | | ||
| - | | setFont | This will probably be moved to it's own Font class later. That way we can have multiple fonts if we want and it keeps the code a bit cleaner. | | ||
| - | |||
| - | ==== full code | ||
| - | < | ||
| - | import pygame | ||
| - | |||
| - | class Window: | ||
| - | def __init__(self): | ||
| - | pygame.init() | ||
| - | |||
| - | def setLogo(self, | ||
| - | self.logo = pygame.image.load(filename) | ||
| - | pygame.display.set_icon(self.logo) | ||
| - | return self.logo | ||
| - | |||
| - | def setCaption(self, | ||
| - | pygame.display.set_caption(cap) | ||
| - | |||
| - | def setSize(self, | ||
| - | self.width = width | ||
| - | self.height = height | ||
| - | self.size = (width, height) | ||
| - | self.screen = pygame.display.set_mode(self.size) | ||
| - | return self.screen | ||
| - | |||
| - | def setFont(self, | ||
| - | pygame.font.init() | ||
| - | self.font = pygame.font.Font(filename, | ||
| - | |||
| - | font_width, font_height = self.font.size(" | ||
| - | self.fontwidth = font_width | ||
| - | self.fontheight = size | ||
| - | |||
| - | return self.font</ | ||
p5bg/bullet_game.1725069178.txt.gz · Last modified: 2024/08/31 01:52 by appledog
