Skip to content

Commit

Permalink
Merge #316
Browse files Browse the repository at this point in the history
316: Move things, break loops r=pathunstrom a=astronouth7303

Grab a u-haul! 🚚 

Generally moving things and reducing imports to improve the import loop situation

* Break up "the machinery implementing a thing" and "a pile of things that use the thing"
* Prefer module imports to individual imports, so any unavoidable loops don't wreck everything.

Depends on #306 because I didn't feel like dealing with the merge conflict.

No docs changes because this doesn't touch anything publicly documented.

Co-authored-by: Jamie Bliss <jamie@ivyleav.es>
  • Loading branch information
bors[bot] and AstraLuma committed Jul 18, 2019
2 parents 027034e + 9932158 commit 865dc6f
Show file tree
Hide file tree
Showing 16 changed files with 273 additions and 250 deletions.
2 changes: 1 addition & 1 deletion ppb/assets.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import threading

import ppb.vfs as vfs
from ppb.systems import System
from ppb.systemslib import System

__all__ = 'Asset', 'AssetLoadingSystem',

Expand Down
2 changes: 1 addition & 1 deletion ppb/camera.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from typing import Sequence
from numbers import Number

from ppb import Vector
from ppb_vector import Vector
from ppb.sprites import BaseSprite
from ppb.flags import DoNotRender

Expand Down
12 changes: 5 additions & 7 deletions ppb/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,8 @@
from typing import Union

import ppb.events as events
from ppb.events import StartScene
from ppb.events import EventMixin
from ppb.events import Quit
from ppb.systems import PygameEventPoller
from ppb.eventlib import EventMixin
from ppb.systems import EventPoller
from ppb.systems import Renderer
from ppb.systems import Updater
from ppb.assets import AssetLoadingSystem
Expand All @@ -27,7 +25,7 @@
class GameEngine(EventMixin, LoggingMixin):

def __init__(self, first_scene: Type, *,
basic_systems=(Renderer, Updater, PygameEventPoller, AssetLoadingSystem),
basic_systems=(Renderer, Updater, EventPoller, AssetLoadingSystem),
systems=(), scene_kwargs=None, **kwargs):

super(GameEngine, self).__init__()
Expand Down Expand Up @@ -135,7 +133,7 @@ def publish(self):
for game_object in scene:
game_object.__event__(event, self.signal)

def on_start_scene(self, event: StartScene, signal: Callable[[Any], None]):
def on_start_scene(self, event: events.StartScene, signal: Callable[[Any], None]):
"""
Start a new scene. The current scene pauses.
"""
Expand All @@ -159,7 +157,7 @@ def on_replace_scene(self, event: events.ReplaceScene, signal):
self.stop_scene()
self.start_scene(event.new_scene, event.kwargs)

def on_quit(self, quit_event: Quit, signal: Callable[[Any], None]):
def on_quit(self, quit_event: events.Quit, signal: Callable[[Any], None]):
self.running = False

def pause_scene(self):
Expand Down
67 changes: 67 additions & 0 deletions ppb/eventlib.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
"""
The event machinery
"""

import logging
import re

__all__ = (
'EventMixin', 'BadEventHandlerException',
)

boundaries_finder = re.compile('(.)([A-Z][a-z]+)')
boundaries_finder_2 = re.compile('([a-z0-9])([A-Z])')


def camel_to_snake(txt):
s1 = boundaries_finder.sub(r'\1_\2', txt)
return boundaries_finder_2.sub(r'\1_\2', s1).lower()


class BadEventHandlerException(TypeError):

def __init__(self, instance, method, event):
object_type = type(instance)
event_type = type(event)
o_name = object_type.__name__
e_name = event_type.__name__
article = ['a', 'an'][int(e_name.lower()[0] in "aeiou")]

message = f"""
{o_name}.{method}() signature incorrect, it should accept {article} {e_name} object and a signal function.
{e_name} is a dataclass that represents an event. Its attributes
tell you about the event.
The signal function is a function you can call that accepts an event instance
as its only parameter. Call it to add an event to the queue. You don't have to
use it, but it is a mandatory argument provided by ppb.
It should look like this:
def {method}({e_name.lower()}_event: {e_name}, signal_function):
(Your code goes here.)
"""
super().__init__(message)


class EventMixin:
def __event__(self, bag, fire_event):
elog = logging.getLogger('game.events')

name = camel_to_snake(type(bag).__name__)
meth_name = 'on_' + name
meth = getattr(self, meth_name, None)
if callable(meth):
try:
elog.debug(f"Calling handler {meth} for {name}")
meth(bag, fire_event)
except TypeError as ex:
from inspect import signature
sig = signature(meth)
try:
sig.bind(bag, fire_event)
except TypeError:
raise BadEventHandlerException(self, meth_name, bag) from ex
else:
raise
63 changes: 3 additions & 60 deletions ppb/events.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""
A big pile of the events defined in PPB.
"""
from dataclasses import dataclass
import logging
import re
from typing import Any
from typing import Collection
from typing import Dict
Expand All @@ -11,7 +12,6 @@

__all__ = (
'StartScene',
'EventMixin',
'PreRender',
'Quit',
'Render',
Expand All @@ -24,63 +24,6 @@
'Update',
)

boundaries_finder = re.compile('(.)([A-Z][a-z]+)')
boundaries_finder_2 = re.compile('([a-z0-9])([A-Z])')

def camel_to_snake(txt):
s1 = boundaries_finder.sub(r'\1_\2', txt)
return boundaries_finder_2.sub(r'\1_\2', s1).lower()


class BadEventHandlerException(TypeError):

def __init__(self, instance, method, event):
object_type = type(instance)
event_type = type(event)
o_name = object_type.__name__
e_name = event_type.__name__
article = ['a', 'an'][int(e_name.lower()[0] in "aeiou")]

message = f"""
{o_name}.{method}() signature incorrect, it should accept {article} {e_name} object and a signal function.
{e_name} is a dataclass that represents an event. Its attributes
tell you about the event.
The signal function is a function you can call that accepts an event instance
as its only parameter. Call it to add an event to the queue. You don't have to
use it, but it is a mandatory argument provided by ppb.
It should look like this:
def {method}({e_name.lower()}_event: {e_name}, signal_function):
(Your code goes here.)
"""
super().__init__(message)


class EventMixin:
def __event__(self, bag, fire_event):
elog = logging.getLogger('game.events')

name = camel_to_snake(type(bag).__name__)
meth_name = 'on_' + name
meth = getattr(self, meth_name, None)
if callable(meth):
try:
elog.debug(f"Calling handler {meth} for {name}")
meth(bag, fire_event)
except TypeError as ex:
from inspect import signature
sig = signature(meth)
try:
sig.bind(bag, fire_event)
except TypeError:
raise BadEventHandlerException(self, meth_name, bag) from ex
else:
raise


# Remember to define scene at the end so the pargs version of __init__() still works

from ppb.scenes import BaseScene
Expand Down
4 changes: 2 additions & 2 deletions ppb/features/twophase.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
A system for two phase updates: Update, and Commit.
"""
from dataclasses import dataclass
from ppb.systems import System
from ppb.events import EventMixin
from ppb.systemslib import System
from ppb.eventlib import EventMixin

__all__ = 'Commit',

Expand Down
2 changes: 1 addition & 1 deletion ppb/scenes.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from typing import Type

from ppb.camera import Camera
from ppb.events import EventMixin
from ppb.eventlib import EventMixin


class GameObjectCollection(Collection):
Expand Down
2 changes: 1 addition & 1 deletion ppb/sprites.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

import ppb
from ppb import Vector
from ppb.events import EventMixin
from ppb.eventlib import EventMixin
from ppb.utils import FauxFloat

import ppb_vector
Expand Down
Loading

0 comments on commit 865dc6f

Please sign in to comment.