magmacrunch-solitaire 0.1.0__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.
klondike/__init__.py ADDED
File without changes
klondike/__main__.py ADDED
@@ -0,0 +1,27 @@
1
+ """``python -m klondike`` -- play the arcade's Solitaire: Klondike, draw three."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+
7
+
8
+ def main() -> None:
9
+ parser = argparse.ArgumentParser(prog="solitaire",
10
+ description="Klondike solitaire, draw three.")
11
+ parser.add_argument("--play", action="store_true", help="skip the title screen")
12
+ parser.add_argument("--seed", type=int, default=None, help="the same deals every time")
13
+ parser.add_argument(
14
+ "--ascii", action="store_true", dest="ascii_only",
15
+ help="draw with plain ASCII instead of block and box glyphs. Detected "
16
+ "automatically from the terminal's encoding; this forces it. "
17
+ "MAGMACRUNCH_ASCII=1 says the same for every cabinet.",
18
+ )
19
+ args = parser.parse_args()
20
+
21
+ from klondike.app import run
22
+
23
+ run(args.seed, args.play, args.ascii_only)
24
+
25
+
26
+ if __name__ == "__main__":
27
+ main()
klondike/app.py ADDED
@@ -0,0 +1,98 @@
1
+ """Wiring -- what outlives one deal, and how the screens reach it.
2
+
3
+ Everything that draws lives in :mod:`klondike.scenes`; everything that decides
4
+ lives in :mod:`klondike.rules`. **The terminal is not owned here**: it belongs
5
+ to a ``TuiHost``, which is what lets this run as its own command or be seated
6
+ by the arcade.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import random
12
+ import time
13
+ from collections.abc import Callable
14
+ from typing import Any
15
+
16
+ from magmacrunch.engine.scores import ScoreBook
17
+
18
+ from klondike.arcade import INFO
19
+ from klondike.scenes import GameScene, TitleScene
20
+
21
+
22
+ class SolitaireApp:
23
+ def __init__(self, host: Any, seed: int | None = None,
24
+ scores: ScoreBook | None = None,
25
+ clock: Callable[[], float] | None = None):
26
+ self.host = host
27
+ #: Where each deal's shuffle comes from. Seeded, so ``--seed``
28
+ #: replays a whole session.
29
+ self.rng = random.Random(seed)
30
+ #: The board the browser posts to: the score of a won game, with its
31
+ #: time beside it.
32
+ self.scores = scores or ScoreBook(INFO.scoreboard)
33
+ #: Seconds, for the page's clock. A test hands in its own.
34
+ self.clock = clock or time.monotonic
35
+ self.initials = "AAA"
36
+ self.last_rank: int | None = None
37
+ self.root_scene = TitleScene(self)
38
+
39
+ @property
40
+ def renderer(self):
41
+ return self.host.renderer
42
+
43
+ def new_rand(self):
44
+ return random.Random(self.rng.randrange(1 << 32)).random
45
+
46
+ def start_game(self) -> None:
47
+ self.host.push_scene(GameScene(self))
48
+
49
+ def show_scores(self) -> None:
50
+ from klondike.scenes import ScoresScene
51
+
52
+ self.host.push_scene(ScoresScene(self))
53
+
54
+ def show_rules(self) -> None:
55
+ from klondike.scenes import RulesScene
56
+
57
+ self.host.push_scene(RulesScene(self))
58
+
59
+ def enter_initials(self, score: int, extra: dict) -> None:
60
+ from klondike.scenes import InitialsScene
61
+
62
+ self.host.push_scene(InitialsScene(self, score, extra))
63
+
64
+ def to_title(self) -> None:
65
+ self.host.pop_scene()
66
+
67
+ def leave(self) -> None:
68
+ self.host.pop_scene()
69
+
70
+ def qualifies(self, score: int) -> bool:
71
+ """``isHighScore``: above nothing, and in the top ten."""
72
+ return score > 0 and self.scores.qualifies(score)
73
+
74
+ def record(self, score: int, initials: str | None = None,
75
+ extra: dict | None = None):
76
+ self.initials = initials or self.initials
77
+ result = self.scores.save(self.initials, score, **(extra or {}))
78
+ self.last_rank = result.rank
79
+ return result
80
+
81
+ @property
82
+ def scene(self):
83
+ return self.host.scene
84
+
85
+
86
+ def run(seed: int | None = None, skip_title: bool = False,
87
+ ascii_only: bool = False) -> None:
88
+ """Play Solitaire as its own command."""
89
+ from magmacrunch.engine.core.tui_host import TuiHost
90
+ from magmacrunch.engine.ui.glyphs import Glyphs
91
+
92
+ host = TuiHost(title=INFO.title, fps=INFO.fps, hold_ms=INFO.hold_ms,
93
+ glyphs=Glyphs.detect(ascii_only=ascii_only))
94
+ app = SolitaireApp(host, seed)
95
+ host.push_scene(app.root_scene)
96
+ if skip_title:
97
+ host.push_scene(GameScene(app))
98
+ host.run()
klondike/arcade.py ADDED
@@ -0,0 +1,39 @@
1
+ """What the arcade needs to know to launch this game. Kept tiny: a menu loads
2
+ one of these per installed game just to draw a card."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from typing import Any
7
+
8
+ from magmacrunch.engine.arcade import GameInfo
9
+
10
+ from klondike import theme
11
+
12
+ INFO = GameInfo(
13
+ key="solitaire",
14
+ title="Solitaire",
15
+ blurb="Klondike, draw three, against the clock.",
16
+ # The frame rate moves the page's clock and the cursor, nothing else.
17
+ # Edge input, so one arrow is one step.
18
+ fps=20,
19
+ hold_ms=0,
20
+ min_cols=theme.MIN_COLS,
21
+ min_rows=theme.MIN_ROWS,
22
+ accent=theme.PINK,
23
+ )
24
+
25
+
26
+ class SolitaireGame:
27
+ """Satisfies :class:`magmacrunch.engine.arcade.ArcadeGame`."""
28
+
29
+ info = INFO
30
+
31
+ def start(self, host: Any) -> Any:
32
+ from klondike.app import SolitaireApp
33
+
34
+ return SolitaireApp(host).root_scene
35
+
36
+
37
+ GAME = SolitaireGame()
38
+
39
+ __all__ = ["GAME", "INFO", "SolitaireGame"]
klondike/rules.py ADDED
@@ -0,0 +1,404 @@
1
+ """The page's Klondike, function for function.
2
+
3
+ ``web/js/game.js`` is one class, ``Solitaire``, that keeps the table and
4
+ draws it; this is the keeping half, method for method, with the drawing left
5
+ to :mod:`klondike.scenes`. The deck and its shuffle are the website's
6
+ ``shared/adenosine-cards.js``. ``tests/test_oracle.py`` holds every method
7
+ here to the page's own, click for click.
8
+
9
+ **The page's clock is part of the rules.** The time on the table is
10
+ ``elapsedSeconds``, which the page's one-second ``setInterval`` sets, so it
11
+ can be up to a second behind until a win reads the clock itself. So the
12
+ clock here is the page's: :class:`Game` keeps the time in milliseconds,
13
+ :meth:`Game.advance` moves it on, and the interval fires at each of its
14
+ seconds on the way, as a browser fires it. A double click is two clicks on
15
+ one card inside 300 ms of that time.
16
+
17
+ Nothing here draws, waits or reads a real clock; the screen moves the time.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import math
23
+ from collections.abc import Callable
24
+ from dataclasses import dataclass
25
+
26
+ Rand = Callable[[], float]
27
+
28
+ SUITS = ("hearts", "diamonds", "clubs", "spades")
29
+ RANKS = ("A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K")
30
+ SUIT_SYMBOLS = {"hearts": "♥", "diamonds": "♦", "clubs": "♣", "spades": "♠"}
31
+ #: ``SUIT_COLORS``: the ink, which is what the page compares to alternate.
32
+ SUIT_COLORS = {"hearts": "#cc0000", "diamonds": "#cc0000", "clubs": "#111111",
33
+ "spades": "#111111"}
34
+ RANK_VALUES = {r: i for i, r in enumerate(RANKS, start=1)}
35
+
36
+ #: The win bonus, ``(700,000 / seconds) x 35``, as Windows paid it.
37
+ BONUS = 700000
38
+ BONUS_TIMES = 35
39
+ #: A win faster than this is paid as this, so the bonus never falls as a
40
+ #: win gets faster. Windows paid nothing under 30 seconds.
41
+ BONUS_FLOOR_SECONDS = 30
42
+ #: What a double click is, in milliseconds.
43
+ DOUBLE_CLICK_MS = 300
44
+ #: ``setTimeout(showWinModal, 400)``.
45
+ WIN_SCREEN_MS = 400
46
+
47
+ TABLEAU, WASTE, FOUNDATION = "tableau", "waste", "foundation"
48
+
49
+
50
+ @dataclass(eq=False)
51
+ class Card:
52
+ """``AdCards.Card``. Compared by identity, as the page compares them."""
53
+
54
+ suit: str
55
+ rank: str
56
+ face_up: bool = False
57
+
58
+ @property
59
+ def color(self) -> str:
60
+ return SUIT_COLORS[self.suit]
61
+
62
+ @property
63
+ def value(self) -> int:
64
+ return RANK_VALUES[self.rank]
65
+
66
+ @property
67
+ def red(self) -> bool:
68
+ return self.suit in ("hearts", "diamonds")
69
+
70
+ def flip(self) -> None:
71
+ self.face_up = not self.face_up
72
+
73
+ @property
74
+ def id(self) -> str:
75
+ return f"{self.rank}{self.suit[0]}"
76
+
77
+ def __repr__(self) -> str:
78
+ return f"{self.id}{'' if self.face_up else '*'}"
79
+
80
+
81
+ def new_deck() -> list[Card]:
82
+ """``Deck.createDeck``: suit by suit, ace to king."""
83
+ return [Card(s, r) for s in SUITS for r in RANKS]
84
+
85
+
86
+ def shuffle(cards: list[Card], rand: Rand) -> None:
87
+ """``Deck.shuffle``: Fisher-Yates from the end."""
88
+ for i in range(len(cards) - 1, 0, -1):
89
+ j = math.floor(rand() * (i + 1))
90
+ cards[i], cards[j] = cards[j], cards[i]
91
+
92
+
93
+ def time_bonus_for(seconds: int) -> int:
94
+ """``timeBonusFor``: the bonus for a win in ``seconds``, counted as at
95
+ least 30."""
96
+ return math.floor((BONUS / max(seconds, BONUS_FLOOR_SECONDS)) * BONUS_TIMES)
97
+
98
+
99
+ def clock_text(seconds: int) -> str:
100
+ """``m:ss``, as the page writes the time."""
101
+ return f"{seconds // 60}:{seconds % 60:02d}"
102
+
103
+
104
+ @dataclass
105
+ class Win:
106
+ """What the page hands its win screen, 400 ms after the winning move."""
107
+
108
+ score: int
109
+ time: str
110
+ bonus: int
111
+ #: When the screen is due, on the game's clock.
112
+ due: float
113
+
114
+
115
+ class Game:
116
+ """``Solitaire``, without the page."""
117
+
118
+ def __init__(self, rand: Rand) -> None:
119
+ self.rand = rand
120
+ #: ``Date.now()``, in milliseconds. Only :meth:`advance` moves it.
121
+ self.now = 0.0
122
+ #: ``setInterval``'s timers, by id: when each fires next.
123
+ self._intervals: dict[int, float] = {}
124
+ self._next_id = 1
125
+ self.tableau: list[list[Card]] = [[] for _ in range(7)]
126
+ self.foundation: list[list[Card]] = [[] for _ in range(4)]
127
+ self.stock: list[Card] = []
128
+ self.waste: list[Card] = []
129
+ self.selected_card: Card | None = None
130
+ #: ``selectedPile``: (type, index, cardIndex).
131
+ self.selected_pile: tuple[str, int, int] | None = None
132
+ self.moves = 0
133
+ self.score = 0
134
+ self.time_started = 0.0
135
+ #: ``timerInterval``: the id, or None once a win or a pause stops it.
136
+ self.timer_interval: int | None = None
137
+ self.elapsed_seconds = 0
138
+ self.timer_paused = False
139
+ self.pause_start = 0.0
140
+ #: ``pauseReasons``: what holds the clock, a modal or the page hidden.
141
+ #: It runs again only once none is left.
142
+ self.pause_reasons: set[str] = set()
143
+ #: ``gameWon``: a won table is finished, and takes no more moves.
144
+ self.game_won = False
145
+ self._last_click: tuple[Card, str, int, int, float] | None = None
146
+ #: Win screens the page has set going, oldest first; each is shown
147
+ #: at its ``due`` time. The page sets one for every winning move.
148
+ self.wins: list[Win] = []
149
+ #: Every win screen ever set going, shown or not.
150
+ self.win_count = 0
151
+
152
+ # -- The page's clock ------------------------------------------------
153
+
154
+ def _set_interval(self) -> int:
155
+ i = self._next_id
156
+ self._next_id += 1
157
+ self._intervals[i] = self.now + 1000
158
+ return i
159
+
160
+ def _clear_interval(self, i: int | None) -> None:
161
+ self._intervals.pop(i, None)
162
+
163
+ def _tick(self) -> None:
164
+ self.elapsed_seconds = math.floor((self.now - self.time_started) / 1000)
165
+
166
+ def advance(self, ms: float) -> None:
167
+ """Move the clock on, firing the interval at each of its seconds."""
168
+ end = self.now + ms
169
+ while self._intervals:
170
+ i, due = min(self._intervals.items(), key=lambda kv: kv[1])
171
+ if due > end:
172
+ break
173
+ self.now = due
174
+ self._intervals[i] = due + 1000
175
+ self._tick()
176
+ self.now = end
177
+
178
+ @property
179
+ def clock_running(self) -> bool:
180
+ return bool(self._intervals)
181
+
182
+ # -- A deal ----------------------------------------------------------
183
+
184
+ def init(self) -> None:
185
+ deck = new_deck()
186
+ shuffle(deck, self.rand)
187
+ self.tableau = [[] for _ in range(7)]
188
+ self.foundation = [[] for _ in range(4)]
189
+ self.stock = []
190
+ self.waste = []
191
+ self.selected_card = None
192
+ self.selected_pile = None
193
+ self.moves = 0
194
+ self.score = 0
195
+ self.elapsed_seconds = 0
196
+ self.game_won = False
197
+ # A win's screen belongs to the deal that was won: ``clearTimeout``.
198
+ self.wins = []
199
+ if self.timer_interval:
200
+ self._clear_interval(self.timer_interval)
201
+ self.time_started = self.now
202
+ self.timer_interval = self._set_interval()
203
+ # A fresh clock holds for nothing from the last deal.
204
+ self.timer_paused = False
205
+ self.pause_reasons.clear()
206
+ for col in range(7):
207
+ for row in range(col + 1):
208
+ card = deck.pop()
209
+ if row == col:
210
+ card.flip()
211
+ self.tableau[col].append(card)
212
+ while deck:
213
+ self.stock.append(deck.pop())
214
+
215
+ def pause_timer(self, reason: str = "modal") -> None:
216
+ if not self.timer_paused and not self.timer_interval:
217
+ return # not running: nothing to hold
218
+ self.pause_reasons.add(reason)
219
+ if self.timer_paused:
220
+ return
221
+ self.timer_paused = True
222
+ self.pause_start = self.now
223
+ self._clear_interval(self.timer_interval)
224
+ self.timer_interval = None
225
+
226
+ def resume_timer(self, reason: str = "modal") -> None:
227
+ if not self.timer_paused:
228
+ return
229
+ self.pause_reasons.discard(reason)
230
+ if self.pause_reasons:
231
+ return
232
+ self.timer_paused = False
233
+ self.time_started += self.now - self.pause_start
234
+ self.timer_interval = self._set_interval()
235
+
236
+ # -- Play ------------------------------------------------------------
237
+
238
+ def draw_from_stock(self) -> None:
239
+ if self.game_won:
240
+ return
241
+ # A draw changes the waste, so a waste card held is put down.
242
+ if self.selected_pile and self.selected_pile[0] == WASTE:
243
+ self.selected_card = None
244
+ self.selected_pile = None
245
+ if self.stock:
246
+ for _ in range(min(3, len(self.stock))):
247
+ card = self.stock.pop()
248
+ card.flip()
249
+ self.waste.append(card)
250
+ self.moves += 1
251
+ elif self.waste:
252
+ while self.waste:
253
+ card = self.waste.pop()
254
+ card.flip()
255
+ self.stock.append(card)
256
+ self.score = max(0, self.score - 100)
257
+
258
+ def can_place_on_tableau(self, card: Card, target: list[Card]) -> bool:
259
+ if not target:
260
+ return card.rank == "K"
261
+ top = target[-1]
262
+ return top.face_up and top.color != card.color and top.value == card.value + 1
263
+
264
+ def can_place_on_foundation(self, card: Card, index: int) -> bool:
265
+ pile = self.foundation[index]
266
+ if not pile:
267
+ return card.rank == "A"
268
+ top = pile[-1]
269
+ return top.suit == card.suit and top.value == card.value - 1
270
+
271
+ def handle_card_click(self, card: Card, pile_type: str, pile_index: int,
272
+ card_index: int) -> None:
273
+ # A won table is finished.
274
+ if self.game_won or not card.face_up:
275
+ return
276
+ last = self._last_click
277
+ double = (last is not None and last[0] is card and last[1] == pile_type
278
+ and last[2] == pile_index and self.now - last[4] < DOUBLE_CLICK_MS)
279
+ self._last_click = (card, pile_type, pile_index, card_index, self.now)
280
+ if double:
281
+ self._last_click = None
282
+ if self.auto_move_to_foundation(card, pile_type, pile_index):
283
+ return
284
+ if not self.selected_card:
285
+ self.selected_card = card
286
+ self.selected_pile = (pile_type, pile_index, card_index)
287
+ return
288
+ if self.selected_card is card:
289
+ self.selected_card = None
290
+ self.selected_pile = None
291
+ return
292
+ self.try_move(pile_type, pile_index)
293
+
294
+ def auto_move_to_foundation(self, card: Card, pile_type: str, pile_index: int) -> bool:
295
+ for fi in range(4):
296
+ if self.can_place_on_foundation(card, fi):
297
+ if pile_type == TABLEAU:
298
+ source = self.tableau[pile_index]
299
+ # Only a column's top card goes home.
300
+ if not source or source[-1] is not card:
301
+ return False
302
+ self.selected_card = card
303
+ self.selected_pile = (TABLEAU, pile_index,
304
+ next(i for i, c in enumerate(source) if c is card))
305
+ elif pile_type == WASTE:
306
+ self.selected_card = card
307
+ self.selected_pile = (WASTE, 0, len(self.waste) - 1)
308
+ else:
309
+ return False
310
+ self.try_move(FOUNDATION, fi)
311
+ return True
312
+ return False
313
+
314
+ def try_move(self, target_type: str, target_index: int) -> None:
315
+ if self.game_won or not self.selected_pile:
316
+ return
317
+ source_type, source_index, card_index = self.selected_pile
318
+ moved = False
319
+ change = 0
320
+ if target_type == TABLEAU:
321
+ target = self.tableau[target_index]
322
+ if self.can_place_on_tableau(self.selected_card, target):
323
+ if source_type == TABLEAU:
324
+ source = self.tableau[source_index]
325
+ # ``splice(cardIndex)``: everything from there, onto the
326
+ # target, which may be the same column.
327
+ moving = source[card_index:]
328
+ del source[card_index:]
329
+ self.tableau[target_index].extend(moving)
330
+ if source and not source[-1].face_up:
331
+ source[-1].flip()
332
+ change += 5
333
+ elif source_type == WASTE:
334
+ self.tableau[target_index].append(self._pop(self.waste))
335
+ change += 5
336
+ elif source_type == FOUNDATION:
337
+ self.tableau[target_index].append(self._pop(self.foundation[source_index]))
338
+ change -= 15
339
+ moved = True
340
+ self.moves += 1
341
+ elif target_type == FOUNDATION:
342
+ # One card at a time, and only a column's top card; a card already
343
+ # on a foundation stays where it is.
344
+ is_top = (source_type != TABLEAU
345
+ or card_index == len(self.tableau[source_index]) - 1)
346
+ if (source_type != FOUNDATION and is_top
347
+ and self.can_place_on_foundation(self.selected_card, target_index)):
348
+ if source_type == TABLEAU:
349
+ source = self.tableau[source_index]
350
+ self.foundation[target_index].append(self._pop(source))
351
+ change += 10
352
+ if source and not source[-1].face_up:
353
+ source[-1].flip()
354
+ change += 5
355
+ elif source_type == WASTE:
356
+ self.foundation[target_index].append(self._pop(self.waste))
357
+ change += 10
358
+ moved = True
359
+ self.moves += 1
360
+ if change:
361
+ self.score = max(0, self.score + change)
362
+ self.selected_card = None
363
+ self.selected_pile = None
364
+ if moved and self.check_win():
365
+ self.game_won = True
366
+ self._clear_interval(self.timer_interval)
367
+ self.timer_interval = None
368
+ # The time to the win, not the timer's last tick.
369
+ self.elapsed_seconds = math.floor((self.now - self.time_started) / 1000)
370
+ bonus = time_bonus_for(self.elapsed_seconds)
371
+ self.score += bonus
372
+ self.wins.append(Win(self.score, clock_text(self.elapsed_seconds), bonus,
373
+ self.now + WIN_SCREEN_MS))
374
+ self.win_count += 1
375
+
376
+ @staticmethod
377
+ def _pop(pile: list):
378
+ """``Array.pop``: undefined from an empty pile, here None."""
379
+ return pile.pop() if pile else None
380
+
381
+ def deselect(self) -> None:
382
+ """A click on the felt, away from every pile."""
383
+ if self.selected_card:
384
+ self.selected_card = None
385
+ self.selected_pile = None
386
+
387
+ def check_win(self) -> bool:
388
+ return all(len(p) == 13 for p in self.foundation)
389
+
390
+ # -- What the screen asks --------------------------------------------
391
+
392
+ @property
393
+ def time_text(self) -> str:
394
+ return clock_text(self.elapsed_seconds)
395
+
396
+ def due_win(self) -> Win | None:
397
+ """The oldest win screen whose 400 ms are up, taken off the list."""
398
+ if self.wins and self.wins[0].due <= self.now:
399
+ return self.wins.pop(0)
400
+ return None
401
+
402
+
403
+ __all__ = ["FOUNDATION", "TABLEAU", "WASTE", "Card", "Game", "Win", "clock_text",
404
+ "new_deck", "shuffle", "time_bonus_for"]