Menu
Sign inDownload

Example: Hello

The bones of an add-on, file by file.

The complete example add-on (it's tested with every Comms Array build). It adds a tap-counter widget to the pad and counts your deaths in the game. Zip these files (manifest at the top) and install the zip from the Add-ons tab, as Make an add-on describes.

manifest.json

{"name": "hello", "package": "ca_hello", "version": "2.2.0", "title": "Hello (example)",
 "description": "A tap counter for the pad that also counts your deaths. A starting point for your own add-on.",
 "author": "you", "api": 1, "api_version": "1.4", "permissions": ["pad.widgets", "events.game"],
 "widgets": ["hello_counter", "hello_board"], "pad_js": "pad_hello.js",
 "pages": [{"title": "Counter", "desc": "The tap counter and the tap board, with a heading", "cols": 24,
            "widgets": [{"type": "label", "text": "Tap to count", "size": "m", "x": 0, "y": 0, "w": 12, "h": 1},
                        {"type": "hello_counter", "label": "Taps", "x": 0, "y": 1, "w": 4, "h": 2},
                        {"type": "hello_board", "x": 4, "y": 1, "w": 8, "h": 8}]}]}

ca_hello/__init__.py

"""Example Comms Array add-on: a pad button that counts taps, plus a death counter from game events.

It runs in its own process. `api` is all it gets from Comms Array, and only what the user allowed in manifest.json's
"permissions" (here: pad.widgets for the button, events.game for the deaths).
"""


class Hello:
    def __init__(self, api):
        self.api = api
        self.taps = 0
        self.deaths = 0

    async def handle_pad(self, device: dict, body: dict):
        """Your pad widget's POST /api/pad/mod/hello. Return (json, http status)."""
        if body.get("op") == "tap":
            self.taps += 1
            self.api.set_status({"taps": self.taps, "deaths": self.deaths})   # your pad frames read it as CA.pad.status
        return {"taps": self.taps}, 200

    def on_event(self, ev: dict):                      # every game event (needs events.game)
        if ev["type"] == "player.dead":
            self.deaths += 1
            self.api.set_status({"taps": self.taps, "deaths": self.deaths})   # the board's Deaths tab reads it


def create(api):
    return Hello(api)

ca_hello/pad_hello.js

// The example's pad widgets. Each one runs in its own sandboxed frame on the pad (see docs/addon-api.md): it draws, and
// talks to this add-on on the PC with CA.call. It can't reach the pad page, the network or anything stored on the device.

// "hello_counter": a tile you tap. The pad's own classes ("w b", "sub") make it look like the pad's buttons, and on a
// button pack's plate it takes the pack's colours with no code.
CA.widget("hello_counter", {
  add: { label: "Tap counter", desc: "Example add-on", size: [4, 2], props: () => ({ label: "Taps" }) },
  settings: [{ key: "label", type: "text", label: "Label", max: 40 }],
  tile(root, w, { editing }) {
    root.innerHTML = `<div class="w b"><span>${CA.esc(w.label)}</span><span class="sub">0</span></div>`;
    if (editing) return;
    const tile = root.firstChild;
    tile.onclick = async () => {
      const r = await CA.call({ op: "tap" });          // POSTs to this add-on on the PC
      tile.querySelector(".sub").textContent = r.taps ?? "?";
    };
  },
});

// "hello_board" (add-on API 1.4): a small screen built from the pack's parts, by class name: tabs, a screen, a
// segmented toggle, the table and a button with a lamp. In "the pack's look" (the default, CA.look === "pack") they
// are drawn in the layout's button pack; the player can switch this widget to its own look, which is the CSS below.
const OWN_LOOK = `
  body.ca-look-own .pk-tab.on { border-bottom-color: #f5a524; }
  body.ca-look-own .pk-screen { color: #f5a524; border-color: #6b4a12; }
  body.ca-look-own .pk-toggle > button.on { background: #3a2a0c; color: #f5a524; }
  body.ca-look-own .pk-btn { border-color: #6b4a12; }`;
CA.widget("hello_board", {
  add: { label: "Tap board", desc: "Example: tabs, a toggle, the table, a lamp button", size: [8, 8] },
  tile(root, w, { editing }) {
    const style = document.createElement("style");
    style.textContent = OWN_LOOK;
    document.head.appendChild(style);
    root.innerHTML = `<div class="w" style="display:flex;flex-direction:column;gap:6px;padding:6px">
      <div class="pk-tabs"><button class="pk-tab on" data-tab="taps">Taps</button><button class="pk-tab" data-tab="deaths">Deaths</button></div>
      <div style="display:flex;gap:6px;align-items:center">
        <div class="pk-screen" style="flex:1">0 taps</div>
        <div class="pk-toggle"><button class="on" data-order="new">New</button><button data-order="old">Old</button></div>
      </div>
      <div class="list" style="flex:1;min-height:0;display:flex"></div>
      <button class="pk-btn" id="tap">${CA.lamp("")} Tap</button></div>`;
    const taps = [];                                   // this frame's taps (the PC keeps the count)
    let tab = "taps", order = "new";
    const $ = (s) => root.querySelector(s);
    const draw = () => {
      const deaths = CA.pad.status?.deaths ?? 0;       // the add-on's api.set_status({..., deaths})
      $(".pk-screen").textContent = tab === "taps" ? `${taps.length ? taps[taps.length - 1].n : 0} taps` : `${deaths} deaths`;
      const rows = (order === "new" ? [...taps].reverse() : taps).map((t, i) => ({
        cells: ["", `Tap ${t.n}`, t.at], level: "ok", on: order === "new" ? i === 0 : i === taps.length - 1 }));
      $(".list").innerHTML = tab === "taps"
        ? CA.table([{ kind: "lamp" }, { kind: "text", label: "Tap" }, { kind: "num", label: "At" }], rows, "No taps yet")
        : CA.table([{ kind: "text", label: "Counted on the PC" }, { kind: "num" }], [{ cells: ["Deaths", String(deaths)], level: deaths ? "warn" : "" }]);
      CA.fitTable($(".list"));
    };
    root.querySelectorAll(".pk-tab").forEach((b) => b.onclick = () => {
      tab = b.dataset.tab;
      root.querySelectorAll(".pk-tab").forEach((x) => x.classList.toggle("on", x === b));
      draw();
    });
    root.querySelectorAll(".pk-toggle > button").forEach((b) => b.onclick = () => {
      order = b.dataset.order;
      root.querySelectorAll(".pk-toggle > button").forEach((x) => x.classList.toggle("on", x === b));
      draw();
    });
    const btn = $("#tap");
    btn.onclick = async () => {
      if (editing) return;
      const lamp = (lv) => { btn.classList.toggle("on", !!lv); btn.firstElementChild.outerHTML = CA.lamp(lv); };
      lamp("ok");                                      // lit while the PC answers
      const r = await CA.call({ op: "tap" });
      lamp("");
      if (typeof r.taps === "number") taps.push({ n: r.taps, at: new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit" }) });
      draw();
    };
    draw();
  },
});
From the Comms Array source, commsarray-agent d615c4d.