switching

This commit is contained in:
James Turk 2024-04-22 01:35:14 -05:00
parent 89646260c0
commit 5eb52fd0cf
3 changed files with 39 additions and 11 deletions

View File

@ -5,6 +5,6 @@ c = Circle()
g = Group().pos(400, 300)
for r in range(20, 50, 5):
Circle(g).radius(r).color(*Color.random()).z_index(-r)
Circle(g).radius(r).color(Color.random()).z_index(-r)
for r in range(60, 150, 10):
Circle(g).radius(r).color(*Color.random()).z_index(-r)
Circle(g).radius(r).color(Color.random()).z_index(-r)

View File

@ -1,8 +1,5 @@
import sys
import time
import copy
import random
import math
from pathlib import Path
import pygame
import importlib
import typer
@ -11,11 +8,17 @@ from .world import world
FPS = 60
MS_PER_FRAME = 1000 / 60
def main(modname: str):
pygame.init()
world.init()
pygame.display.set_caption("Doodles")
def get_examples():
module_path = Path(__file__).parent / "examples"
submodules = [
file.stem for file in module_path.glob("*.py") if file.name != "__init__.py"
]
return submodules
def load_module(modname):
pygame.display.set_caption("doodles: " + modname)
world.clear()
try:
# try fully-qualified first
mod = importlib.import_module(modname)
@ -24,7 +27,22 @@ def main(modname: str):
try:
mod = importlib.import_module("doodles.examples." + modname)
except ImportError:
raise ImportError(f"Tried to import {modname} and doodles.examples.{modname}")
raise ImportError(
f"Tried to import {modname} and doodles.examples.{modname}"
)
return mod
def main(modname: str = None):
pygame.init()
world.init()
examples = get_examples()
ex_index = 0
if modname:
load_module(modname)
else:
load_module(examples[ex_index])
elapsed = last_update = 0
@ -33,6 +51,13 @@ def main(modname: str):
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
ex_index = (ex_index + 1) % len(examples)
load_module(examples[ex_index])
elif event.key == pygame.K_LEFT:
ex_index = (ex_index - 1) % len(examples)
load_module(examples[ex_index])
elapsed = pygame.time.get_ticks() - last_update
while elapsed > MS_PER_FRAME:
elapsed -= MS_PER_FRAME

View File

@ -54,6 +54,9 @@ class World:
raise ValueError("Can't initialize world twice!")
self.screen = pygame.display.set_mode((world.WIDTH, world.HEIGHT))
def clear(self):
self._drawables = []
def add(self, drawable):
self._drawables.append(drawable)