Skip to content

Commit

Permalink
rework toplevel for future event infra
Browse files Browse the repository at this point in the history
  • Loading branch information
pmp-p committed Dec 5, 2023
1 parent bf0c294 commit c13bee6
Show file tree
Hide file tree
Showing 9 changed files with 849 additions and 19 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@ jobs:
build:
runs-on: ubuntu-22.04
env:
SDK_VERSION: 3.1.50.1bi
SDK_VERSION: 3.1.51.0bi
SYS_PYTHON: /usr/bin/python3
PACKAGES: emsdk hpy _ctypes pygame
BUILD_STATIC: emsdk _ctypes hpy
STATIC: false
BUILDS: 3.11 3.12
CYTHON: Cython-3.0.5-py2.py3-none-any.whl
CYTHON: Cython-3.0.6-py2.py3-none-any.whl
LD_VENDOR: -sUSE_GLFW=3

steps:
Expand Down
10 changes: 10 additions & 0 deletions pygbag/support/cross/aio/repl.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# pygbag repl implement at the same time :
# - the python console in the style of browser javascript's one
# - the virtual gamepad
# - demo record/replay
# - event passthrough for pygame apps


HISTORY = []

from embed import set_ps1, set_ps2, prompt, readline
29 changes: 14 additions & 15 deletions pygbag/support/cross/aio/toplevel.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,12 @@
import types
import inspect

HISTORY = []

try:
import embed
except:
embed = False

if not __UPY__:
try:
from . import repl
except:
repl = None

import code

class AsyncInteractiveConsole(code.InteractiveConsole):
Expand Down Expand Up @@ -61,7 +59,6 @@ def parse_sync(shell, line, **env):
sys.ps2 = "--- "



def runsource(self, source, filename="<stdin>", symbol="single"):
if len(self.buffer) > 1:
symbol = "exec"
Expand Down Expand Up @@ -90,8 +87,8 @@ def runsource(self, source, filename="<stdin>", symbol="single"):

def runcode(self, code):

if embed:
embed.set_ps1()
if repl:
repl.set_ps1()
self.rv = undefined

bc = types.FunctionType(code, self.locals)
Expand Down Expand Up @@ -138,16 +135,16 @@ def prompt(self, prompt=None):
import platform
# that is the browser one
#platform.prompt(prompt or sys.ps1)
embed.prompt()
if repl:repl.prompt()

async def input_console(self, prompt=">>> "):
if len(self.buffer):
return self.buffer.pop(0)

# if program wants I/O do not empty buffers
if self.shell.is_interactive:
if not aio.cross.simulator:
maybe = embed.readline()
if repl and not aio.cross.simulator:
maybe = repl.readline()
elif aio.async_input:
maybe = await aio.async_input()
else:
Expand Down Expand Up @@ -180,8 +177,8 @@ async def interact_step(self, prompt=None):
if self.push(self.line):
if self.one_liner:
prompt = sys.ps2
if embed:
embed.set_ps2()
if repl:
repl.set_ps2()
print("Sorry, multi line input editing is not supported", file=sys.stderr)
self.one_liner = False
self.resetbuffer()
Expand Down Expand Up @@ -263,5 +260,7 @@ async def start_toplevel(cls, shell, console=True, ns="__main__"):

else:

# TODO upy event driven async repl

class AsyncInteractiveConsole:
...
74 changes: 74 additions & 0 deletions pygbag/support/pygbag_app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
this = __import__(__name__)

from pygbag_ui import Tui, TTY
import pygbag_ui as ui
from pygbag_ux import *

ux_dim(1280 // 2 , 720 // 2)


if 1:

import pygame
class vpad:
X = 0
Z = 1
Y = 2
evx = []
evy = []
evz = []
axis = [evx, evz, evy]

LZ = 0.5

@classmethod
def get_axis(self, n):
if len(self.axis[n]):
return self.axis[n].pop(0)
return 0.0

@classmethod
def emit(self, axis, value):
self.axis[axis].append(float(value))
ev = pygame.event.Event(pygame.JOYAXISMOTION)
pygame.event.post(ev)
return False




import sys
if sys.platform not in ('emscripten','wasi') or aio.cross.simulator:
sleep_delay = 0
else:
sleep_delay = 0.0155




def console():
import platform
try:
platform.window.pyconsole.hidden = False
platform.window.document.body.style.background = "#000000";
except:
...

import os
_, LINES = os.get_terminal_size()
CONSOLE = os.get_console_size()

# split the display
if sys.platform not in ('emscripten','wasi') or aio.cross.simulator:
LINES = LINES - CONSOLE

TTY.set_raw(1)
import select,os,platform

platform.shell.is_interactive = False
platform.shell.interactive(True)
aio.toplevel.handler.muted = False

ui.clear(LINES, CONSOLE, '>>> ')


118 changes: 118 additions & 0 deletions pygbag/support/pygbag_fsm.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
from transitions import Machine
from dataclasses import dataclass
import textwrap

index = {}


class State(object):
...


class Draft(object):
...


@dataclass()
class FSM(Machine):
states: tuple
initial: str

def __init__(self, *argv, **kw):
Machine.__init__(self, states=self.states, initial=self.initial)


# TODO move the wrap out of there.


def state_refs(*argv):
global index
#tw = textwrap.TextWrapper(width=78)
tw=None
states = []
maxchapters = len(argv)
for chapter, component in enumerate(argv):
source = component.script
block = source.strip().split("\n", 1)[0]
states.append(block)
lines = []
cmds = []
for i, line in enumerate(source.split("\n")):
if i:
if line:
if line[0] != ":":
# markdown eats space at § begin
# line = line.replace(' ','\u2002\u2002')
if tw:
lines.extend(tw.wrap(line))
else:
lines.append(line)
else:
cmds.append(line[1:])
else:
lines.append("")
while len(lines) and not lines[-1]:
lines.pop()
lines.append("")
lines.append("")
lines.pop(0)
index[block] = {
"heading": f"Chapter {chapter+1}/{maxchapters} : {block} ",
"body": "\n".join(lines),
"logic": cmds,
}

return tuple(states)


def build(pkg, **kw):
global story
steps = [] # INTRO, BORED, WANDERING, EXPLORATION, BOOTING, PLAY

for k, v in vars(pkg).items():
if v in [State, Draft]:
continue

if isinstance(v, type):
if issubclass(
v,
(
State,
Draft,
),
):
print(k, v)
steps.append(v)

class Story(FSM):
states: tuple = state_refs(*steps)
initial: str = states[0]
index = index

def setup(self, pkg, **kw):
global index
self.name = kw.get("name", pkg.__name__)

for state in self.states:
store = index[state]
store["choices"] = {}

for cmd in store["logic"]:
if cmd.find(":") > 0:
rel, tail = cmd.split(":")
if rel == "?":
continue
if rel.find("->") >= 0:
trigger, dest = map(str.strip, rel.split("->", 1))
if trigger == '-':
trigger = dest
else:
if not trigger:
trigger = dest
store["choices"][trigger] = tail

self.add_transition(trigger=trigger, source=state, dest=dest)
return self

story = Story()
return story.setup(pkg, **kw)
File renamed without changes.
Loading

0 comments on commit c13bee6

Please sign in to comment.