A complete engine for a pretend game. It imports nothing of Comms Array's: it speaks the link over stdin and stdout, as any program can. See Write an engine.
engine.json
{
"id": "hello_engine", "game": "hello_game", "engine_api": 2, "version": "1.0.0",
"name": "Hello Engine", "author": "Ada Lovelace",
"processes": ["HelloGame.exe"],
"run": {"program": "run.cmd", "args": []},
"consent": {
"terms_version": "1",
"notice": "An example engine: it reads nothing; it counts.",
"reads": ["Nothing: it makes up a number"],
"never": ["Any file or program on your PC"]
},
"show_labels": {"count": "Count"},
"input_rules": {"automation": "not_allowed", "text": "It takes no key presses."}
}
engine.py
"""A telemetry engine as its own program (docs/engine-api.md, "Program engines"; docs/write-an-engine.md).
It imports nothing from Comms Array: it only speaks the engine link, a WebSocket with JSON messages. Any language
works the same way; this one is Python with aiohttp. Comms Array starts it with:
CA_ENGINE_URL ws://127.0.0.1:<port>/engine/v1 connect here
CA_ENGINE_TOKEN <token> send it as "Authorization: Bearer <token>"
CA_ENGINE_DIR a folder for its own data (kept across updates)
CA_ENGINE_PACKAGE the installed package's folder (also the working directory; replaced on an update)
It has no game: it pretends one is running, counts up, and answers requests. Exit when the socket closes.
run.cmd starts it with the Python launcher for trying it locally; to publish on the hub, build it into an .exe
(PyInstaller or similar) and name that in engine.json's run.program.
"""
import asyncio
import json
import os
import sys
import time
from pathlib import Path
import aiohttp
PACKAGE = Path(os.environ.get("CA_ENGINE_PACKAGE") or Path(__file__).parent)
MANIFEST = json.loads((PACKAGE / "engine.json").read_text(encoding="utf-8"))
def info() -> dict:
"""Who it is (the hello's info). Ids must match engine.json; engine_api is the link version it speaks."""
return {
"id": MANIFEST["id"], "engine_api": MANIFEST["engine_api"], "name": MANIFEST["name"],
"version": MANIFEST["version"],
"glossary": {"player": "player", "vehicle": "vehicle"},
"metrics": {"count": {"label": "Count", "group": "Hello", "type": "number"}},
"layouts": {"Phone": {"pages": []}, "Tablet": {"pages": []}},
"sharing": ["count"],
"sharing_labels": {"count": "How far it has counted"},
# which switch each field of the share view needs; anything not declared never leaves the PC
"share_fields": {"player": "always", "player.name": "always", "show": "always", "show.count": "count"},
}
async def main() -> int:
url, token = os.environ.get("CA_ENGINE_URL"), os.environ.get("CA_ENGINE_TOKEN")
if not (url and token):
print("Comms Array starts this engine.", file=sys.stderr)
return 2
data = Path(os.environ.get("CA_ENGINE_DIR") or ".")
data.mkdir(parents=True, exist_ok=True)
(data / "started.json").write_text(json.dumps({
"cwd": os.getcwd(), "dir": os.environ.get("CA_ENGINE_DIR"), "package": os.environ.get("CA_ENGINE_PACKAGE"),
"version": MANIFEST["version"]}), encoding="utf-8")
sharing: dict = {}
async with aiohttp.ClientSession() as http, http.ws_connect(
url, headers={"Authorization": "Bearer " + token}, heartbeat=20) as ws:
async def send(msg):
await ws.send_str(json.dumps(msg))
async def frames():
n = 0
while True:
n += 1
share = {"game": "live", "player": {"name": "Ada Lovelace"},
"show": {"count": str(n), "lines": [["count"]]},
"secret": "an undeclared field: the core never lets it out"}
await send({"t": "frame", "state": {"count": n}, "at": time.time(), "events": [],
"views": {"share": share, "pad": {"metrics": {"count": {"v": n}}},
"identity": {"key": "ada", "name": "Ada Lovelace"}}})
await asyncio.sleep(0.2)
await send({"t": "hello", "info": info()})
await send({"t": "status", "status": "live"})
ticker = asyncio.create_task(frames())
try:
async for m in ws:
if m.type != aiohttp.WSMsgType.TEXT:
continue
msg = json.loads(m.data)
if msg.get("t") == "configure":
sharing = msg.get("sharing") or {}
elif msg.get("t") == "req":
op = msg.get("op")
body = ({"status": "ok", "sharing": sharing, "version": MANIFEST["version"]} if op == "hello"
else {"status": "bad_request", "message": f"unknown op {op!r}"})
await send({"t": "res", "id": msg.get("id"), "body": body})
finally:
ticker.cancel()
return 0
if __name__ == "__main__":
try:
sys.exit(asyncio.run(main()))
except (aiohttp.ClientError, ConnectionError):
sys.exit(0)
run.cmd
@echo off
rem Starts the example engine with the Python launcher. A real engine ships its own program (an .exe).
py -3 "%~dp0engine.py" %*
From the Comms Array source, commsarray-agent d615c4d.