Skip to content

Instantly share code, notes, and snippets.

@syegulalp
Created September 9, 2024 14:33
Show Gist options
  • Save syegulalp/ab5ccf257381344ea6c3f29bf36936bc to your computer and use it in GitHub Desktop.
Save syegulalp/ab5ccf257381344ea6c3f29bf36936bc to your computer and use it in GitHub Desktop.
Simple modal game demo
# Simple example of a game with multiple modes.
# THe only dependency is pygame-ce.
# This code is in the public domain.
# Use it as you see fit.
import random
import pygame
pygame.init()
screen = pygame.display.set_mode((720, 720))
clock = pygame.time.Clock()
font = pygame.font.Font(None, 48)
running = True
keystrokes = (
(pygame.K_a, "a"),
(pygame.K_s, "s"),
(pygame.K_d, "d"),
(pygame.K_f, "f"),
)
class Game:
def __init__(self):
self.mode = self.mode_boot
self.score = 0
self.timer = 0
self.key, self.letter = "", None
self.set_text("LetterMatcher: Press Space To Begin")
self.bg_color = "purple"
def set_text(self, text=None):
if text:
self.text = font.render(text, True, (10, 10, 10))
self.prompt = font.render(self.letter, True, (10, 10, 10))
self.score_text = font.render(f"Score: {self.score}", True, (10, 10, 10))
def draw(self):
screen.fill(self.bg_color)
screen.blit(self.text, (64, 64))
screen.blit(self.prompt, (64, 192))
screen.blit(self.score_text, (64, 256))
if self.timer:
pygame.draw.rect(
screen, "orange", pygame.Rect(64, 100, (self.timer * 4), 64)
)
def set_challenge(self):
self.key, self.letter = random.choice(keystrokes)
self.timer = 60
def start_game(self):
self.score = 0
self.set_challenge()
self.set_text("Press The Key That Matches")
self.mode = self.mode_play
def end_game(self, key=None):
self.mode = self.mode_game_over
self.set_text("Game Over. Press Space To Play Again")
if key:
self.prompt = font.render(
f"You pressed {pygame.key.name(key.key)}, not {pygame.key.name(self.key)}", True, (10, 10, 10))
# Game modes
def mode_boot(self, key):
self.bg_color = "purple"
if key and key.key == pygame.K_SPACE:
self.start_game()
def mode_play(self, key):
self.bg_color = "pink"
self.timer -= 1
if not self.timer:
self.end_game()
if key:
if key.key == self.key:
self.set_challenge()
self.score += 1
self.set_text()
else:
self.end_game(key)
def mode_game_over(self, key):
self.bg_color = "green"
if key and key.key == pygame.K_SPACE:
self.start_game()
game = Game()
while running:
key = None
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
key = event
game.mode(key)
game.draw()
pygame.display.flip()
clock.tick(60) # limits FPS to 60
pygame.quit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment