magmacrunch-threes 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.
- magmacrunch_threes-0.1.0.dist-info/METADATA +75 -0
- magmacrunch_threes-0.1.0.dist-info/RECORD +13 -0
- magmacrunch_threes-0.1.0.dist-info/WHEEL +4 -0
- magmacrunch_threes-0.1.0.dist-info/entry_points.txt +5 -0
- magmacrunch_threes-0.1.0.dist-info/licenses/LICENSE +75 -0
- magmacrunch_threes-0.1.0.dist-info/licenses/NOTICE +36 -0
- threes/__init__.py +0 -0
- threes/__main__.py +29 -0
- threes/app.py +104 -0
- threes/arcade.py +46 -0
- threes/rules.py +238 -0
- threes/scenes.py +524 -0
- threes/theme.py +82 -0
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: magmacrunch-threes
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: THREES - slide, merge, survive. Terminal version.
|
|
5
|
+
Project-URL: Homepage, https://magmacrunch.com/arcade/threes/
|
|
6
|
+
Author: magmacrunch media
|
|
7
|
+
License-Expression: PolyForm-Noncommercial-1.0.0
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
License-File: NOTICE
|
|
10
|
+
Keywords: arcade,games,puzzle,terminal,tiles,tui
|
|
11
|
+
Requires-Python: >=3.10
|
|
12
|
+
Requires-Dist: magmacrunch>=0.7.0
|
|
13
|
+
Provides-Extra: dev
|
|
14
|
+
Requires-Dist: pytest>=7.0; extra == 'dev'
|
|
15
|
+
Requires-Dist: ruff>=0.6; extra == 'dev'
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
|
|
18
|
+
# THREES (terminal)
|
|
19
|
+
|
|
20
|
+
Slide, merge, survive, in a terminal. The second version of the game beside
|
|
21
|
+
`web/`, on the [magmacrunch](https://github.com/magmacrunch-media/magmacrunch)
|
|
22
|
+
engine's terminal backend: a cabinet in the magmacrunch arcade and its own
|
|
23
|
+
command, the same either way.
|
|
24
|
+
|
|
25
|
+
```
|
|
26
|
+
pip install -e ".[dev]"
|
|
27
|
+
python -m threes
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## Keys
|
|
31
|
+
|
|
32
|
+
| key | |
|
|
33
|
+
|---|---|
|
|
34
|
+
| arrows (or WASD, hjkl) | slide every tile one step |
|
|
35
|
+
| `R` | new game |
|
|
36
|
+
| `Esc` | the title (from the title, back to the arcade) |
|
|
37
|
+
| `Q` | quit |
|
|
38
|
+
|
|
39
|
+
1 + 2 makes 3, and from there same plus same; 1 + 1 and 2 + 2 do not merge.
|
|
40
|
+
The new tile comes in on the edge you slid away from, and lights up for a
|
|
41
|
+
moment so you can see where it landed.
|
|
42
|
+
|
|
43
|
+
## It is the browser's game
|
|
44
|
+
|
|
45
|
+
`threes/rules.py` is `web/js/game.js` plus the part of adenosine-puzzle's
|
|
46
|
+
`createGame` it relies on: a move is the left slide with the board rotated
|
|
47
|
+
round it, and only a move that changed something brings a tile and counts.
|
|
48
|
+
`tests/test_oracle.py` checks it: `tools/js_oracle.mjs` loads the website's
|
|
49
|
+
`adenosine-puzzle.js` and `web/js/game.js` unmodified with `Math.random`
|
|
50
|
+
seeded, plays 300 games through the game's own `handleMove()`, and the test
|
|
51
|
+
replays every move through the port and requires the same board, score and
|
|
52
|
+
move count after each one, and the same answer to whether it moved at all.
|
|
53
|
+
|
|
54
|
+
The oracle needs the website, for the bundle. It finds it the way
|
|
55
|
+
`tools/link-shared.mjs` does: `../shared`, `$WEBSITE`, `../../website`,
|
|
56
|
+
`../../../web/website`. CI checks the website out beside the game.
|
|
57
|
+
|
|
58
|
+
The browser's choices are copied rather than improved, because both versions
|
|
59
|
+
share a scoreboard and a rule changed in one would make its scores mean
|
|
60
|
+
something else:
|
|
61
|
+
|
|
62
|
+
- **Three new tiles in four are 1s** (75% 1, 15% 2, 10% 3), and a 1 merges only
|
|
63
|
+
with a 2, so the board fills with 1s and a game lasts a few dozen moves.
|
|
64
|
+
The original Threes! deals 1s and 2s about evenly.
|
|
65
|
+
- **The score is the sum of every merge**, not the original's powers of three.
|
|
66
|
+
|
|
67
|
+
Change either in `web/js/game.js` and here together, and the oracle will hold
|
|
68
|
+
the two to each other.
|
|
69
|
+
|
|
70
|
+
Needs a 56x21 terminal.
|
|
71
|
+
|
|
72
|
+
## Licence
|
|
73
|
+
|
|
74
|
+
[PolyForm Noncommercial 1.0.0](LICENSE), as the rest of this repository. See
|
|
75
|
+
[NOTICE](NOTICE), which also says whose the name is.
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
threes/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
2
|
+
threes/__main__.py,sha256=v46QFdRGE5YVBElgywdA63vC0K9MwCJcbIVMYAND_Y4,955
|
|
3
|
+
threes/app.py,sha256=rygP4SX9KFPGXgLMzdrdJyTkki35MPIExbS4Nj383B8,3401
|
|
4
|
+
threes/arcade.py,sha256=sNPbtg50-QIGsRDMXG-X5e9plKmgXRwO3B4WxaLHZ-8,1229
|
|
5
|
+
threes/rules.py,sha256=TI22_B0Z6NDzbkRVypYHfSToeOjlM06js8zoSEVWmt8,8489
|
|
6
|
+
threes/scenes.py,sha256=iGnqgzYX_miiIr5U5gga6tchKEFswuk074guCTsGcBs,19334
|
|
7
|
+
threes/theme.py,sha256=CuzB7F5ltnyTALo9hm_d9yqzYvneHEY6VutL3rE_L68,2042
|
|
8
|
+
magmacrunch_threes-0.1.0.dist-info/METADATA,sha256=p9ZphwSNyDBWLBGnRwYK46vh1ZOE_m5CL870p1UScco,2811
|
|
9
|
+
magmacrunch_threes-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
|
|
10
|
+
magmacrunch_threes-0.1.0.dist-info/entry_points.txt,sha256=0jtbqYLaVJnCxXH_06LVemy8a27YWFak_CwQhDSp4z0,97
|
|
11
|
+
magmacrunch_threes-0.1.0.dist-info/licenses/LICENSE,sha256=dQ7s_huoOpXIV8Gtdt3ZVm4N2UofO4MvxlappsL14Q8,4640
|
|
12
|
+
magmacrunch_threes-0.1.0.dist-info/licenses/NOTICE,sha256=tTs1g_jul4JBtE4NAOKLs8M6fwalMg_j7APAl4nK8nY,1581
|
|
13
|
+
magmacrunch_threes-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
Required Notice: Copyright 2026 magmacrunch media (https://magmacrunch.com)
|
|
2
|
+
|
|
3
|
+
# PolyForm Noncommercial License 1.0.0
|
|
4
|
+
|
|
5
|
+
<https://polyformproject.org/licenses/noncommercial/1.0.0>
|
|
6
|
+
|
|
7
|
+
## Acceptance
|
|
8
|
+
|
|
9
|
+
In order to get any license under these terms, you must agree to them as both strict obligations and conditions to all your licenses.
|
|
10
|
+
|
|
11
|
+
## Copyright License
|
|
12
|
+
|
|
13
|
+
The licensor grants you a copyright license for the software to do everything you might do with the software that would otherwise infringe the licensor's copyright in it for any permitted purpose. However, you may only distribute the software according to [Distribution License](#distribution-license) and make changes or new works based on the software according to [Changes and New Works License](#changes-and-new-works-license).
|
|
14
|
+
|
|
15
|
+
## Distribution License
|
|
16
|
+
|
|
17
|
+
The licensor grants you an additional copyright license to distribute copies of the software. Your license to distribute covers distributing the software with changes and new works permitted by [Changes and New Works License](#changes-and-new-works-license).
|
|
18
|
+
|
|
19
|
+
## Notices
|
|
20
|
+
|
|
21
|
+
You must ensure that anyone who gets a copy of any part of the software from you also gets a copy of these terms or the URL for them above, as well as copies of any plain-text lines beginning with `Required Notice:` that the licensor provided with the software. For example:
|
|
22
|
+
|
|
23
|
+
> Required Notice: Copyright Yoyodyne, Inc. (http://example.com)
|
|
24
|
+
|
|
25
|
+
## Changes and New Works License
|
|
26
|
+
|
|
27
|
+
The licensor grants you an additional copyright license to make changes and new works based on the software for any permitted purpose.
|
|
28
|
+
|
|
29
|
+
## Patent License
|
|
30
|
+
|
|
31
|
+
The licensor grants you a patent license for the software that covers patent claims the licensor can license, or becomes able to license, that you would infringe by using the software.
|
|
32
|
+
|
|
33
|
+
## Noncommercial Purposes
|
|
34
|
+
|
|
35
|
+
Any noncommercial purpose is a permitted purpose.
|
|
36
|
+
|
|
37
|
+
## Personal Uses
|
|
38
|
+
|
|
39
|
+
Personal use for research, experiment, and testing for the benefit of public knowledge, personal study, private entertainment, hobby projects, amateur pursuits, or religious observance, without any anticipated commercial application, is use for a permitted purpose.
|
|
40
|
+
|
|
41
|
+
## Noncommercial Organizations
|
|
42
|
+
|
|
43
|
+
Use by any charitable organization, educational institution, public research organization, public safety or health organization, environmental protection organization, or government institution is use for a permitted purpose regardless of the source of funding or obligations resulting from the funding.
|
|
44
|
+
|
|
45
|
+
## Fair Use
|
|
46
|
+
|
|
47
|
+
You may have "fair use" rights for the software under the law. These terms do not limit them.
|
|
48
|
+
|
|
49
|
+
## No Other Rights
|
|
50
|
+
|
|
51
|
+
These terms do not allow you to sublicense or transfer any of your licenses to anyone else, or prevent the licensor from granting licenses to anyone else. These terms do not imply any other licenses.
|
|
52
|
+
|
|
53
|
+
## Patent Defense
|
|
54
|
+
|
|
55
|
+
If you make any written claim that the software infringes or contributes to infringement of any patent, your patent license for the software granted under these terms ends immediately. If your company makes such a claim, your patent license ends immediately for work on behalf of your company.
|
|
56
|
+
|
|
57
|
+
## Violations
|
|
58
|
+
|
|
59
|
+
The first time you are notified in writing that you have violated any of these terms, or done anything with the software not covered by your licenses, your licenses can nonetheless continue if you come into full compliance with these terms, and take practical steps to correct past violations, within 32 days of receiving notice. Otherwise, all your licenses end immediately.
|
|
60
|
+
|
|
61
|
+
## No Liability
|
|
62
|
+
|
|
63
|
+
***As far as the law allows, the software comes as is, without any warranty or condition, and the licensor will not be liable to you for any damages arising out of these terms or the use or nature of the software, under any kind of legal claim.***
|
|
64
|
+
|
|
65
|
+
## Definitions
|
|
66
|
+
|
|
67
|
+
The **licensor** is the individual or entity offering these terms, and the **software** is the software the licensor makes available under these terms.
|
|
68
|
+
|
|
69
|
+
**You** refers to the individual or entity agreeing to these terms.
|
|
70
|
+
|
|
71
|
+
**Your company** is any legal entity, sole proprietorship, or other kind of organization that you work for, plus all organizations that have control over, are under the control of, or are under common control with that organization. **Control** means ownership of substantially all the assets of an entity, or the power to direct its management and policies by vote, contract, or otherwise. Control can be direct or indirect.
|
|
72
|
+
|
|
73
|
+
**Your licenses** are all the licenses granted to you for the software under these terms.
|
|
74
|
+
|
|
75
|
+
**Use** means anything you do with the software requiring one of your licenses.
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
threes
|
|
2
|
+
Copyright 2026 magmacrunch media
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
THE LICENCE
|
|
6
|
+
|
|
7
|
+
Everything in this repository -- the game in web/, its terminal version in
|
|
8
|
+
tui/, its tests, the tools and the
|
|
9
|
+
documentation -- is licensed under the PolyForm Noncommercial License 1.0.0, in the
|
|
10
|
+
LICENSE file beside this one.
|
|
11
|
+
|
|
12
|
+
Read it, learn from it, build on it, play with it. Any noncommercial purpose is
|
|
13
|
+
permitted, and that includes personal projects, teaching and research. What is not
|
|
14
|
+
permitted is commercial use: selling the game or a derivative of it, shipping it inside
|
|
15
|
+
a product, or running it as part of a business.
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
THE NAME IS NOT OURS
|
|
19
|
+
|
|
20
|
+
Threes! is Sirvo's game (Asher Vollmer, Greg Wohlwend and Jimmy Hinson, 2014), and
|
|
21
|
+
its name is theirs. This is an unofficial fan implementation, played for free in the
|
|
22
|
+
magmacrunch arcade, and is not affiliated with or endorsed by Sirvo. Nothing here
|
|
23
|
+
claims the name, and the licence above grants no rights in it. What is licensed is
|
|
24
|
+
this implementation only: the code and the arcade's presentation.
|
|
25
|
+
|
|
26
|
+
What is reserved: the magmacrunch name and marks and the visual design of the arcade.
|
|
27
|
+
If you want to use any of it, ask.
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
THIRD-PARTY COMPONENTS
|
|
31
|
+
|
|
32
|
+
Fonts are loaded from Google Fonts under the SIL Open Font License 1.1 rather than
|
|
33
|
+
shipped here as files.
|
|
34
|
+
|
|
35
|
+
The page loads adenosine-puzzle.js, adenosine-score-client.js, arcade-base.css, puzzle/puzzle-base.css, puzzle/puzzle-grid.css, puzzle/puzzle-modals.css, puzzle/puzzle-responsive.css, score-server.js from the website's arcade/shared/.
|
|
36
|
+
Those are part of the magmacrunch.com repository and adenosine, and are not copied here.
|
threes/__init__.py
ADDED
|
File without changes
|
threes/__main__.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""``python -m threes`` -- play THREES in a terminal."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def main() -> None:
|
|
9
|
+
parser = argparse.ArgumentParser(
|
|
10
|
+
prog="threes", description="THREES - slide, merge, survive.")
|
|
11
|
+
parser.add_argument("--seed", type=int, default=None,
|
|
12
|
+
help="fix the session's tiles, for a reproducible one")
|
|
13
|
+
parser.add_argument("--play", action="store_true",
|
|
14
|
+
help="skip the title screen")
|
|
15
|
+
parser.add_argument(
|
|
16
|
+
"--ascii", action="store_true", dest="ascii_only",
|
|
17
|
+
help="draw with plain ASCII instead of block and arrow glyphs. "
|
|
18
|
+
"Detected automatically from the terminal's encoding; this "
|
|
19
|
+
"forces it. MAGMACRUNCH_ASCII=1 says the same for every cabinet.",
|
|
20
|
+
)
|
|
21
|
+
args = parser.parse_args()
|
|
22
|
+
|
|
23
|
+
from threes.app import run
|
|
24
|
+
|
|
25
|
+
run(args.seed, args.play, args.ascii_only)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
if __name__ == "__main__":
|
|
29
|
+
main()
|
threes/app.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""Wiring -- what outlives a single game, and how the screens reach it.
|
|
2
|
+
|
|
3
|
+
Everything that draws lives in :mod:`threes.scenes`; everything that decides
|
|
4
|
+
lives in :mod:`threes.rules`. This holds the score table and the source of
|
|
5
|
+
tiles. **The terminal is not owned here**: it belongs to a ``TuiHost``, which
|
|
6
|
+
is what lets this run as its own command or be seated by the arcade.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import random
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from magmacrunch.engine.scores import ScoreBook
|
|
15
|
+
|
|
16
|
+
from threes.arcade import INFO
|
|
17
|
+
from threes.scenes import GameScene, TitleScene
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class ThreesApp:
|
|
21
|
+
"""A session of THREES, drawing on somebody else's terminal."""
|
|
22
|
+
|
|
23
|
+
def __init__(self, host: Any, seed: int | None = None,
|
|
24
|
+
scores: ScoreBook | None = None):
|
|
25
|
+
self.host = host
|
|
26
|
+
#: Where each game's tiles come from. Seeded, so ``--seed`` replays a
|
|
27
|
+
#: whole session.
|
|
28
|
+
self.rng = random.Random(seed)
|
|
29
|
+
#: The browser's board -- see arcade.INFO.
|
|
30
|
+
self.scores = scores or ScoreBook(INFO.scoreboard)
|
|
31
|
+
self.initials = "AAA"
|
|
32
|
+
self.last_rank: int | None = None
|
|
33
|
+
self.root_scene = TitleScene(self)
|
|
34
|
+
|
|
35
|
+
@property
|
|
36
|
+
def renderer(self):
|
|
37
|
+
return self.host.renderer
|
|
38
|
+
|
|
39
|
+
def new_rand(self):
|
|
40
|
+
"""A tile source for one game, as ``Math.random`` is to the web."""
|
|
41
|
+
return random.Random(self.rng.randrange(1 << 32)).random
|
|
42
|
+
|
|
43
|
+
# -- Flow --------------------------------------------------------
|
|
44
|
+
|
|
45
|
+
def start_game(self) -> None:
|
|
46
|
+
self.host.push_scene(GameScene(self))
|
|
47
|
+
|
|
48
|
+
def show_scores(self) -> None:
|
|
49
|
+
from threes.scenes import ScoresScene
|
|
50
|
+
|
|
51
|
+
self.host.push_scene(ScoresScene(self))
|
|
52
|
+
|
|
53
|
+
def show_rules(self) -> None:
|
|
54
|
+
from threes.scenes import RulesScene
|
|
55
|
+
|
|
56
|
+
self.host.push_scene(RulesScene(self))
|
|
57
|
+
|
|
58
|
+
def enter_initials(self, score: int, extra: dict) -> None:
|
|
59
|
+
from threes.scenes import InitialsScene
|
|
60
|
+
|
|
61
|
+
self.host.push_scene(InitialsScene(self, score, extra))
|
|
62
|
+
|
|
63
|
+
def to_title(self) -> None:
|
|
64
|
+
self.host.pop_scene()
|
|
65
|
+
|
|
66
|
+
def leave(self) -> None:
|
|
67
|
+
"""Pop the title: alone that ends the session; seated, it returns to
|
|
68
|
+
the arcade. The game does not need to know which."""
|
|
69
|
+
self.host.pop_scene()
|
|
70
|
+
|
|
71
|
+
# -- Scores ------------------------------------------------------
|
|
72
|
+
|
|
73
|
+
@property
|
|
74
|
+
def best(self) -> int:
|
|
75
|
+
return self.scores.best()
|
|
76
|
+
|
|
77
|
+
def qualifies(self, score: int) -> bool:
|
|
78
|
+
return score > 0 and self.scores.qualifies(score)
|
|
79
|
+
|
|
80
|
+
def record(self, score: int, initials: str | None = None,
|
|
81
|
+
extra: dict | None = None):
|
|
82
|
+
self.initials = initials or self.initials
|
|
83
|
+
result = self.scores.save(self.initials, score, **(extra or {}))
|
|
84
|
+
self.last_rank = result.rank
|
|
85
|
+
return result
|
|
86
|
+
|
|
87
|
+
@property
|
|
88
|
+
def scene(self):
|
|
89
|
+
return self.host.scene
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def run(seed: int | None = None, skip_title: bool = False,
|
|
93
|
+
ascii_only: bool = False) -> None:
|
|
94
|
+
"""Play THREES as its own command."""
|
|
95
|
+
from magmacrunch.engine.core.tui_host import TuiHost
|
|
96
|
+
from magmacrunch.engine.ui.glyphs import Glyphs
|
|
97
|
+
|
|
98
|
+
host = TuiHost(title=INFO.title, fps=INFO.fps, hold_ms=INFO.hold_ms,
|
|
99
|
+
glyphs=Glyphs.detect(ascii_only=ascii_only))
|
|
100
|
+
app = ThreesApp(host, seed)
|
|
101
|
+
host.push_scene(app.root_scene)
|
|
102
|
+
if skip_title:
|
|
103
|
+
host.push_scene(GameScene(app))
|
|
104
|
+
host.run()
|
threes/arcade.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""What the arcade needs to know to launch this game.
|
|
2
|
+
|
|
3
|
+
Kept tiny: a menu loads one of these per installed game just to draw a card,
|
|
4
|
+
and should not pay for the rules or the screens to do it.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from magmacrunch.engine.arcade import GameInfo
|
|
12
|
+
|
|
13
|
+
from threes import theme
|
|
14
|
+
|
|
15
|
+
INFO = GameInfo(
|
|
16
|
+
key="threes",
|
|
17
|
+
title="THREES",
|
|
18
|
+
blurb="Slide. Merge. Survive. 1 and 2 make 3, then same plus same.",
|
|
19
|
+
# Nothing moves between presses but a new tile's flash and the clock, so
|
|
20
|
+
# this is only how promptly those draw.
|
|
21
|
+
fps=20,
|
|
22
|
+
# Edge input: a slide is a press, and a held arrow is the terminal
|
|
23
|
+
# repeating it. Nothing reads held state.
|
|
24
|
+
hold_ms=0,
|
|
25
|
+
min_cols=theme.MIN_COLS,
|
|
26
|
+
min_rows=theme.MIN_ROWS,
|
|
27
|
+
# The browser's board is `threes` too (AdPuzzle.createScoring('threes')),
|
|
28
|
+
# so the key is the name and needs no override.
|
|
29
|
+
accent=theme.ACCENT,
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class ThreesGame:
|
|
34
|
+
"""Satisfies :class:`magmacrunch.engine.arcade.ArcadeGame`."""
|
|
35
|
+
|
|
36
|
+
info = INFO
|
|
37
|
+
|
|
38
|
+
def start(self, host: Any) -> Any:
|
|
39
|
+
from threes.app import ThreesApp
|
|
40
|
+
|
|
41
|
+
return ThreesApp(host).root_scene
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
GAME = ThreesGame()
|
|
45
|
+
|
|
46
|
+
__all__ = ["GAME", "INFO", "ThreesGame"]
|
threes/rules.py
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
"""The rules, ported from ``web/js/game.js`` and the adenosine-puzzle base it
|
|
2
|
+
extends, line for line.
|
|
3
|
+
|
|
4
|
+
Nothing here imports the engine or a terminal, so it runs on a bare
|
|
5
|
+
interpreter, which ``tests/test_oracle.py`` relies on: it replays the
|
|
6
|
+
browser's own games through :class:`Board` and requires the same grid,
|
|
7
|
+
score and move count after every move.
|
|
8
|
+
|
|
9
|
+
Two halves, because the browser has two. ``game.js`` supplies the Threes
|
|
10
|
+
parts: nine starting tiles, the merge rule, the one-step slide to the left,
|
|
11
|
+
spawning on the edge the board moved away from, at the end of a row or
|
|
12
|
+
column that moved, and the game-over test.
|
|
13
|
+
adenosine-puzzle's ``createGame`` supplies the rest: a move is the left
|
|
14
|
+
slide with the board rotated round it, and only a move that changed
|
|
15
|
+
something spawns a tile and counts.
|
|
16
|
+
|
|
17
|
+
The browser's quirks are kept on purpose, because they are the game people
|
|
18
|
+
have been playing: the score is the plain sum of every merge (not the
|
|
19
|
+
original's powers of three), and the tiles slide by scanning the row once,
|
|
20
|
+
left to right.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
from collections.abc import Callable
|
|
26
|
+
from dataclasses import dataclass, field
|
|
27
|
+
|
|
28
|
+
SIZE = 4
|
|
29
|
+
INITIAL_TILE_COUNT = 9
|
|
30
|
+
# The bag: four each of 1, 2 and 3, shuffled and dealt until empty, then
|
|
31
|
+
# refilled. game.js deals the opening nine and every new tile from it.
|
|
32
|
+
BAG = (1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3)
|
|
33
|
+
|
|
34
|
+
DIRECTIONS = ("up", "down", "left", "right")
|
|
35
|
+
|
|
36
|
+
Grid = list[list[int]]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def can_merge(a: int, b: int) -> bool:
|
|
40
|
+
if a == 0 or b == 0:
|
|
41
|
+
return False
|
|
42
|
+
if a == 1 and b == 2:
|
|
43
|
+
return True
|
|
44
|
+
if a == 2 and b == 1:
|
|
45
|
+
return True
|
|
46
|
+
return a == b and a >= 3
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def merge(a: int, b: int) -> int:
|
|
50
|
+
if (a == 1 and b == 2) or (a == 2 and b == 1):
|
|
51
|
+
return 3
|
|
52
|
+
return a + b
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def rotate(grid: Grid, times: int = 1) -> Grid:
|
|
56
|
+
"""``PuzzleGrid.rotate``: clockwise, ``times`` quarter turns."""
|
|
57
|
+
for _ in range(times):
|
|
58
|
+
out = [[0] * SIZE for _ in range(SIZE)]
|
|
59
|
+
for r in range(SIZE):
|
|
60
|
+
for c in range(SIZE):
|
|
61
|
+
out[c][SIZE - 1 - r] = grid[r][c]
|
|
62
|
+
grid = out
|
|
63
|
+
return grid
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def empty_cells(grid: Grid) -> list[tuple[int, int]]:
|
|
67
|
+
"""Row by row, left to right, as ``PuzzleGrid.getEmptyCells`` lists them:
|
|
68
|
+
the order matters, because a random index is taken into it."""
|
|
69
|
+
return [(r, c) for r in range(SIZE) for c in range(SIZE) if grid[r][c] == 0]
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def max_value(grid: Grid) -> int:
|
|
73
|
+
return max(max(row) for row in grid)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@dataclass(eq=False)
|
|
77
|
+
class Board:
|
|
78
|
+
"""One game. ``rand`` is the game's ``Math.random``: pass a seeded one to
|
|
79
|
+
replay a game exactly."""
|
|
80
|
+
|
|
81
|
+
rand: Callable[[], float]
|
|
82
|
+
grid: Grid = field(default_factory=lambda: [[0] * SIZE for _ in range(SIZE)])
|
|
83
|
+
score: int = 0
|
|
84
|
+
moves: int = 0
|
|
85
|
+
over: bool = False
|
|
86
|
+
last_direction: str | None = None
|
|
87
|
+
# Which rows (left/right) or columns (up/down) the last move changed: the
|
|
88
|
+
# new tile only comes in at the end of one of those.
|
|
89
|
+
moved_lines: list[bool] | None = None
|
|
90
|
+
bag: list[int] = field(default_factory=list)
|
|
91
|
+
|
|
92
|
+
# -- Setup ------------------------------------------------------------
|
|
93
|
+
|
|
94
|
+
def start(self) -> Board:
|
|
95
|
+
"""``init()``: an empty board, then the nine starting tiles."""
|
|
96
|
+
self.grid = [[0] * SIZE for _ in range(SIZE)]
|
|
97
|
+
self.score = 0
|
|
98
|
+
self.moves = 0
|
|
99
|
+
self.over = False
|
|
100
|
+
self.last_direction = None
|
|
101
|
+
self.moved_lines = None
|
|
102
|
+
self._add_initial_tiles()
|
|
103
|
+
return self
|
|
104
|
+
|
|
105
|
+
def next_value(self) -> int:
|
|
106
|
+
"""``nextValue``: the top of the bag, refilled and shuffled (Fisher-Yates
|
|
107
|
+
from the back, one draw per swap) when it runs out."""
|
|
108
|
+
if not self.bag:
|
|
109
|
+
self.bag = list(BAG)
|
|
110
|
+
for i in range(len(self.bag) - 1, 0, -1):
|
|
111
|
+
j = int(self.rand() * (i + 1))
|
|
112
|
+
self.bag[i], self.bag[j] = self.bag[j], self.bag[i]
|
|
113
|
+
return self.bag.pop()
|
|
114
|
+
|
|
115
|
+
def _add_initial_tiles(self) -> None:
|
|
116
|
+
# Every value is drawn before any cell is, as game.js does it, from a
|
|
117
|
+
# fresh bag.
|
|
118
|
+
self.bag = []
|
|
119
|
+
values = [self.next_value() for _ in range(INITIAL_TILE_COUNT)]
|
|
120
|
+
cells = empty_cells(self.grid)
|
|
121
|
+
for value in values:
|
|
122
|
+
if not cells:
|
|
123
|
+
break
|
|
124
|
+
row, col = cells.pop(int(self.rand() * len(cells)))
|
|
125
|
+
self.grid[row][col] = value
|
|
126
|
+
|
|
127
|
+
# -- A move -----------------------------------------------------------
|
|
128
|
+
|
|
129
|
+
def move(self, direction: str) -> bool:
|
|
130
|
+
"""``handleMove``. Returns whether anything moved; a move that did not
|
|
131
|
+
change the board spawns nothing and does not count."""
|
|
132
|
+
if self.over:
|
|
133
|
+
return False
|
|
134
|
+
if direction not in DIRECTIONS:
|
|
135
|
+
raise ValueError(f"not a direction: {direction!r}")
|
|
136
|
+
before = [row[:] for row in self.grid]
|
|
137
|
+
self._move_in(direction)
|
|
138
|
+
if self.grid == before:
|
|
139
|
+
return False
|
|
140
|
+
vertical = direction in ("up", "down")
|
|
141
|
+
self.moved_lines = [
|
|
142
|
+
any((before[j][i] if vertical else before[i][j])
|
|
143
|
+
!= (self.grid[j][i] if vertical else self.grid[i][j]) for j in range(SIZE))
|
|
144
|
+
for i in range(SIZE)
|
|
145
|
+
]
|
|
146
|
+
self.moves += 1
|
|
147
|
+
self.last_direction = direction
|
|
148
|
+
self._add_random_tile()
|
|
149
|
+
self._check_state()
|
|
150
|
+
return True
|
|
151
|
+
|
|
152
|
+
def _move_in(self, direction: str) -> None:
|
|
153
|
+
if direction == "left":
|
|
154
|
+
self._move_left()
|
|
155
|
+
elif direction == "right":
|
|
156
|
+
self.grid = rotate(self.grid, 2)
|
|
157
|
+
self._move_left()
|
|
158
|
+
self.grid = rotate(self.grid, 2)
|
|
159
|
+
elif direction == "up":
|
|
160
|
+
self.grid = rotate(self.grid, 3)
|
|
161
|
+
self._move_left()
|
|
162
|
+
self.grid = rotate(self.grid, 1)
|
|
163
|
+
else:
|
|
164
|
+
self.grid = rotate(self.grid, 1)
|
|
165
|
+
self._move_left()
|
|
166
|
+
self.grid = rotate(self.grid, 3)
|
|
167
|
+
|
|
168
|
+
def _move_left(self) -> None:
|
|
169
|
+
board = self.grid
|
|
170
|
+
for r in range(SIZE):
|
|
171
|
+
merged = [False] * SIZE
|
|
172
|
+
for c in range(1, SIZE):
|
|
173
|
+
if board[r][c] == 0:
|
|
174
|
+
continue
|
|
175
|
+
target = c - 1
|
|
176
|
+
if board[r][target] == 0:
|
|
177
|
+
board[r][target] = board[r][c]
|
|
178
|
+
board[r][c] = 0
|
|
179
|
+
elif not merged[target] and can_merge(board[r][target], board[r][c]):
|
|
180
|
+
val = merge(board[r][target], board[r][c])
|
|
181
|
+
self.score += val
|
|
182
|
+
board[r][target] = val
|
|
183
|
+
board[r][c] = 0
|
|
184
|
+
merged[target] = True
|
|
185
|
+
|
|
186
|
+
def spawn_edge(self) -> list[tuple[int, int]]:
|
|
187
|
+
"""The edge the last move pulled away from, where the next tile comes
|
|
188
|
+
in. Also what the screen marks, so a player can see it coming."""
|
|
189
|
+
d = self.last_direction
|
|
190
|
+
if d == "up":
|
|
191
|
+
return [(SIZE - 1, c) for c in range(SIZE)]
|
|
192
|
+
if d == "down":
|
|
193
|
+
return [(0, c) for c in range(SIZE)]
|
|
194
|
+
if d == "left":
|
|
195
|
+
return [(r, SIZE - 1) for r in range(SIZE)]
|
|
196
|
+
if d == "right":
|
|
197
|
+
return [(r, 0) for r in range(SIZE)]
|
|
198
|
+
return empty_cells(self.grid)
|
|
199
|
+
|
|
200
|
+
def _add_random_tile(self) -> None:
|
|
201
|
+
vertical = self.last_direction in ("up", "down")
|
|
202
|
+
empty = [(r, c) for r, c in self.spawn_edge()
|
|
203
|
+
if self.grid[r][c] == 0
|
|
204
|
+
and (self.moved_lines is None or self.moved_lines[c if vertical else r])]
|
|
205
|
+
if not empty:
|
|
206
|
+
empty = empty_cells(self.grid)
|
|
207
|
+
if not empty:
|
|
208
|
+
return
|
|
209
|
+
row, col = empty[int(self.rand() * len(empty))]
|
|
210
|
+
self.grid[row][col] = self.next_value()
|
|
211
|
+
|
|
212
|
+
# -- The end ----------------------------------------------------------
|
|
213
|
+
|
|
214
|
+
def _check_state(self) -> None:
|
|
215
|
+
if empty_cells(self.grid):
|
|
216
|
+
return
|
|
217
|
+
if self.has_merges():
|
|
218
|
+
return
|
|
219
|
+
self.over = True
|
|
220
|
+
|
|
221
|
+
def has_merges(self) -> bool:
|
|
222
|
+
g = self.grid
|
|
223
|
+
for r in range(SIZE):
|
|
224
|
+
for c in range(SIZE):
|
|
225
|
+
v = g[r][c]
|
|
226
|
+
if c < SIZE - 1 and can_merge(v, g[r][c + 1]):
|
|
227
|
+
return True
|
|
228
|
+
if r < SIZE - 1 and can_merge(v, g[r + 1][c]):
|
|
229
|
+
return True
|
|
230
|
+
return False
|
|
231
|
+
|
|
232
|
+
@property
|
|
233
|
+
def high_tile(self) -> int:
|
|
234
|
+
return max_value(self.grid)
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
__all__ = ["DIRECTIONS", "INITIAL_TILE_COUNT", "SIZE", "Board", "can_merge",
|
|
238
|
+
"empty_cells", "max_value", "merge", "rotate"]
|
threes/scenes.py
ADDED
|
@@ -0,0 +1,524 @@
|
|
|
1
|
+
"""The screens, as scenes.
|
|
2
|
+
|
|
3
|
+
Modality is the stack, not a flag, which is the engine's own rule.
|
|
4
|
+
:class:`TitleScene` sits at the bottom; a game, the rules and the table are
|
|
5
|
+
pushed over it and popped back.
|
|
6
|
+
|
|
7
|
+
**Every control is a press**, and a move is the whole of a turn: nothing
|
|
8
|
+
here runs on the clock except the game timer and the flash on a new tile.
|
|
9
|
+
That makes this the simplest kind of port, and it is why the screen can call
|
|
10
|
+
:meth:`threes.rules.Board.move` directly with no frame bookkeeping.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import textwrap
|
|
16
|
+
from dataclasses import replace
|
|
17
|
+
|
|
18
|
+
from magmacrunch.engine import scores
|
|
19
|
+
from magmacrunch.engine.ui import bigtext
|
|
20
|
+
from magmacrunch.engine.ui.menu import Menu
|
|
21
|
+
from magmacrunch.engine.ui.theme import DEFAULT_THEME
|
|
22
|
+
|
|
23
|
+
from threes import rules, theme
|
|
24
|
+
|
|
25
|
+
MENU_HELP = "↑↓ choose Enter select Q quit"
|
|
26
|
+
ARCADE_HELP = "Esc back to the arcade"
|
|
27
|
+
OVER_HELP = "Enter play again Esc title"
|
|
28
|
+
RULES_HELP = "↑↓ scroll any other key goes back"
|
|
29
|
+
INITIALS_HELP = "Enter confirms Backspace fixes"
|
|
30
|
+
SCORES_HELP = "any key goes back"
|
|
31
|
+
|
|
32
|
+
MOVE_KEYS = {
|
|
33
|
+
"up": "up", "w": "up", "k": "up",
|
|
34
|
+
"down": "down", "s": "down", "j": "down",
|
|
35
|
+
"left": "left", "a": "left", "h": "left",
|
|
36
|
+
"right": "right", "d": "right", "l": "right",
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
KEYS = (
|
|
40
|
+
("arrows", "slide"),
|
|
41
|
+
("R", "new game"),
|
|
42
|
+
("Esc", "title"),
|
|
43
|
+
("Q", "quit"),
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
#: The page's "how to play" and "credits", in its own words where it has them.
|
|
47
|
+
RULES = (
|
|
48
|
+
("HOW TO PLAY", theme.ACCENT),
|
|
49
|
+
("Slide every tile one step with the arrow keys.", theme.VALUE),
|
|
50
|
+
("", ""),
|
|
51
|
+
("MERGING", theme.ACCENT),
|
|
52
|
+
("1 + 2 = 3 (or 2 + 1 = 3).", theme.VALUE),
|
|
53
|
+
("3 + 3 = 6, then 6 + 6 = 12, 12 + 12 = 24, and so on.", theme.VALUE),
|
|
54
|
+
("1 + 1 and 2 + 2 do NOT merge.", theme.DEAD),
|
|
55
|
+
("", ""),
|
|
56
|
+
("NEW TILES", theme.ACCENT),
|
|
57
|
+
("After each move a new tile (1, 2 or 3) appears on the edge opposite "
|
|
58
|
+
"the direction you slid. A move that changes nothing brings no tile.",
|
|
59
|
+
theme.VALUE),
|
|
60
|
+
("", ""),
|
|
61
|
+
("THE END", theme.ACCENT),
|
|
62
|
+
("The game ends when the board is full and no merges are possible. Your "
|
|
63
|
+
"score is the sum of every tile you merge. How high can you go?",
|
|
64
|
+
theme.VALUE),
|
|
65
|
+
("", ""),
|
|
66
|
+
("CREDITS", theme.ACCENT),
|
|
67
|
+
("Design and development: Jake A. McCoy. Original concept: based on "
|
|
68
|
+
"Threes! by Sirvo (Asher Vollmer, Greg Wohlwend and Jimmy Hinson). "
|
|
69
|
+
"Published by magmacrunch media.", theme.VALUE),
|
|
70
|
+
("", ""),
|
|
71
|
+
("KEYS", theme.ACCENT),
|
|
72
|
+
("arrows, WASD or hjkl slide R new game Esc title Q quit",
|
|
73
|
+
theme.VALUE),
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _fit(text: str, width: int) -> str:
|
|
78
|
+
if width <= 1 or len(text) <= width:
|
|
79
|
+
return text
|
|
80
|
+
return text[:width - 1] + "…"
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _too_small(renderer, cols: int, rows: int) -> bool:
|
|
84
|
+
if renderer.width >= cols and renderer.height >= rows:
|
|
85
|
+
return False
|
|
86
|
+
renderer.ui_text(1, 1, "TERMINAL TOO SMALL", fill=theme.DEAD)
|
|
87
|
+
renderer.ui_text(1, 2, f"need {cols}x{rows}, "
|
|
88
|
+
f"have {renderer.width}x{renderer.height}",
|
|
89
|
+
fill=theme.DIM)
|
|
90
|
+
return True
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _clock(seconds: float) -> str:
|
|
94
|
+
s = int(seconds)
|
|
95
|
+
return f"{s // 60}:{s % 60:02d}"
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
# ── The title ───────────────────────────────────────────────────────
|
|
99
|
+
|
|
100
|
+
class TitleScene:
|
|
101
|
+
ITEMS = ("PLAY", "SCORES", "HOW TO PLAY", "QUIT")
|
|
102
|
+
|
|
103
|
+
def __init__(self, app):
|
|
104
|
+
self.app = app
|
|
105
|
+
self.menu = Menu(
|
|
106
|
+
app.renderer, theme=_menu_theme(), menu_width=theme.MENU_W,
|
|
107
|
+
item_height=theme.MENU_ITEM_H, title_height=theme.MENU_TITLE_H,
|
|
108
|
+
item_padding=theme.MENU_PAD, border_pad=theme.MENU_BORDER,
|
|
109
|
+
selected_color=theme.MENU_SELECTED, normal_color=theme.VALUE,
|
|
110
|
+
)
|
|
111
|
+
self._show()
|
|
112
|
+
|
|
113
|
+
def _show(self) -> None:
|
|
114
|
+
self.menu.show(list(self.ITEMS), on_select=self._chose)
|
|
115
|
+
|
|
116
|
+
def _chose(self, index: int, label: str) -> None: # noqa: ARG002
|
|
117
|
+
if index == 0:
|
|
118
|
+
self.app.start_game()
|
|
119
|
+
elif index == 1:
|
|
120
|
+
self.app.show_scores()
|
|
121
|
+
elif index == 2:
|
|
122
|
+
self.app.show_rules()
|
|
123
|
+
else:
|
|
124
|
+
self.app.host.quit()
|
|
125
|
+
|
|
126
|
+
def on_resume(self) -> None:
|
|
127
|
+
self._show()
|
|
128
|
+
|
|
129
|
+
def handle_key(self, key: str) -> bool:
|
|
130
|
+
if key in ("up", "w", "k"):
|
|
131
|
+
self.menu.move_up()
|
|
132
|
+
elif key in ("down", "s", "j"):
|
|
133
|
+
self.menu.move_down()
|
|
134
|
+
elif key in ("enter", "space"):
|
|
135
|
+
self.menu.confirm()
|
|
136
|
+
elif key == "q":
|
|
137
|
+
self.app.host.quit()
|
|
138
|
+
elif key == "escape":
|
|
139
|
+
self.app.leave()
|
|
140
|
+
else:
|
|
141
|
+
return False
|
|
142
|
+
return True
|
|
143
|
+
|
|
144
|
+
def update(self, dt: float) -> None:
|
|
145
|
+
pass
|
|
146
|
+
|
|
147
|
+
def render(self) -> None:
|
|
148
|
+
r = self.app.renderer
|
|
149
|
+
r.clear()
|
|
150
|
+
r.draw_rect(0, 0, r.width, r.height, theme.BG)
|
|
151
|
+
if _too_small(r, theme.MENU_MIN_COLS, theme.MENU_MIN_ROWS):
|
|
152
|
+
r.present()
|
|
153
|
+
return
|
|
154
|
+
cx = r.width // 2
|
|
155
|
+
box_top = self._menu_box_top(r)
|
|
156
|
+
y = _draw_title(r, cx, box_top)
|
|
157
|
+
if y < box_top:
|
|
158
|
+
r.ui_text(cx, y, _fit(theme.TAGLINE, r.width - 2), fill=theme.LABEL, anchor="n")
|
|
159
|
+
self.menu.render()
|
|
160
|
+
|
|
161
|
+
below = box_top + len(self.ITEMS) + 2 * theme.MENU_PAD + 3
|
|
162
|
+
if self.app.best and below < r.height - 3:
|
|
163
|
+
r.ui_text(cx, below, f"best {self.app.best:,}", fill=theme.LABEL, anchor="n")
|
|
164
|
+
if self.app.host.seated:
|
|
165
|
+
r.ui_text(cx, r.height - 1, _fit(ARCADE_HELP, r.width - 2),
|
|
166
|
+
fill=theme.DIM, anchor="n")
|
|
167
|
+
r.ui_text(cx, r.height - 2, _fit(MENU_HELP, r.width - 2), fill=theme.DIM,
|
|
168
|
+
anchor="n")
|
|
169
|
+
r.present()
|
|
170
|
+
|
|
171
|
+
def _menu_box_top(self, renderer) -> int:
|
|
172
|
+
rows = len(self.ITEMS) * theme.MENU_ITEM_H + 2 * theme.MENU_PAD
|
|
173
|
+
return (renderer.height - rows) // 2 - theme.MENU_BORDER
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
# ── Rules and scores ────────────────────────────────────────────────
|
|
177
|
+
|
|
178
|
+
class RulesScene:
|
|
179
|
+
def __init__(self, app):
|
|
180
|
+
self.app = app
|
|
181
|
+
self.offset = 0
|
|
182
|
+
|
|
183
|
+
def handle_key(self, key: str) -> bool:
|
|
184
|
+
if key in ("up", "w", "k"):
|
|
185
|
+
self.offset = max(0, self.offset - 1)
|
|
186
|
+
elif key in ("down", "s", "j"):
|
|
187
|
+
self.offset = min(self._max_offset(), self.offset + 1)
|
|
188
|
+
else:
|
|
189
|
+
self.app.host.pop_scene()
|
|
190
|
+
return True
|
|
191
|
+
|
|
192
|
+
def update(self, dt: float) -> None:
|
|
193
|
+
pass
|
|
194
|
+
|
|
195
|
+
def _width(self) -> int:
|
|
196
|
+
return min(64, self.app.renderer.width - 4)
|
|
197
|
+
|
|
198
|
+
def _lines(self) -> list[tuple[str, str]]:
|
|
199
|
+
out = []
|
|
200
|
+
for text, fill in RULES:
|
|
201
|
+
if not text:
|
|
202
|
+
out.append(("", theme.DIM))
|
|
203
|
+
continue
|
|
204
|
+
out.extend((line, fill) for line in textwrap.wrap(text, max(10, self._width())))
|
|
205
|
+
return out
|
|
206
|
+
|
|
207
|
+
def _viewport(self) -> int:
|
|
208
|
+
return max(1, self.app.renderer.height - 5)
|
|
209
|
+
|
|
210
|
+
def _max_offset(self) -> int:
|
|
211
|
+
return max(0, len(self._lines()) - self._viewport())
|
|
212
|
+
|
|
213
|
+
def render(self) -> None:
|
|
214
|
+
r = self.app.renderer
|
|
215
|
+
r.clear()
|
|
216
|
+
r.draw_rect(0, 0, r.width, r.height, theme.BG)
|
|
217
|
+
if _too_small(r, theme.MENU_MIN_COLS, theme.MENU_MIN_ROWS):
|
|
218
|
+
r.present()
|
|
219
|
+
return
|
|
220
|
+
self.offset = min(self.offset, self._max_offset())
|
|
221
|
+
r.ui_text(r.width // 2, 1, "HOW TO PLAY", fill=theme.ACCENT, anchor="n")
|
|
222
|
+
left = (r.width - self._width()) // 2
|
|
223
|
+
for i, (text, fill) in enumerate(self._lines()[self.offset:self.offset + self._viewport()]):
|
|
224
|
+
r.ui_text(left, 3 + i, text, fill=fill)
|
|
225
|
+
r.ui_text(r.width // 2, r.height - 1, _fit(RULES_HELP, r.width - 2),
|
|
226
|
+
fill=theme.DIM, anchor="n")
|
|
227
|
+
r.present()
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
class ScoresScene:
|
|
231
|
+
def __init__(self, app):
|
|
232
|
+
self.app = app
|
|
233
|
+
self.offset = 0
|
|
234
|
+
|
|
235
|
+
def handle_key(self, key: str) -> bool:
|
|
236
|
+
if key in ("up", "w", "k"):
|
|
237
|
+
self.offset = max(0, self.offset - 1)
|
|
238
|
+
elif key in ("down", "s", "j"):
|
|
239
|
+
self.offset = min(self._max_offset(), self.offset + 1)
|
|
240
|
+
else:
|
|
241
|
+
self.app.host.pop_scene()
|
|
242
|
+
return True
|
|
243
|
+
|
|
244
|
+
def update(self, dt: float) -> None:
|
|
245
|
+
pass
|
|
246
|
+
|
|
247
|
+
def _viewport(self) -> int:
|
|
248
|
+
return max(1, self.app.renderer.height - 6)
|
|
249
|
+
|
|
250
|
+
def _max_offset(self) -> int:
|
|
251
|
+
return max(0, len(self.app.scores.load()) - self._viewport())
|
|
252
|
+
|
|
253
|
+
def render(self) -> None:
|
|
254
|
+
r = self.app.renderer
|
|
255
|
+
r.clear()
|
|
256
|
+
r.draw_rect(0, 0, r.width, r.height, theme.BG)
|
|
257
|
+
if _too_small(r, theme.MENU_MIN_COLS, theme.MENU_MIN_ROWS):
|
|
258
|
+
r.present()
|
|
259
|
+
return
|
|
260
|
+
cx = r.width // 2
|
|
261
|
+
entries = self.app.scores.load()
|
|
262
|
+
self.offset = min(self.offset, self._max_offset())
|
|
263
|
+
r.ui_text(cx, 1, "HIGH SCORES", fill=theme.ACCENT, anchor="n")
|
|
264
|
+
if not entries:
|
|
265
|
+
r.ui_text(cx, r.height // 2, "no scores yet", fill=theme.DIM, anchor="n")
|
|
266
|
+
r.ui_text(cx, r.height - 2, SCORES_HELP, fill=theme.DIM, anchor="n")
|
|
267
|
+
r.present()
|
|
268
|
+
return
|
|
269
|
+
left = max(1, cx - 13)
|
|
270
|
+
r.ui_text(left, 3, " SCORE BEST", fill=theme.LABEL)
|
|
271
|
+
for i, entry in enumerate(entries[self.offset:self.offset + self._viewport()],
|
|
272
|
+
start=self.offset + 1):
|
|
273
|
+
y = 3 + i - self.offset
|
|
274
|
+
fill = theme.GOLD if i == 1 else theme.VALUE
|
|
275
|
+
r.ui_text(left, y, f"{i:>3}. {entry.initials:<3}", fill=fill)
|
|
276
|
+
r.ui_text(left + 9, y, f"{entry.score:>8,}", fill=theme.ACCENT)
|
|
277
|
+
top = entry.extra.get("highestTile")
|
|
278
|
+
if top is not None:
|
|
279
|
+
r.ui_text(left + 19, y, f"{top:>4}", fill=theme.LABEL)
|
|
280
|
+
more = len(entries) - (self.offset + self._viewport())
|
|
281
|
+
hint = RULES_HELP if (more > 0 or self.offset) else SCORES_HELP
|
|
282
|
+
r.ui_text(cx, r.height - 2, _fit(hint, r.width - 2), fill=theme.DIM, anchor="n")
|
|
283
|
+
r.present()
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
class InitialsScene:
|
|
287
|
+
"""Who just did that. Drawn over the finished game."""
|
|
288
|
+
|
|
289
|
+
render_below = True
|
|
290
|
+
|
|
291
|
+
def __init__(self, app, score: int, extra: dict | None = None):
|
|
292
|
+
self.app = app
|
|
293
|
+
self.score = score
|
|
294
|
+
#: What the browser files beside the number: the time and top tile.
|
|
295
|
+
self.extra = extra or {}
|
|
296
|
+
self.typed = ""
|
|
297
|
+
|
|
298
|
+
def handle_key(self, key: str) -> bool:
|
|
299
|
+
if key == "backspace":
|
|
300
|
+
self.typed = self.typed[:-1]
|
|
301
|
+
elif key in ("enter", "escape"):
|
|
302
|
+
self._confirm()
|
|
303
|
+
elif len(key) == 1 and key.isalpha():
|
|
304
|
+
if len(self.typed) < scores.INITIALS_LENGTH:
|
|
305
|
+
self.typed += key.upper()
|
|
306
|
+
# Anything else is swallowed: an arrow still being mashed as the board
|
|
307
|
+
# filled must not reach the finished game underneath.
|
|
308
|
+
return True
|
|
309
|
+
|
|
310
|
+
def _confirm(self) -> None:
|
|
311
|
+
self.app.record(self.score, self.typed or None, self.extra)
|
|
312
|
+
self.app.host.pop_scene()
|
|
313
|
+
|
|
314
|
+
def update(self, dt: float) -> None:
|
|
315
|
+
pass
|
|
316
|
+
|
|
317
|
+
def render(self) -> None:
|
|
318
|
+
r = self.app.renderer
|
|
319
|
+
cx, cy = r.width // 2, r.height // 2
|
|
320
|
+
box_w = min(r.width - 4, 34)
|
|
321
|
+
r.draw_rect(cx - box_w // 2, cy - 3, box_w, 7, theme.MENU_BOX)
|
|
322
|
+
r.ui_text(cx, cy - 2, "NEW HIGH SCORE!", fill=theme.GOLD, anchor="n")
|
|
323
|
+
r.ui_text(cx, cy - 1, f"{self.score:,}", fill=theme.VALUE, anchor="n")
|
|
324
|
+
slots = self.typed.ljust(scores.INITIALS_LENGTH, "_")
|
|
325
|
+
r.ui_text(cx, cy + 1, " ".join(slots), fill=theme.ACCENT, anchor="n")
|
|
326
|
+
r.ui_text(cx, cy + 2, _fit(INITIALS_HELP, box_w - 2), fill=theme.DIM, anchor="n")
|
|
327
|
+
r.present()
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
# ── A game ──────────────────────────────────────────────────────────
|
|
331
|
+
|
|
332
|
+
class GameScene:
|
|
333
|
+
"""The board and its panel."""
|
|
334
|
+
|
|
335
|
+
#: Seconds after the board fills before Enter starts another game, so an
|
|
336
|
+
#: arrow mashed into the last move does not skip past the score.
|
|
337
|
+
OVER_GRACE = 0.6
|
|
338
|
+
#: Seconds a newly arrived tile stays lit.
|
|
339
|
+
FLASH_SECONDS = 0.35
|
|
340
|
+
|
|
341
|
+
def __init__(self, app):
|
|
342
|
+
self.app = app
|
|
343
|
+
self.restart()
|
|
344
|
+
|
|
345
|
+
def restart(self) -> None:
|
|
346
|
+
self.app.host.input.clear()
|
|
347
|
+
self.board = rules.Board(rand=self.app.new_rand()).start()
|
|
348
|
+
self.elapsed = 0.0
|
|
349
|
+
self.over_for = 0.0
|
|
350
|
+
self.recorded = False
|
|
351
|
+
self.flash: tuple[int, int] | None = None
|
|
352
|
+
self.flash_left = 0.0
|
|
353
|
+
self.app.last_rank = None
|
|
354
|
+
|
|
355
|
+
@property
|
|
356
|
+
def over(self) -> bool:
|
|
357
|
+
return self.board.over
|
|
358
|
+
|
|
359
|
+
def _slide(self, direction: str) -> None:
|
|
360
|
+
before = [row[:] for row in self.board.grid]
|
|
361
|
+
if not self.board.move(direction):
|
|
362
|
+
return
|
|
363
|
+
# The one cell that was empty and now holds a 1, 2 or 3 is the tile
|
|
364
|
+
# that just came in. The slide only ever empties cells or merges into
|
|
365
|
+
# occupied ones, so nothing else can match.
|
|
366
|
+
for r in range(rules.SIZE):
|
|
367
|
+
for c in range(rules.SIZE):
|
|
368
|
+
if before[r][c] == 0 and self.board.grid[r][c] and \
|
|
369
|
+
(r, c) in self.board.spawn_edge():
|
|
370
|
+
self.flash = (r, c)
|
|
371
|
+
self.flash_left = self.FLASH_SECONDS
|
|
372
|
+
if self.over:
|
|
373
|
+
self._finish()
|
|
374
|
+
|
|
375
|
+
def _extra(self) -> dict:
|
|
376
|
+
return {"time": int(self.elapsed), "highestTile": self.board.high_tile}
|
|
377
|
+
|
|
378
|
+
def _finish(self) -> None:
|
|
379
|
+
if self.recorded:
|
|
380
|
+
return
|
|
381
|
+
self.recorded = True
|
|
382
|
+
b = self.board
|
|
383
|
+
if self.app.qualifies(b.score):
|
|
384
|
+
self.app.enter_initials(b.score, self._extra())
|
|
385
|
+
elif b.score > 0:
|
|
386
|
+
self.app.record(b.score, None, self._extra())
|
|
387
|
+
|
|
388
|
+
def update(self, dt: float) -> None:
|
|
389
|
+
self.app.host.input.poll()
|
|
390
|
+
self.flash_left = max(0.0, self.flash_left - dt)
|
|
391
|
+
if self.over:
|
|
392
|
+
self.over_for += dt
|
|
393
|
+
return
|
|
394
|
+
self.elapsed += dt
|
|
395
|
+
|
|
396
|
+
def handle_key(self, key: str) -> bool:
|
|
397
|
+
if key == "q":
|
|
398
|
+
self.app.host.quit()
|
|
399
|
+
elif key == "escape":
|
|
400
|
+
self.app.to_title()
|
|
401
|
+
elif key == "r":
|
|
402
|
+
self.restart()
|
|
403
|
+
elif self.over:
|
|
404
|
+
if self.over_for >= self.OVER_GRACE and key in ("enter", "space"):
|
|
405
|
+
self.restart()
|
|
406
|
+
elif key in MOVE_KEYS:
|
|
407
|
+
self._slide(MOVE_KEYS[key])
|
|
408
|
+
else:
|
|
409
|
+
return False
|
|
410
|
+
return True
|
|
411
|
+
|
|
412
|
+
# -- Drawing -----------------------------------------------------
|
|
413
|
+
|
|
414
|
+
def _origin(self, r) -> tuple[int, int]:
|
|
415
|
+
x = (r.width - (theme.BOARD_W + theme.PANEL_GAP + theme.PANEL_W)) // 2
|
|
416
|
+
spare = r.height - theme.BOARD_H
|
|
417
|
+
y = 1 if spare >= 2 else max(0, spare)
|
|
418
|
+
return x, y
|
|
419
|
+
|
|
420
|
+
def render(self) -> None:
|
|
421
|
+
r = self.app.renderer
|
|
422
|
+
r.clear()
|
|
423
|
+
r.draw_rect(0, 0, r.width, r.height, theme.BG)
|
|
424
|
+
if _too_small(r, theme.MIN_COLS, theme.MIN_ROWS):
|
|
425
|
+
r.present()
|
|
426
|
+
return
|
|
427
|
+
ox, oy = self._origin(r)
|
|
428
|
+
self._draw_board(r, ox, oy)
|
|
429
|
+
self._draw_panel(r, ox + theme.BOARD_W + theme.PANEL_GAP, oy)
|
|
430
|
+
if self.over:
|
|
431
|
+
self._draw_box(r, ox, oy, self._over_lines())
|
|
432
|
+
r.present()
|
|
433
|
+
|
|
434
|
+
def _draw_board(self, r, ox: int, oy: int) -> None:
|
|
435
|
+
r.draw_rect(ox, oy, theme.BOARD_W, theme.BOARD_H, theme.BORDER)
|
|
436
|
+
r.draw_rect(ox + 1, oy + 1, theme.BOARD_W - 2, theme.BOARD_H - 2, theme.FIELD)
|
|
437
|
+
for row in range(rules.SIZE):
|
|
438
|
+
for col in range(rules.SIZE):
|
|
439
|
+
x = ox + 1 + theme.GAP + col * (theme.TILE_W + theme.GAP)
|
|
440
|
+
y = oy + 1 + theme.GAP + row * (theme.TILE_H + theme.GAP)
|
|
441
|
+
self._draw_tile(r, x, y, self.board.grid[row][col],
|
|
442
|
+
lit=self.flash_left > 0 and self.flash == (row, col))
|
|
443
|
+
|
|
444
|
+
def _draw_tile(self, r, x: int, y: int, value: int, lit: bool) -> None:
|
|
445
|
+
if value == 0:
|
|
446
|
+
r.draw_rect(x, y, theme.TILE_W, theme.TILE_H, theme.SLOT)
|
|
447
|
+
return
|
|
448
|
+
bg, fg = theme.tile_colours(value)
|
|
449
|
+
if lit:
|
|
450
|
+
bg, fg = fg, theme.BG
|
|
451
|
+
if value == 1 and not lit:
|
|
452
|
+
# The page draws a 1 as an outline. Here that is a frame of the
|
|
453
|
+
# outline's blue round the fill, which needs no glyph and so
|
|
454
|
+
# survives --ascii.
|
|
455
|
+
r.draw_rect(x, y, theme.TILE_W, theme.TILE_H, theme.ONE_EDGE)
|
|
456
|
+
r.draw_rect(x + 1, y + 1, theme.TILE_W - 2, theme.TILE_H - 2, bg)
|
|
457
|
+
else:
|
|
458
|
+
r.draw_rect(x, y, theme.TILE_W, theme.TILE_H, bg)
|
|
459
|
+
r.ui_text(x + theme.TILE_W // 2, y + theme.TILE_H // 2, str(value),
|
|
460
|
+
fill=fg, anchor="n")
|
|
461
|
+
|
|
462
|
+
def _draw_panel(self, r, x: int, y: int) -> None:
|
|
463
|
+
b = self.board
|
|
464
|
+
best = max(self.app.best, b.score)
|
|
465
|
+
stats = (
|
|
466
|
+
("SCORE", f"{b.score:,}", theme.ACCENT),
|
|
467
|
+
("BEST", f"{best:,}" if best else "---", theme.GOLD),
|
|
468
|
+
("TOP TILE", str(b.high_tile), theme.GREEN),
|
|
469
|
+
("TIME", _clock(self.elapsed), theme.VALUE),
|
|
470
|
+
)
|
|
471
|
+
sy = y + 1
|
|
472
|
+
for label, value, fill in stats:
|
|
473
|
+
r.ui_text(x, sy, label, fill=theme.LABEL)
|
|
474
|
+
r.ui_text(x, sy + 1, value, fill=fill)
|
|
475
|
+
sy += 3
|
|
476
|
+
sy += 1
|
|
477
|
+
for key, word in KEYS:
|
|
478
|
+
if sy >= y + theme.BOARD_H:
|
|
479
|
+
break
|
|
480
|
+
r.ui_text(x, sy, f"{key:<7}", fill=theme.VALUE)
|
|
481
|
+
r.ui_text(x + 7, sy, word, fill=theme.DIM)
|
|
482
|
+
sy += 1
|
|
483
|
+
|
|
484
|
+
def _over_lines(self) -> list[tuple[str, str]]:
|
|
485
|
+
b = self.board
|
|
486
|
+
lines = [("GAME OVER", theme.DEAD), (f"{b.score:,}", theme.VALUE),
|
|
487
|
+
(f"best tile {b.high_tile} · {_clock(self.elapsed)}", theme.LABEL)]
|
|
488
|
+
if self.app.last_rank:
|
|
489
|
+
lines.append((f"rank {self.app.last_rank}", theme.GOLD))
|
|
490
|
+
if self.over_for >= self.OVER_GRACE:
|
|
491
|
+
lines += [("Enter again", theme.DIM), ("Esc title", theme.DIM)]
|
|
492
|
+
return lines
|
|
493
|
+
|
|
494
|
+
def _draw_box(self, r, ox: int, oy: int, lines: list[tuple[str, str]]) -> None:
|
|
495
|
+
inner = theme.BOARD_W - 4
|
|
496
|
+
top = oy + theme.BOARD_H // 2 - len(lines) // 2 - 1
|
|
497
|
+
r.draw_rect(ox + 2, top, inner, len(lines) + 2, theme.MENU_BOX)
|
|
498
|
+
for i, (text, fill) in enumerate(lines):
|
|
499
|
+
r.ui_text(ox + 2 + inner // 2, top + 1 + i, _fit(text, inner - 2),
|
|
500
|
+
fill=fill, anchor="n")
|
|
501
|
+
|
|
502
|
+
|
|
503
|
+
def _draw_title(renderer, cx: int, box_top: int) -> int:
|
|
504
|
+
if bigtext.width(theme.BANNER) <= renderer.width - 2 and \
|
|
505
|
+
bigtext.height(theme.BANNER) + 1 <= box_top - 1:
|
|
506
|
+
y = 1
|
|
507
|
+
for line in bigtext.lines(theme.BANNER):
|
|
508
|
+
renderer.ui_text(cx, y, line, fill=theme.ACCENT, anchor="n")
|
|
509
|
+
y += 1
|
|
510
|
+
return y
|
|
511
|
+
renderer.ui_text(cx, 1, theme.BANNER, fill=theme.ACCENT, anchor="n")
|
|
512
|
+
return 2
|
|
513
|
+
|
|
514
|
+
|
|
515
|
+
def _menu_theme():
|
|
516
|
+
return replace(
|
|
517
|
+
DEFAULT_THEME, primary=theme.MENU_SELECTED, text=theme.VALUE,
|
|
518
|
+
dim_text=theme.DIM, box_fill=theme.MENU_BOX, box_outline=theme.LABEL,
|
|
519
|
+
outline_width=1, selection_fill=theme.MENU_SELECTION_BG,
|
|
520
|
+
)
|
|
521
|
+
|
|
522
|
+
|
|
523
|
+
__all__ = ["GameScene", "InitialsScene", "RulesScene", "ScoresScene",
|
|
524
|
+
"TitleScene"]
|
threes/theme.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""Palette and layout, in character cells.
|
|
2
|
+
|
|
3
|
+
The colours are the browser's, from ``web/css/game.css``: the arcade's dark
|
|
4
|
+
violet behind everything, and each tile's own background and text colour.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
BG = "#0A0612"
|
|
10
|
+
FIELD = "#1A0A2A"
|
|
11
|
+
SLOT = "#140A20"
|
|
12
|
+
BORDER = "#2A1A3A"
|
|
13
|
+
LABEL = "#8A7FA8"
|
|
14
|
+
VALUE = "#F0EAD8"
|
|
15
|
+
DIM = "#4A3F68"
|
|
16
|
+
ACCENT = "#00F5FF"
|
|
17
|
+
GOLD = "#FFE03A"
|
|
18
|
+
GREEN = "#39FF6E"
|
|
19
|
+
DEAD = "#FF3D6E"
|
|
20
|
+
EDGE = "#5BA3F5"
|
|
21
|
+
|
|
22
|
+
MENU_BOX = "#1A0A2A"
|
|
23
|
+
MENU_SELECTED = "#00F5FF"
|
|
24
|
+
MENU_SELECTION_BG = "#2A1A3A"
|
|
25
|
+
|
|
26
|
+
#: ``.tile[data-value]`` in game.css: (background, text). Past 12288 the last
|
|
27
|
+
#: one holds, as the page's would.
|
|
28
|
+
TILES: dict[int, tuple[str, str]] = {
|
|
29
|
+
1: ("#1A1A2E", "#F0EAD8"),
|
|
30
|
+
2: ("#0A2A5A", "#6EC8FF"),
|
|
31
|
+
3: ("#005A6A", "#00F5FF"),
|
|
32
|
+
6: ("#006A4A", "#39FF6E"),
|
|
33
|
+
12: ("#4A6A00", "#FFE03A"),
|
|
34
|
+
24: ("#7A4A00", "#FF7C1F"),
|
|
35
|
+
48: ("#8A1A3A", "#FF3D6E"),
|
|
36
|
+
96: ("#6A0060", "#E040FF"),
|
|
37
|
+
192: ("#3A0080", "#C45FFF"),
|
|
38
|
+
384: ("#1A00AA", "#8080FF"),
|
|
39
|
+
768: ("#5A3A00", "#FFD700"),
|
|
40
|
+
1536: ("#7A5A00", "#FFE03A"),
|
|
41
|
+
3072: ("#8A6A00", "#FFF0A0"),
|
|
42
|
+
6144: ("#FFD700", "#0A0612"),
|
|
43
|
+
12288: ("#FFFFFF", "#0A0612"),
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
#: A 1 has an outline on the page, not a fill; here its edge is that blue.
|
|
47
|
+
ONE_EDGE = "#5BA3F5"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def tile_colours(value: int) -> tuple[str, str]:
|
|
51
|
+
if value in TILES:
|
|
52
|
+
return TILES[value]
|
|
53
|
+
return TILES[max(TILES)] if value > max(TILES) else TILES[1]
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
#: A tile is 7 cells by 3 rows, which reads as roughly square in a terminal
|
|
57
|
+
#: whose cells are about twice as tall as they are wide.
|
|
58
|
+
TILE_W = 7
|
|
59
|
+
TILE_H = 3
|
|
60
|
+
GAP = 1
|
|
61
|
+
|
|
62
|
+
#: The board with its frame: four tiles and three gaps each way, plus a gap
|
|
63
|
+
#: of margin and a border on every side.
|
|
64
|
+
BOARD_W = 4 * TILE_W + 5 * GAP + 2
|
|
65
|
+
BOARD_H = 4 * TILE_H + 5 * GAP + 2
|
|
66
|
+
|
|
67
|
+
PANEL_W = 16
|
|
68
|
+
PANEL_GAP = 3
|
|
69
|
+
|
|
70
|
+
MIN_COLS = BOARD_W + PANEL_GAP + PANEL_W + 2
|
|
71
|
+
MIN_ROWS = BOARD_H + 2
|
|
72
|
+
|
|
73
|
+
MENU_MIN_COLS = 40
|
|
74
|
+
MENU_MIN_ROWS = 16
|
|
75
|
+
MENU_W = 26
|
|
76
|
+
MENU_ITEM_H = 1
|
|
77
|
+
MENU_TITLE_H = 0
|
|
78
|
+
MENU_PAD = 1
|
|
79
|
+
MENU_BORDER = 1
|
|
80
|
+
|
|
81
|
+
BANNER = "THREES"
|
|
82
|
+
TAGLINE = "SLIDE MERGE SURVIVE"
|