ovos-skill-backgammon 0.1.0a1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. ovos_skill_backgammon/__init__.py +71 -0
  2. ovos_skill_backgammon/boardgame.py +440 -0
  3. ovos_skill_backgammon/controlpanel.json +116 -0
  4. ovos_skill_backgammon/controlpanel.svg +1 -0
  5. ovos_skill_backgammon/engine.py +438 -0
  6. ovos_skill_backgammon/icon.png +0 -0
  7. ovos_skill_backgammon/icon.svg +1 -0
  8. ovos_skill_backgammon/locale/ca-ES/backgammon.json +201 -0
  9. ovos_skill_backgammon/locale/ca-ES/backgammon_skill.voc +1 -0
  10. ovos_skill_backgammon/locale/ca-ES/controlpanel.json +25 -0
  11. ovos_skill_backgammon/locale/ca-ES/play.intent +9 -0
  12. ovos_skill_backgammon/locale/ca-ES/skill.json +28 -0
  13. ovos_skill_backgammon/locale/da-DK/backgammon.json +207 -0
  14. ovos_skill_backgammon/locale/da-DK/backgammon_skill.voc +1 -0
  15. ovos_skill_backgammon/locale/da-DK/controlpanel.json +25 -0
  16. ovos_skill_backgammon/locale/da-DK/play.intent +9 -0
  17. ovos_skill_backgammon/locale/da-DK/skill.json +28 -0
  18. ovos_skill_backgammon/locale/de-DE/backgammon.json +204 -0
  19. ovos_skill_backgammon/locale/de-DE/backgammon_skill.voc +1 -0
  20. ovos_skill_backgammon/locale/de-DE/controlpanel.json +25 -0
  21. ovos_skill_backgammon/locale/de-DE/play.intent +9 -0
  22. ovos_skill_backgammon/locale/de-DE/skill.json +28 -0
  23. ovos_skill_backgammon/locale/en-US/backgammon.json +205 -0
  24. ovos_skill_backgammon/locale/en-US/backgammon_skill.voc +1 -0
  25. ovos_skill_backgammon/locale/en-US/controlpanel.json +25 -0
  26. ovos_skill_backgammon/locale/en-US/play.intent +9 -0
  27. ovos_skill_backgammon/locale/en-US/skill.json +28 -0
  28. ovos_skill_backgammon/locale/es-ES/backgammon.json +203 -0
  29. ovos_skill_backgammon/locale/es-ES/backgammon_skill.voc +1 -0
  30. ovos_skill_backgammon/locale/es-ES/controlpanel.json +25 -0
  31. ovos_skill_backgammon/locale/es-ES/play.intent +9 -0
  32. ovos_skill_backgammon/locale/es-ES/skill.json +28 -0
  33. ovos_skill_backgammon/locale/eu-ES/backgammon.json +198 -0
  34. ovos_skill_backgammon/locale/eu-ES/backgammon_skill.voc +1 -0
  35. ovos_skill_backgammon/locale/eu-ES/controlpanel.json +25 -0
  36. ovos_skill_backgammon/locale/eu-ES/play.intent +9 -0
  37. ovos_skill_backgammon/locale/eu-ES/skill.json +28 -0
  38. ovos_skill_backgammon/locale/fr-FR/backgammon.json +202 -0
  39. ovos_skill_backgammon/locale/fr-FR/backgammon_skill.voc +1 -0
  40. ovos_skill_backgammon/locale/fr-FR/controlpanel.json +25 -0
  41. ovos_skill_backgammon/locale/fr-FR/play.intent +9 -0
  42. ovos_skill_backgammon/locale/fr-FR/skill.json +28 -0
  43. ovos_skill_backgammon/locale/gl-ES/backgammon.json +201 -0
  44. ovos_skill_backgammon/locale/gl-ES/backgammon_skill.voc +1 -0
  45. ovos_skill_backgammon/locale/gl-ES/controlpanel.json +25 -0
  46. ovos_skill_backgammon/locale/gl-ES/play.intent +9 -0
  47. ovos_skill_backgammon/locale/gl-ES/skill.json +28 -0
  48. ovos_skill_backgammon/locale/it-IT/backgammon.json +200 -0
  49. ovos_skill_backgammon/locale/it-IT/backgammon_skill.voc +1 -0
  50. ovos_skill_backgammon/locale/it-IT/controlpanel.json +25 -0
  51. ovos_skill_backgammon/locale/it-IT/play.intent +9 -0
  52. ovos_skill_backgammon/locale/it-IT/skill.json +28 -0
  53. ovos_skill_backgammon/locale/nb-NO/backgammon.json +202 -0
  54. ovos_skill_backgammon/locale/nb-NO/backgammon_skill.voc +1 -0
  55. ovos_skill_backgammon/locale/nb-NO/controlpanel.json +25 -0
  56. ovos_skill_backgammon/locale/nb-NO/play.intent +9 -0
  57. ovos_skill_backgammon/locale/nb-NO/skill.json +28 -0
  58. ovos_skill_backgammon/locale/nl-NL/backgammon.json +203 -0
  59. ovos_skill_backgammon/locale/nl-NL/backgammon_skill.voc +1 -0
  60. ovos_skill_backgammon/locale/nl-NL/controlpanel.json +25 -0
  61. ovos_skill_backgammon/locale/nl-NL/play.intent +9 -0
  62. ovos_skill_backgammon/locale/nl-NL/skill.json +28 -0
  63. ovos_skill_backgammon/locale/pt-BR/backgammon.json +202 -0
  64. ovos_skill_backgammon/locale/pt-BR/backgammon_skill.voc +1 -0
  65. ovos_skill_backgammon/locale/pt-BR/controlpanel.json +25 -0
  66. ovos_skill_backgammon/locale/pt-BR/play.intent +10 -0
  67. ovos_skill_backgammon/locale/pt-BR/skill.json +28 -0
  68. ovos_skill_backgammon/locale/pt-PT/backgammon.json +202 -0
  69. ovos_skill_backgammon/locale/pt-PT/backgammon_skill.voc +1 -0
  70. ovos_skill_backgammon/locale/pt-PT/controlpanel.json +25 -0
  71. ovos_skill_backgammon/locale/pt-PT/play.intent +10 -0
  72. ovos_skill_backgammon/locale/pt-PT/skill.json +28 -0
  73. ovos_skill_backgammon/locale/sv-SE/backgammon.json +203 -0
  74. ovos_skill_backgammon/locale/sv-SE/backgammon_skill.voc +1 -0
  75. ovos_skill_backgammon/locale/sv-SE/controlpanel.json +25 -0
  76. ovos_skill_backgammon/locale/sv-SE/play.intent +9 -0
  77. ovos_skill_backgammon/locale/sv-SE/skill.json +28 -0
  78. ovos_skill_backgammon/picture.py +156 -0
  79. ovos_skill_backgammon/screenshot-portrait.png +0 -0
  80. ovos_skill_backgammon/screenshot.png +0 -0
  81. ovos_skill_backgammon/spoken_numbers.py +132 -0
  82. ovos_skill_backgammon-0.1.0a1.dist-info/METADATA +131 -0
  83. ovos_skill_backgammon-0.1.0a1.dist-info/RECORD +87 -0
  84. ovos_skill_backgammon-0.1.0a1.dist-info/WHEEL +5 -0
  85. ovos_skill_backgammon-0.1.0a1.dist-info/entry_points.txt +2 -0
  86. ovos_skill_backgammon-0.1.0a1.dist-info/licenses/LICENSE +201 -0
  87. ovos_skill_backgammon-0.1.0a1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,71 @@
1
+ # Copyright 2026 emkay-voice
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Backgammon against Emkay, by voice.
16
+
17
+ "Play backgammon" - the points are numbered 1 to 24 from your side, so a
18
+ move is just "13 to 7"; "bar to 22", "6 off". Say roll, or the two numbers
19
+ you rolled on real dice. Emkay rolls its own dice on the screen and says
20
+ its moves in the same numbers - play on the screen, or on your own board
21
+ and move Emkay's checkers as it says. Easy, normal and hard. The game is
22
+ saved as you go - also for your other devices with My Emkay. Made for
23
+ Emkay, works on any OpenVoiceOS."""
24
+ from .boardgame import BoardGameSkill, normalize
25
+ from .engine import EMKAY, YOU, Game, new_game, pips, state
26
+ from .picture import compose
27
+
28
+
29
+ class BackgammonSkill(BoardGameSkill):
30
+ WORDS = "backgammon.json"
31
+ VOC = "backgammon_skill"
32
+ BUS = "backgammon"
33
+ URI = "backgammon:game"
34
+ ICON = "https://raw.githubusercontent.com/emkay-voice/ovos-skill-backgammon/main/icon.png"
35
+ BACKGROUND = "#12161c"
36
+ DEFAULTS = {"pictures": True, "layout": "auto", "dice": "screen"}
37
+
38
+ def _said(self, utterance, key):
39
+ said = f" {normalize(utterance)} "
40
+ return any(f" {normalize(w)} " in said for w in self._words().get(key, []))
41
+
42
+ def _choice(self, utterance, key):
43
+ said = f" {normalize(utterance)} "
44
+ for name, spoken in self._words().get(key, {}).items():
45
+ if any(f" {normalize(w)} " in said for w in spoken):
46
+ return name
47
+ return None
48
+
49
+ def wants_new(self, utterance):
50
+ return bool(utterance) and bool(self._choice(utterance, "levels") or self._said(utterance, "emkay_first")
51
+ or self._said(utterance, "real_dice") or self._said(utterance, "screen_dice"))
52
+
53
+ def new_game(self, utterance=""):
54
+ real = self.setting("dice") == "real"
55
+ if utterance and self._said(utterance, "real_dice"):
56
+ real = True
57
+ if utterance and self._said(utterance, "screen_dice"):
58
+ real = False
59
+ first = EMKAY if utterance and self._said(utterance, "emkay_first") else YOU
60
+ return new_game(self._choice(utterance, "levels") or "normal", first, real)
61
+
62
+ def make_game(self, g):
63
+ return Game(g, self._words())
64
+
65
+ def picture(self, game, portrait):
66
+ return compose(game.g, game.words, game.words["title"], portrait=portrait)
67
+
68
+ def panel_status(self, g):
69
+ words = self._words()
70
+ you, me = pips(state(g))
71
+ return {"pips": f"{you} – {me}", "dice_kind": words.get("cp_dice", {}).get("real" if g.get("real") else "screen", "")}
@@ -0,0 +1,440 @@
1
+ # Copyright 2026 emkay-voice
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """What every board game of emkay-voice does the same way, so each game is
16
+ only its rules (engine.py) and its picture (picture.py).
17
+
18
+ * "play <game>" comes through OCP's search (OCP takes every "play ...") as a
19
+ game, and through the skill's own play.intent.
20
+ * While a game is on, what is said goes to the game first (converse), so
21
+ "down" or "seven" is the game's and not another skill's. The answer to
22
+ ovos-core is quick; the turn is played on the skill's own event.
23
+ * "stop" (can_stop/stop) saves the game and ends it; "play <game>" goes on.
24
+ * The game is saved after every turn, and on your other devices too (My
25
+ Emkay sync).
26
+ * The picture is drawn for a lying or a standing screen, as the screen says
27
+ (ovos-phal-plugin-browser) or as set.
28
+ * The control panel's page asks ovos.<bus>.status/start/reset/stop.
29
+ * "Show the rules" (words "rules_q") puts the rules (words "rules_page", a
30
+ list of short lines) on the screen as a page of their own and reads them;
31
+ the next turn shows the board again.
32
+
33
+ The same file is in every board game of emkay-voice; keep them alike.
34
+
35
+ A game (engine.Game) is made from its saved dict and the words of the
36
+ language: Game(g, words). It has .g (the dict that is saved), .handle(said)
37
+ -> the answer to say, .describe() -> where the game stands, and g["over"]
38
+ is None while it goes on, else "won", "lost" or "draw"."""
39
+ import json
40
+ import random
41
+ import re
42
+ import threading
43
+ import unicodedata
44
+ from pathlib import Path
45
+
46
+ from ovos_bus_client.message import Message
47
+ from ovos_utils import classproperty
48
+ from ovos_utils.ocp import MediaEntry, MediaType, PlaybackType, PlayerState, Playlist
49
+ from ovos_utils.process_utils import RuntimeRequirements
50
+ from ovos_workshop.decorators import intent_handler, ocp_featured_media, ocp_search
51
+ from ovos_workshop.skills.common_play import OVOSCommonPlaybackSkill
52
+ from ovos_workshop.skills.converse import ConversationalSkill
53
+
54
+
55
+ def normalize(text):
56
+ text = unicodedata.normalize("NFKC", str(text or "")).lower()
57
+ return " ".join(re.sub(r"[^\w\s]", " ", text).split())
58
+
59
+
60
+ def wrap(text, width):
61
+ """Lines of at most width characters (words are not broken)."""
62
+ lines, line = [], ""
63
+ for word in str(text).split():
64
+ if line and len(line) + 1 + len(word) > width:
65
+ lines.append(line)
66
+ line = word
67
+ else:
68
+ line = f"{line} {word}".strip()
69
+ return lines + ([line] if line else [])
70
+
71
+
72
+ def rules_page(title, rules, portrait=False, background="#0b1020", accent="#ffd23f"):
73
+ """The rules as a page: the title, and each rule as a bullet, wrapped to fit."""
74
+ from xml.sax.saxutils import escape
75
+ W, H = (480, 960) if portrait else (800, 500)
76
+ width = 30 if portrait else 54
77
+ size = 22 if portrait else 21
78
+ step = size * 1.38
79
+ out = [f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {W} {H}" width="{W}" height="{H}">',
80
+ f'<rect width="{W}" height="{H}" fill="{background}"/>',
81
+ f'<text x="{W / 2}" y="{58 if portrait else 46}" text-anchor="middle" font-size="{30 if portrait else 28}" '
82
+ f'font-weight="bold" letter-spacing="3" fill="{accent}" font-family="DejaVu Sans, Arial, sans-serif">'
83
+ f'{escape(str(title).upper())}</text>']
84
+ y = (110 if portrait else 84)
85
+ for rule in rules:
86
+ lines = wrap(rule, width)
87
+ out.append(f'<circle cx="{28}" cy="{y - size * 0.35:.1f}" r="4.5" fill="{accent}"/>')
88
+ for line in lines:
89
+ out.append(f'<text x="44" y="{y:.1f}" font-size="{size}" fill="#eef2ff" '
90
+ f'font-family="DejaVu Sans, Arial, sans-serif">{escape(line)}</text>')
91
+ y += step
92
+ y += step * 0.35
93
+ out.append("</svg>")
94
+ return "".join(out)
95
+
96
+
97
+ def data_url(svg):
98
+ import base64
99
+ return "data:image/svg+xml;base64," + base64.b64encode(svg.encode("utf-8")).decode("ascii")
100
+
101
+
102
+ class BoardGameSkill(ConversationalSkill, OVOSCommonPlaybackSkill):
103
+ """Subclasses set the class names below and implement new_game, make_game,
104
+ picture and (optionally) panel_status."""
105
+
106
+ WORDS = "game.json" # the texts of the language (locale/<lang>/)
107
+ VOC = "game_skill" # OCP's keywords for this skill (locale/<lang>/<VOC>.voc)
108
+ BUS = "game" # the control panel's messages: ovos.<BUS>.status ...
109
+ URI = "game:play"
110
+ ICON = ""
111
+ BACKGROUND = "#0b1020"
112
+ DEFAULTS = {"pictures": True, "layout": "auto"}
113
+
114
+ @classproperty
115
+ def runtime_requirements(self):
116
+ return RuntimeRequirements(
117
+ internet_before_load=False, network_before_load=False,
118
+ requires_internet=False, requires_network=False,
119
+ no_internet_fallback=True, no_network_fallback=True)
120
+
121
+ def __init__(self, *args, **kwargs):
122
+ self.game = None # the Game while one is on
123
+ self._query = "" # what OCP was last asked to play
124
+ self._orientation = None # "portrait" or "landscape", as the screen says
125
+ kwargs.setdefault("supported_media", list(MediaType))
126
+ kwargs.setdefault("skill_voc_filename", self.VOC)
127
+ kwargs.setdefault("skill_icon", self.ICON)
128
+ super().__init__(*args, playback_handler=self._ocp_play, pause_handler=self._ocp_pause,
129
+ resume_handler=self._ocp_resume, **kwargs)
130
+
131
+ # -- what each game is -------------------------------------------------------
132
+
133
+ def new_game(self, utterance=""):
134
+ """The dict of a new game (as said: "play code breaker with five colours")."""
135
+ raise NotImplementedError
136
+
137
+ def make_game(self, g):
138
+ """The Game for this dict, in the words of the language."""
139
+ raise NotImplementedError
140
+
141
+ def picture(self, game, portrait):
142
+ """The SVG of the game as it is."""
143
+ raise NotImplementedError
144
+
145
+ def panel_status(self, g):
146
+ """Extra rows for the control panel's status block (saved game g)."""
147
+ return {}
148
+
149
+ def wants_new(self, utterance):
150
+ """Was a new game of some kind asked for ("play chess as black")? Then a
151
+ saved game is not taken up."""
152
+ return False
153
+
154
+ def resumable(self, g):
155
+ return isinstance(g, dict) and bool(g) and not g.get("over")
156
+
157
+ # -- start -------------------------------------------------------------------
158
+
159
+ def initialize(self):
160
+ self.add_event(f"{self.skill_id}.turn", self.handle_turn)
161
+ for msg_type, handler in (("status", self.handle_panel_status), ("start", self.handle_panel_start),
162
+ ("reset", self.handle_panel_reset), ("stop", self.handle_panel_stop)):
163
+ self.add_event(f"ovos.{self.BUS}.{msg_type}", handler)
164
+ self.add_event("ovos.phal.sensor", self.handle_sensor)
165
+ threading.Thread(target=self._ask_orientation, daemon=True).start()
166
+ try:
167
+ words = self._words()
168
+ self.register_ocp_keyword(MediaType.GAME, "game_name", words["names"] + [words["title"]])
169
+ except Exception as e: # an older OCP, or none
170
+ self.log.debug(f"no OCP keywords: {e}")
171
+
172
+ # -- the screen: standing or lying -----------------------------------------
173
+
174
+ def _ask_orientation(self):
175
+ """Emkay's browser tells which way the screen stands (ovos-phal-plugin-browser)."""
176
+ answer = self.bus.wait_for_response(
177
+ Message("ovos.phal.sensor.get", {"sensor_ids": ["screen_orientation"]}),
178
+ "ovos.phal.sensor.get.response", timeout=3)
179
+ reading = ((answer.data.get("sensors") or {}).get("screen_orientation") or {}) if answer else {}
180
+ if reading.get("state") in ("portrait", "landscape"):
181
+ self._orientation = reading["state"]
182
+
183
+ def handle_sensor(self, message):
184
+ data = message.data or {}
185
+ if data.get("sensor_id") == "screen_orientation" and data.get("state") in ("portrait", "landscape"):
186
+ changed = data["state"] != self._orientation
187
+ self._orientation = data["state"]
188
+ if changed and self.game:
189
+ self._show()
190
+
191
+ def portrait(self):
192
+ """A standing screen: set so, or (auto) the screen says it stands."""
193
+ layout = self.setting("layout")
194
+ if layout in ("portrait", "landscape"):
195
+ return layout == "portrait"
196
+ return self._orientation == "portrait"
197
+
198
+ # -- settings and texts --------------------------------------------------
199
+
200
+ def setting(self, key):
201
+ return self.settings.get(key, self.DEFAULTS.get(key))
202
+
203
+ def _words(self):
204
+ return self.resources.load_json_file(self.WORDS)
205
+
206
+ def say(self, key, **values):
207
+ text = self._words()["say"][key]
208
+ return (random.choice(text) if isinstance(text, list) else text).format(**values)
209
+
210
+ def match(self, utterance, key):
211
+ said = f" {normalize(utterance)} "
212
+ return any(f" {normalize(w)} " in said for w in self._words().get(key, []))
213
+
214
+ # -- saving --------------------------------------------------------------------
215
+
216
+ def _save_path(self):
217
+ folder = Path(self.file_system.path)
218
+ folder.mkdir(parents=True, exist_ok=True)
219
+ return folder / "game.json"
220
+
221
+ def load_game(self):
222
+ try:
223
+ return json.loads(self._save_path().read_text(encoding="utf-8"))
224
+ except (OSError, ValueError):
225
+ return None
226
+
227
+ def save(self):
228
+ if self.game:
229
+ self._save_path().write_text(json.dumps(self.game.g), encoding="utf-8")
230
+ self.bus.emit(Message("ovos.sync.set", {"ns": self.skill_id, "key": "game", "value": self.game.g}))
231
+
232
+ def forget_save(self):
233
+ self._save_path().unlink(missing_ok=True)
234
+ self.bus.emit(Message("ovos.sync.set", {"ns": self.skill_id, "key": "game", "value": None}))
235
+
236
+ def synced_game(self):
237
+ """A game saved on another of your devices (My Emkay)."""
238
+ answer = self.bus.wait_for_response(Message("ovos.sync.get", {"ns": self.skill_id, "key": "game"}),
239
+ "ovos.sync.get.response", timeout=1.5)
240
+ value = answer.data.get("value") if answer else None
241
+ return value if self.resumable(value) else None
242
+
243
+ # -- playing ---------------------------------------------------------------------
244
+
245
+ @intent_handler("play.intent")
246
+ def handle_play(self, message):
247
+ """"Play <game>", "start <game> over"."""
248
+ utterance = message.data.get("utterance", "")
249
+ self.start(fresh=self.match(utterance, "restart"), utterance=utterance)
250
+
251
+ def start(self, fresh=False, utterance=""):
252
+ fresh = fresh or self.wants_new(utterance)
253
+ saved = None if fresh else (self.load_game() or self.synced_game())
254
+ if self.resumable(saved):
255
+ self.game = self.make_game(saved)
256
+ opening = self.say("welcome_back") + " " + self.game.describe()
257
+ else:
258
+ self.game = self.make_game(self.new_game(utterance))
259
+ opening = self.say("intro") + " " + self.game.describe()
260
+ self._show()
261
+ self.speak(opening.strip(), expect_response=True)
262
+ self.save()
263
+ self._keep_active()
264
+
265
+ def _leave(self):
266
+ """Out of the active skills: what is said is everybody's again."""
267
+ try:
268
+ self.deactivate()
269
+ except Exception:
270
+ pass
271
+
272
+ def _keep_active(self):
273
+ try:
274
+ self.activate()
275
+ except Exception:
276
+ pass
277
+
278
+ def can_converse(self, message=None):
279
+ return self.game is not None
280
+
281
+ def converse(self, message=None):
282
+ if not self.game or message is None:
283
+ return False
284
+ utterance = (message.data.get("utterances") or [""])[0]
285
+ self.bus.emit(message.forward(f"{self.skill_id}.turn", {"utterance": utterance}))
286
+ return True
287
+
288
+ def handle_turn(self, message):
289
+ if self.game:
290
+ self.play_turn(message.data.get("utterance", ""))
291
+
292
+ def play_turn(self, utterance):
293
+ if self.match(utterance, "quit"):
294
+ self.save()
295
+ self.end()
296
+ self.speak(self.say("bye"))
297
+ return
298
+ if self.match(utterance, "restart"):
299
+ self.start(fresh=True, utterance=utterance)
300
+ return
301
+ if self.match(utterance, "rules_q"):
302
+ self.show_rules()
303
+ return
304
+ game = self.game
305
+ game.words = self._words()
306
+ answer = game.handle(utterance)
307
+ self._show()
308
+ if game.g.get("over"):
309
+ self.forget_save()
310
+ self.speak(answer)
311
+ self.game = None
312
+ self._leave()
313
+ self._ocp_stopped()
314
+ return
315
+ self.save()
316
+ self.speak(answer, expect_response=True)
317
+ self._keep_active()
318
+
319
+ def end(self):
320
+ self.game = None
321
+ self._leave()
322
+ self._ocp_stopped()
323
+ try:
324
+ self.gui.release()
325
+ except Exception:
326
+ pass
327
+
328
+ def can_stop(self, message=None):
329
+ """The stop pipeline asks first: "stop" ends a game that is on."""
330
+ return bool(self.game)
331
+
332
+ def stop(self):
333
+ """"Stop": the game is saved and ends - "play ..." goes on with it."""
334
+ if self.game:
335
+ self.save()
336
+ bye = self.say("bye")
337
+ self.end()
338
+ self.speak(bye)
339
+ return True
340
+ return False
341
+
342
+ # -- OCP: "play ..." -------------------------------------------------------------------
343
+
344
+ def _entry(self, confidence):
345
+ return MediaEntry(uri=self.URI, title=self._words()["title"], image=self.ICON, skill_icon=self.ICON,
346
+ playback=PlaybackType.SKILL, media_type=MediaType.GAME, match_confidence=confidence)
347
+
348
+ @ocp_search()
349
+ def search_game(self, phrase, media_type=MediaType.GENERIC):
350
+ """"play <game>" -> the game."""
351
+ said = normalize(phrase)
352
+ self._query = phrase
353
+ names = sorted((normalize(n) for n in self._words()["names"]), key=len, reverse=True)
354
+ for n in names:
355
+ if n and f" {n} " in f" {said} ":
356
+ whole = len(n) >= len(said) - 4
357
+ game = media_type in (MediaType.GAME, MediaType.GENERIC)
358
+ confidence = (100 if whole else 90) if game else (80 if whole else 0)
359
+ return [self._entry(confidence)] if confidence else []
360
+ return []
361
+
362
+ @ocp_featured_media()
363
+ def featured_game(self):
364
+ playlist = Playlist(title=self._words()["title"], image=self.ICON, skill_icon=self.ICON,
365
+ playback=PlaybackType.SKILL, media_type=MediaType.GAME, match_confidence=100)
366
+ playlist.add_entry(self._entry(100))
367
+ return playlist
368
+
369
+ def _ocp_play(self, message=None):
370
+ self.start(utterance=self._query)
371
+
372
+ def _ocp_pause(self, message=None):
373
+ self.save()
374
+ return True
375
+
376
+ def _ocp_resume(self, message=None):
377
+ if self.game:
378
+ self.speak(self.game.describe(), expect_response=True)
379
+ return True
380
+
381
+ def _ocp_stopped(self):
382
+ """Tell OCP the game is over, so "next", "pause" and "play" are its own again."""
383
+ playing = getattr(self, "_playing", None)
384
+ if playing is not None and playing.is_set():
385
+ playing.clear()
386
+ self.bus.emit(Message("ovos.common_play.player.state", {"state": PlayerState.STOPPED}))
387
+
388
+ # -- the screen ------------------------------------------------------------------------
389
+
390
+ def _show(self):
391
+ if not self.game or not self.setting("pictures"):
392
+ return
393
+ words = self._words()
394
+ self.game.words = words
395
+ self.gui["image"] = data_url(self.picture(self.game, self.portrait()))
396
+ self.gui["title"] = words["title"]
397
+ self.gui["caption"] = ""
398
+ self.gui["fill"] = "PreserveAspectFit"
399
+ self.gui["background_color"] = self.BACKGROUND
400
+ self.gui.show_page("SYSTEM_ImageFrame", override_idle=True)
401
+
402
+ def show_rules(self):
403
+ """The rules on the screen, and read aloud (the board comes back with the next turn)."""
404
+ words = self._words()
405
+ rules = words.get("rules_page", [])
406
+ if self.setting("pictures"):
407
+ accent = getattr(self, "ACCENT", "#ffd23f")
408
+ self.gui["image"] = data_url(rules_page(words["title"], rules, self.portrait(), self.BACKGROUND, accent))
409
+ self.gui["title"] = words["title"]
410
+ self.gui["caption"] = ""
411
+ self.gui["fill"] = "PreserveAspectFit"
412
+ self.gui["background_color"] = self.BACKGROUND
413
+ self.gui.show_page("SYSTEM_ImageFrame", override_idle=True)
414
+ self.speak(" ".join(rules), expect_response=bool(self.game))
415
+ if self.game:
416
+ self._keep_active()
417
+
418
+ # -- the control panel ----------------------------------------------------------------
419
+
420
+ def handle_panel_status(self, message):
421
+ """The game on now, or the saved one: for the page's status block."""
422
+ g = self.game.g if self.game else self.load_game()
423
+ saved = self.resumable(g)
424
+ data = {"saved": saved, "playing": self.game is not None}
425
+ if saved:
426
+ data.update(self.panel_status(g))
427
+ self.bus.emit(message.response(data))
428
+
429
+ def handle_panel_start(self, message):
430
+ self.start()
431
+ self.bus.emit(message.response({"started": True}))
432
+
433
+ def handle_panel_reset(self, message):
434
+ if self.game:
435
+ self.end()
436
+ self.forget_save()
437
+ self.bus.emit(message.response({"reset": True}))
438
+
439
+ def handle_panel_stop(self, message):
440
+ self.bus.emit(message.response({"stopped": self.stop()}))
@@ -0,0 +1,116 @@
1
+ {
2
+ "controlpanel": 1,
3
+ "id": "backgammon",
4
+ "title": "backgammon.title",
5
+ "group": "everyday",
6
+ "order": 76,
7
+ "icon": "controlpanel.svg",
8
+ "bus": "ovos.backgammon.",
9
+ "blocks": [
10
+ {
11
+ "type": "text",
12
+ "text": "backgammon.intro"
13
+ },
14
+ {
15
+ "type": "text",
16
+ "text": "backgammon.rules"
17
+ },
18
+ {
19
+ "type": "status",
20
+ "heading": "backgammon.game",
21
+ "query": "ovos.backgammon.status",
22
+ "refresh": 10,
23
+ "rows": [
24
+ {
25
+ "text": "backgammon.none",
26
+ "when": "!saved"
27
+ },
28
+ {
29
+ "text": "backgammon.playing",
30
+ "when": "playing"
31
+ },
32
+ {
33
+ "label": "backgammon.pips",
34
+ "value": "{pips}",
35
+ "when": "saved"
36
+ },
37
+ {
38
+ "label": "backgammon.dice_kind",
39
+ "value": "{dice_kind}",
40
+ "when": "saved"
41
+ }
42
+ ],
43
+ "actions": [
44
+ {
45
+ "label": "backgammon.play",
46
+ "send": "ovos.backgammon.start",
47
+ "done": "backgammon.started",
48
+ "when": "!playing"
49
+ },
50
+ {
51
+ "label": "backgammon.reset",
52
+ "send": "ovos.backgammon.reset",
53
+ "done": "backgammon.was_reset",
54
+ "when": "saved",
55
+ "confirm": "backgammon.confirm_reset"
56
+ },
57
+ {
58
+ "label": "backgammon.stop",
59
+ "send": "ovos.backgammon.stop",
60
+ "when": "playing"
61
+ }
62
+ ]
63
+ },
64
+ {
65
+ "type": "form",
66
+ "heading": "backgammon.settings",
67
+ "save": {
68
+ "settings": true
69
+ },
70
+ "fields": [
71
+ {
72
+ "name": "pictures",
73
+ "label": "backgammon.pictures",
74
+ "type": "checkbox",
75
+ "default": true
76
+ },
77
+ {
78
+ "name": "layout",
79
+ "label": "backgammon.layout",
80
+ "type": "select",
81
+ "default": "auto",
82
+ "options": [
83
+ {
84
+ "value": "auto",
85
+ "label": "backgammon.layout_auto"
86
+ },
87
+ {
88
+ "value": "portrait",
89
+ "label": "backgammon.layout_portrait"
90
+ },
91
+ {
92
+ "value": "landscape",
93
+ "label": "backgammon.layout_landscape"
94
+ }
95
+ ]
96
+ },
97
+ {
98
+ "name": "dice",
99
+ "label": "backgammon.dice_label",
100
+ "type": "select",
101
+ "default": "screen",
102
+ "options": [
103
+ {
104
+ "value": "screen",
105
+ "label": "backgammon.dice_screen"
106
+ },
107
+ {
108
+ "value": "real",
109
+ "label": "backgammon.dice_real"
110
+ }
111
+ ]
112
+ }
113
+ ]
114
+ }
115
+ ]
116
+ }
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><rect width="512" height="512" rx="96" fill="#7F1D1D"/><g fill="#fff"><polygon points="96,96 156,96 126,300"/><polygon points="176,96 236,96 206,300" fill-opacity="0.5"/><polygon points="276,416 336,416 306,212" fill-opacity="0.5"/><polygon points="356,416 416,416 386,212"/></g><circle cx="126" cy="372" r="34" fill="none" stroke="#fff" stroke-width="14"/><circle cx="206" cy="372" r="34" fill="#fff"/><circle cx="306" cy="140" r="34" fill="#fff"/><circle cx="386" cy="140" r="34" fill="none" stroke="#fff" stroke-width="14"/></svg>