Skip to content

Instantly share code, notes, and snippets.

@tomowarkar
Last active February 25, 2022 09:38
Show Gist options
  • Save tomowarkar/623da8c941a8f8146fd5dc26c1d88524 to your computer and use it in GitHub Desktop.
Save tomowarkar/623da8c941a8f8146fd5dc26c1d88524 to your computer and use it in GitHub Desktop.
@dataclass
class Maze:
width = 12
height = 8
def maze_renderer(m: Maze, conf: GameConf):
px_size = min(conf.window_width//m.width, conf.window_height//m.height)
suf = pygame.Surface((px_size*m.width, px_size*m.height))
for x in range(0, px_size*m.width, px_size):
for y in range(0, px_size*m.height, px_size):
suf.fill((x % 256, y % 256, 100), (x, y, px_size, px_size))
return suf
if __name__ == "__main__":
conf = GameConf()
game = Game(conf)
m = Maze()
def draw():
game.screen.fill(conf.background_color)
surface = maze_renderer(m, conf)
rect = surface.get_rect(
center=(conf.window_width//2, conf.window_height//2))
game.screen.blit(surface, rect)
setattr(game, "draw", draw)
game.run()
import sys
import pygame
from dataclasses import dataclass
@dataclass
class GameConf:
window_width: int = 640
window_height: int = 480
caption: str = "game window"
fps: int = 60
font_size: int = 24
background_color: str = "gray"
debug: bool = True
@property
def window_size(self):
return (self.window_width, self.window_height)
class Game:
def __init__(self, conf: GameConf) -> None:
pygame.init()
self.screen = pygame.display.set_mode(conf.window_size)
pygame.display.set_caption(conf.caption)
self.font = pygame.font.Font(None, conf.font_size)
self.clock = pygame.time.Clock()
self.conf = conf
def handle_event(self) -> None:
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.running = False
def draw(self) -> None:
self.screen.fill(self.conf.background_color)
def debug(self) -> None:
text = self.font.render("FPS: %.02f" %
self.clock.get_fps(), False, "black")
self.screen.blit(text, (0, 0))
def run(self) -> None:
self.running = True
while self.running:
self.handle_event()
self.draw()
if self.conf.debug:
self.debug()
pygame.display.update()
self.clock.tick(self.conf.fps)
pygame.quit()
sys.exit()
if __name__ == "__main__":
conf = GameConf()
game = Game(conf)
game.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment