kirby-dice 0.1.0__tar.gz

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.
@@ -0,0 +1,170 @@
1
+ # PolyForm Noncommercial License 1.0.0
2
+
3
+ <https://polyformproject.org/licenses/noncommercial/1.0.0>
4
+
5
+ ## Acceptance
6
+
7
+ In order to get any license under these terms, you must agree
8
+ to them as both strict obligations and conditions to all
9
+ your licenses.
10
+
11
+ ## Copyright License
12
+
13
+ The licensor grants you a copyright license for the
14
+ software to do everything you might do with the software
15
+ that would otherwise infringe the licensor's copyright
16
+ in it for any permitted purpose. However, you may
17
+ only distribute the software according to [Distribution
18
+ License](#distribution-license) and make changes or new works
19
+ based on the software according to [Changes and New Works
20
+ License](#changes-and-new-works-license).
21
+
22
+ ## Distribution License
23
+
24
+ The licensor grants you an additional copyright license
25
+ to distribute copies of the software. Your license
26
+ to distribute covers distributing the software with
27
+ changes and new works permitted by [Changes and New Works
28
+ License](#changes-and-new-works-license).
29
+
30
+ ## Notices
31
+
32
+ You must ensure that anyone who gets a copy of any part of
33
+ the software from you also gets a copy of these terms or the
34
+ URL for them above, as well as copies of any plain-text lines
35
+ beginning with `Required Notice:` that the licensor provided
36
+ with the software. For example:
37
+
38
+ > Required Notice: Copyright Yoyodyne, Inc. (http://example.com)
39
+
40
+ ## Changes and New Works License
41
+
42
+ The licensor grants you an additional copyright license to
43
+ make changes and new works based on the software for any
44
+ permitted purpose.
45
+
46
+ ## Patent License
47
+
48
+ The licensor grants you a patent license for the software that
49
+ covers patent claims the licensor can license, or becomes able
50
+ to license, that you would infringe by using the software.
51
+
52
+ ## Noncommercial Purposes
53
+
54
+ Any noncommercial purpose is a permitted purpose.
55
+
56
+ ## Personal Uses
57
+
58
+ Personal use for research, experiment, and testing for
59
+ the benefit of public knowledge, personal study, private
60
+ entertainment, hobby projects, amateur pursuits, or religious
61
+ observance, without any anticipated commercial application,
62
+ is use for a permitted purpose.
63
+
64
+ ## Noncommercial Organizations
65
+
66
+ Use by any charitable organization, educational institution,
67
+ public research organization, public safety or health
68
+ organization, environmental protection organization,
69
+ or government institution is use for a permitted purpose
70
+ regardless of the source of funding or obligations resulting
71
+ from the funding.
72
+
73
+ ## Fair Use
74
+
75
+ You may have "fair use" rights for the software under the
76
+ law. These terms do not limit them.
77
+
78
+ ## No Other Rights
79
+
80
+ These terms do not allow you to sublicense or transfer any of
81
+ your licenses to anyone else, or prevent the licensor from
82
+ granting licenses to anyone else. These terms do not imply
83
+ any other licenses.
84
+
85
+ ## Patent Defense
86
+
87
+ If you make any written claim that the software infringes or
88
+ contributes to infringement of any patent, your patent license
89
+ for the software granted under these terms ends immediately. If
90
+ your company makes such a claim, your patent license ends
91
+ immediately for work on behalf of your company.
92
+
93
+ ## Violations
94
+
95
+ The first time you are notified in writing that you have
96
+ violated any of these terms, or done anything with the software
97
+ not covered by your licenses, your licenses can nonetheless
98
+ continue if you come into full compliance with these terms,
99
+ and take practical steps to correct past violations, within
100
+ 32 days of receiving notice. Otherwise, all your licenses
101
+ end immediately.
102
+
103
+ ## No Liability
104
+
105
+ ***As far as the law allows, the software comes as is, without
106
+ any warranty or condition, and the licensor will not be liable
107
+ to you for any damages arising out of these terms or the use
108
+ or nature of the software, under any kind of legal claim.***
109
+
110
+ ## Definitions
111
+
112
+ The **licensor** is the individual or entity offering these
113
+ terms, and the **software** is the software the licensor makes
114
+ available under these terms.
115
+
116
+ **You** refers to the individual or entity agreeing to these
117
+ terms.
118
+
119
+ **Your company** is any legal entity, sole proprietorship,
120
+ or other kind of organization that you work for, plus all
121
+ organizations that have control over, are under the control of,
122
+ or are under common control with that organization. **Control**
123
+ means ownership of substantially all the assets of an entity,
124
+ or the power to direct its management and policies by vote,
125
+ contract, or otherwise. Control can be direct or indirect.
126
+
127
+ **Your licenses** are all the licenses granted to you for the
128
+ software under these terms.
129
+
130
+ **Use** means anything you do with the software requiring one
131
+ of your licenses.
132
+
133
+
134
+ ================================================================================
135
+ NOTES SPECIFIC TO kirby-cost
136
+ ================================================================================
137
+
138
+ Required Notice: Copyright (c) 2026 Peter D Bethke
139
+
140
+ (The line above begins with `Required Notice:` deliberately -- see the
141
+ Notices section of the licence. It must travel with any copy of this
142
+ software or any part of it.)
143
+
144
+ Why this licence
145
+ ----------------
146
+
147
+ kirby-cost is a Python port of the HERO Designer cost engine. The intent of
148
+ choosing a noncommercial licence is explicit: nobody should be able to build a
149
+ paid product on this work, because doing so would compete with HERO Designer
150
+ and with Hero Games' interests.
151
+
152
+ The Elastic License 2.0 was considered and rejected for this purpose. ELv2's
153
+ only commercial limitation is against offering the software as a hosted or
154
+ managed service; it permits selling a non-hosted product outright. That does
155
+ not serve the intent above.
156
+
157
+ Third-party rights this licence does NOT grant
158
+ -----------------------------------------------
159
+
160
+ This work derives from HERO Designer source licensed from CompNet Design, Inc.
161
+ That licence grants personal use and modification; distribution is separately
162
+ gated on licensing with HERO Games. Nothing in this file grants, or purports to
163
+ grant, any right in HERO Designer's source, in the HERO System rules, or in any
164
+ Hero Games property.
165
+
166
+ kirby-cost ships NO Hero Games data. It requires the operator to supply their
167
+ own licensed HERO Designer template (for example Main6E.hdt). Running this
168
+ software without such a licence is the operator's responsibility.
169
+
170
+ HERO System and HERO Designer are the property of their respective owners.
@@ -0,0 +1,86 @@
1
+ Metadata-Version: 2.4
2
+ Name: kirby-dice
3
+ Version: 0.1.0
4
+ Summary: Fair, seeded, replayable dice for the Kirby HERO System platform
5
+ Author: PeterB
6
+ License: PolyForm Noncommercial License 1.0.0
7
+ Project-URL: Repository, https://github.com/pdbethke/kirby-dice
8
+ Requires-Python: >=3.12
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Provides-Extra: dev
12
+ Requires-Dist: pytest>=8.0; extra == "dev"
13
+ Requires-Dist: pytest-cov>=5.0; extra == "dev"
14
+ Requires-Dist: ruff>=0.6; extra == "dev"
15
+ Dynamic: license-file
16
+
17
+ # kirby-dice
18
+
19
+ Fair, seeded, replayable dice for the Kirby HERO System platform.
20
+
21
+ This package rolls dice and does nothing else. It has **no dependencies** and
22
+ holds **no game rules** — what a roll means is the caller's business.
23
+
24
+ ## Attribution
25
+
26
+ The roller is based in part on the work of **Bill Bame**, shared informally
27
+ and with thanks. No licence condition attaches to it; the credit is here
28
+ because it is owed.
29
+
30
+ ## Why this is its own package
31
+
32
+ Players are, reasonably, funny about dice. A roller buried inside a combat
33
+ engine can *assert* that it is fair. One that ships on its own can prove it.
34
+
35
+ **The dice are fair, and the tests say how we know.** `tests/test_fairness.py`
36
+ runs chi-square uniformity over 60,000 rolls, checks independence across all
37
+ 36 ordered pairs of consecutive rolls, and pins the mean within five sigma of
38
+ 3.5. Every test is seeded and therefore deterministic — a fairness test that
39
+ fails once a fortnight only teaches people to re-run CI. Two of the tests
40
+ guard the guards: a loaded die must trip the uniformity assertion, and twenty
41
+ unseeded rollers must not share a seed.
42
+
43
+ **Every fight can be replayed.** A roller always reports the seed it rolls
44
+ from, including when you did not give it one:
45
+
46
+ ```python
47
+ from kirby_dice import RandomRoller
48
+
49
+ roller = RandomRoller()
50
+ fight = [roller.roll_dice(3) for _ in range(40)]
51
+
52
+ # Record roller.seed alongside the fight, and it replays die for die.
53
+ replay = RandomRoller(seed=roller.seed)
54
+ assert [replay.roll_dice(3) for _ in range(40)] == fight
55
+ ```
56
+
57
+ An unseeded `random.Random()` draws from OS entropy, so the seed never exists
58
+ as a value and a fight cannot be reproduced once fought. `RandomRoller` picks
59
+ its own seed with `secrets.randbits(64)` instead — unguessable, so being
60
+ recordable does not make the next roll predictable.
61
+
62
+ ## Usage
63
+
64
+ ```python
65
+ from kirby_dice import RandomRoller, FakeRoller
66
+
67
+ RandomRoller(seed=42).roll_dice(3) # -> [1, 1, 6]
68
+ RandomRoller().roll_dice(2, sides=20) # any number of sides
69
+
70
+ FakeRoller([[3, 4, 5]]).roll_dice(3) # -> [3, 4, 5], for tests
71
+ ```
72
+
73
+ `DiceRoller` is a `Protocol`, so any object with a matching `roll_dice` will
74
+ do — that is the seam consumers inject through.
75
+
76
+ ### There is no `roll_half_die()`
77
+
78
+ A HERO half die is an extra whole d6 that the **caller** converts, next to the
79
+ rest of its damage rules. This package had such a method once. It had no
80
+ callers, and its mapping disagreed with the live conversion in the combat
81
+ engine — the same d6 gave different results depending on which you asked. Two
82
+ homes for one rule is how they drift apart. Roll dice here; convert them there.
83
+
84
+ ## Licence
85
+
86
+ PolyForm Noncommercial License 1.0.0 — see `LICENSE`.
@@ -0,0 +1,70 @@
1
+ # kirby-dice
2
+
3
+ Fair, seeded, replayable dice for the Kirby HERO System platform.
4
+
5
+ This package rolls dice and does nothing else. It has **no dependencies** and
6
+ holds **no game rules** — what a roll means is the caller's business.
7
+
8
+ ## Attribution
9
+
10
+ The roller is based in part on the work of **Bill Bame**, shared informally
11
+ and with thanks. No licence condition attaches to it; the credit is here
12
+ because it is owed.
13
+
14
+ ## Why this is its own package
15
+
16
+ Players are, reasonably, funny about dice. A roller buried inside a combat
17
+ engine can *assert* that it is fair. One that ships on its own can prove it.
18
+
19
+ **The dice are fair, and the tests say how we know.** `tests/test_fairness.py`
20
+ runs chi-square uniformity over 60,000 rolls, checks independence across all
21
+ 36 ordered pairs of consecutive rolls, and pins the mean within five sigma of
22
+ 3.5. Every test is seeded and therefore deterministic — a fairness test that
23
+ fails once a fortnight only teaches people to re-run CI. Two of the tests
24
+ guard the guards: a loaded die must trip the uniformity assertion, and twenty
25
+ unseeded rollers must not share a seed.
26
+
27
+ **Every fight can be replayed.** A roller always reports the seed it rolls
28
+ from, including when you did not give it one:
29
+
30
+ ```python
31
+ from kirby_dice import RandomRoller
32
+
33
+ roller = RandomRoller()
34
+ fight = [roller.roll_dice(3) for _ in range(40)]
35
+
36
+ # Record roller.seed alongside the fight, and it replays die for die.
37
+ replay = RandomRoller(seed=roller.seed)
38
+ assert [replay.roll_dice(3) for _ in range(40)] == fight
39
+ ```
40
+
41
+ An unseeded `random.Random()` draws from OS entropy, so the seed never exists
42
+ as a value and a fight cannot be reproduced once fought. `RandomRoller` picks
43
+ its own seed with `secrets.randbits(64)` instead — unguessable, so being
44
+ recordable does not make the next roll predictable.
45
+
46
+ ## Usage
47
+
48
+ ```python
49
+ from kirby_dice import RandomRoller, FakeRoller
50
+
51
+ RandomRoller(seed=42).roll_dice(3) # -> [1, 1, 6]
52
+ RandomRoller().roll_dice(2, sides=20) # any number of sides
53
+
54
+ FakeRoller([[3, 4, 5]]).roll_dice(3) # -> [3, 4, 5], for tests
55
+ ```
56
+
57
+ `DiceRoller` is a `Protocol`, so any object with a matching `roll_dice` will
58
+ do — that is the seam consumers inject through.
59
+
60
+ ### There is no `roll_half_die()`
61
+
62
+ A HERO half die is an extra whole d6 that the **caller** converts, next to the
63
+ rest of its damage rules. This package had such a method once. It had no
64
+ callers, and its mapping disagreed with the live conversion in the combat
65
+ engine — the same d6 gave different results depending on which you asked. Two
66
+ homes for one rule is how they drift apart. Roll dice here; convert them there.
67
+
68
+ ## Licence
69
+
70
+ PolyForm Noncommercial License 1.0.0 — see `LICENSE`.
@@ -0,0 +1,24 @@
1
+ """Dice for the Kirby HERO System platform: fair, seeded, and replayable.
2
+
3
+ This package rolls dice and does nothing else. It holds no game rules — what
4
+ a roll MEANS is the caller's business, and deliberately so: a rule with two
5
+ homes is a rule that drifts.
6
+
7
+ **Attribution.** This dice roller is based in part on the work of Bill Bame,
8
+ shared informally and with thanks. No licence condition attaches to it; the
9
+ credit is here because it is owed. It was missing entirely until 2026-08-28,
10
+ and giving it a module of its own is part of why this package exists.
11
+
12
+ **Why a separate package.** Players are, reasonably, funny about dice. A
13
+ roller buried inside a combat engine can assert that it is fair. One that
14
+ ships on its own can prove it:
15
+
16
+ * ``tests/test_fairness.py`` — chi-square uniformity, independence of
17
+ consecutive rolls, mean and range, all seeded so they are deterministic.
18
+ * ``RandomRoller.seed`` — every roller reports the seed it rolls from, so a
19
+ fight recorded with its seed can be replayed die for die.
20
+ """
21
+ from kirby_dice.roller import DiceRoller, RandomRoller
22
+ from kirby_dice.fake import FakeRoller
23
+
24
+ __all__ = ["DiceRoller", "RandomRoller", "FakeRoller"]
@@ -0,0 +1,32 @@
1
+ """Deterministic roller for tests. Yields pre-computed dice results."""
2
+ from __future__ import annotations
3
+
4
+
5
+ class FakeRoller:
6
+ """Yields pre-computed dice values for deterministic tests.
7
+
8
+ Usage::
9
+
10
+ f = FakeRoller([[3, 4, 5], [1, 2, 3]])
11
+ f.roll_dice(3, sides=6) # -> [3, 4, 5]
12
+ f.roll_dice(3, sides=6) # -> [1, 2, 3]
13
+
14
+ A half die needs no special fixture. This package rolls whole dice and
15
+ nothing else; a caller that wants a half die asks for one extra d6 and
16
+ converts the last value itself.
17
+ """
18
+
19
+ def __init__(self, dice_results: list[list[int]]) -> None:
20
+ self._dice = [list(inner) for inner in dice_results]
21
+ self._dice_idx = 0
22
+
23
+ def roll_dice(self, count: int, sides: int = 6) -> list[int]:
24
+ if self._dice_idx >= len(self._dice):
25
+ raise IndexError("FakeRoller dice pool exhausted")
26
+ result = self._dice[self._dice_idx]
27
+ self._dice_idx += 1
28
+ if len(result) != count:
29
+ raise ValueError(
30
+ f"FakeRoller: caller asked for {count} dice, fixture has {len(result)}"
31
+ )
32
+ return list(result)
@@ -0,0 +1,65 @@
1
+ """Dice rolling protocol and default RandomRoller.
2
+
3
+ Based in part on the work of Bill Bame — see this package's ``__init__``
4
+ for the attribution note.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import random
9
+ import secrets
10
+ from typing import Protocol
11
+
12
+
13
+ class DiceRoller(Protocol):
14
+ """Protocol for dice rolling. Engine accepts any implementation."""
15
+
16
+ def roll_dice(self, count: int, sides: int = 6) -> list[int]:
17
+ """Roll `count` dice with `sides` faces. Returns individual results."""
18
+ ...
19
+
20
+
21
+ class RandomRoller:
22
+ """Default engine roller using Python's random module.
23
+
24
+ Always seeded with a REAL number, and always able to hand that number
25
+ back. An unseeded ``random.Random()`` draws from OS entropy, which means
26
+ the seed never exists as a value and a fight can never be replayed once
27
+ it has been fought. Choosing the seed explicitly costs nothing and makes
28
+ every sequence reproducible: record ``roller.seed`` alongside the fight,
29
+ and ``RandomRoller(seed=<recorded>)`` rolls it again, die for die.
30
+
31
+ That is the difference between asserting the dice were fair and proving
32
+ it. See ``tests/test_dice_fairness.py``.
33
+ """
34
+
35
+ def __init__(self, seed: int | None = None) -> None:
36
+ # secrets, not random: the default seed should be as unguessable as
37
+ # the OS entropy it replaces. Being recordable must not make it
38
+ # predictable to a player who would rather know the next roll.
39
+ self._seed = secrets.randbits(64) if seed is None else seed
40
+ self._rng = random.Random(self._seed)
41
+
42
+ @property
43
+ def seed(self) -> int:
44
+ """The seed this roller rolls from. Never None -- see the class doc."""
45
+ return self._seed
46
+
47
+ def roll_dice(self, count: int, sides: int = 6) -> list[int]:
48
+ # Accept whole-valued floats: dice counts computed from canon
49
+ # HDC-imported stats arrive as floats (the cost engine's
50
+ # characteristic_value() returns float, so e.g. PRE 15.0 // 5
51
+ # = 3.0 dice). A NON-integral count is rejected, not truncated:
52
+ # truncating would silently DROP a half die.
53
+ #
54
+ # There is deliberately no roll_half_die(). A half die is an extra
55
+ # whole d6 that the CALLER converts, next to the rest of its damage
56
+ # rules. This package had such a method once, with no callers and a
57
+ # mapping that disagreed with the live conversion; two homes for one
58
+ # rule is how they drift apart. Roll dice here, convert them there.
59
+ n = int(count)
60
+ if n != count:
61
+ raise ValueError(
62
+ f"roll_dice count must be a whole number, got {count!r}; "
63
+ "a half die is an extra whole d6, converted in resolution.damage"
64
+ )
65
+ return [self._rng.randint(1, sides) for _ in range(n)]
@@ -0,0 +1,86 @@
1
+ Metadata-Version: 2.4
2
+ Name: kirby-dice
3
+ Version: 0.1.0
4
+ Summary: Fair, seeded, replayable dice for the Kirby HERO System platform
5
+ Author: PeterB
6
+ License: PolyForm Noncommercial License 1.0.0
7
+ Project-URL: Repository, https://github.com/pdbethke/kirby-dice
8
+ Requires-Python: >=3.12
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Provides-Extra: dev
12
+ Requires-Dist: pytest>=8.0; extra == "dev"
13
+ Requires-Dist: pytest-cov>=5.0; extra == "dev"
14
+ Requires-Dist: ruff>=0.6; extra == "dev"
15
+ Dynamic: license-file
16
+
17
+ # kirby-dice
18
+
19
+ Fair, seeded, replayable dice for the Kirby HERO System platform.
20
+
21
+ This package rolls dice and does nothing else. It has **no dependencies** and
22
+ holds **no game rules** — what a roll means is the caller's business.
23
+
24
+ ## Attribution
25
+
26
+ The roller is based in part on the work of **Bill Bame**, shared informally
27
+ and with thanks. No licence condition attaches to it; the credit is here
28
+ because it is owed.
29
+
30
+ ## Why this is its own package
31
+
32
+ Players are, reasonably, funny about dice. A roller buried inside a combat
33
+ engine can *assert* that it is fair. One that ships on its own can prove it.
34
+
35
+ **The dice are fair, and the tests say how we know.** `tests/test_fairness.py`
36
+ runs chi-square uniformity over 60,000 rolls, checks independence across all
37
+ 36 ordered pairs of consecutive rolls, and pins the mean within five sigma of
38
+ 3.5. Every test is seeded and therefore deterministic — a fairness test that
39
+ fails once a fortnight only teaches people to re-run CI. Two of the tests
40
+ guard the guards: a loaded die must trip the uniformity assertion, and twenty
41
+ unseeded rollers must not share a seed.
42
+
43
+ **Every fight can be replayed.** A roller always reports the seed it rolls
44
+ from, including when you did not give it one:
45
+
46
+ ```python
47
+ from kirby_dice import RandomRoller
48
+
49
+ roller = RandomRoller()
50
+ fight = [roller.roll_dice(3) for _ in range(40)]
51
+
52
+ # Record roller.seed alongside the fight, and it replays die for die.
53
+ replay = RandomRoller(seed=roller.seed)
54
+ assert [replay.roll_dice(3) for _ in range(40)] == fight
55
+ ```
56
+
57
+ An unseeded `random.Random()` draws from OS entropy, so the seed never exists
58
+ as a value and a fight cannot be reproduced once fought. `RandomRoller` picks
59
+ its own seed with `secrets.randbits(64)` instead — unguessable, so being
60
+ recordable does not make the next roll predictable.
61
+
62
+ ## Usage
63
+
64
+ ```python
65
+ from kirby_dice import RandomRoller, FakeRoller
66
+
67
+ RandomRoller(seed=42).roll_dice(3) # -> [1, 1, 6]
68
+ RandomRoller().roll_dice(2, sides=20) # any number of sides
69
+
70
+ FakeRoller([[3, 4, 5]]).roll_dice(3) # -> [3, 4, 5], for tests
71
+ ```
72
+
73
+ `DiceRoller` is a `Protocol`, so any object with a matching `roll_dice` will
74
+ do — that is the seam consumers inject through.
75
+
76
+ ### There is no `roll_half_die()`
77
+
78
+ A HERO half die is an extra whole d6 that the **caller** converts, next to the
79
+ rest of its damage rules. This package had such a method once. It had no
80
+ callers, and its mapping disagreed with the live conversion in the combat
81
+ engine — the same d6 gave different results depending on which you asked. Two
82
+ homes for one rule is how they drift apart. Roll dice here; convert them there.
83
+
84
+ ## Licence
85
+
86
+ PolyForm Noncommercial License 1.0.0 — see `LICENSE`.
@@ -0,0 +1,13 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ kirby_dice/__init__.py
5
+ kirby_dice/fake.py
6
+ kirby_dice/roller.py
7
+ kirby_dice.egg-info/PKG-INFO
8
+ kirby_dice.egg-info/SOURCES.txt
9
+ kirby_dice.egg-info/dependency_links.txt
10
+ kirby_dice.egg-info/requires.txt
11
+ kirby_dice.egg-info/top_level.txt
12
+ tests/test_fairness.py
13
+ tests/test_rollers.py
@@ -0,0 +1,5 @@
1
+
2
+ [dev]
3
+ pytest>=8.0
4
+ pytest-cov>=5.0
5
+ ruff>=0.6
@@ -0,0 +1 @@
1
+ kirby_dice
@@ -0,0 +1,38 @@
1
+ [project]
2
+ name = "kirby-dice"
3
+ version = "0.1.0"
4
+ description = "Fair, seeded, replayable dice for the Kirby HERO System platform"
5
+ requires-python = ">=3.12"
6
+ # Matches kirby-cost and kirby-combat. The roller itself is based in part on
7
+ # Bill Bame's work, shared informally with no licence condition attached.
8
+ license = {text = "PolyForm Noncommercial License 1.0.0"}
9
+ readme = "README.md"
10
+ authors = [{name = "PeterB"}]
11
+ # No dependencies, and that is a feature: this package must be trivially
12
+ # auditable by anyone who wants to check that the dice are fair.
13
+ dependencies = []
14
+
15
+ [project.urls]
16
+ Repository = "https://github.com/pdbethke/kirby-dice"
17
+
18
+ [project.optional-dependencies]
19
+ dev = [
20
+ "pytest>=8.0",
21
+ "pytest-cov>=5.0",
22
+ "ruff>=0.6",
23
+ ]
24
+
25
+ [build-system]
26
+ requires = ["setuptools>=68.0"]
27
+ build-backend = "setuptools.build_meta"
28
+
29
+ [tool.setuptools.packages.find]
30
+ include = ["kirby_dice*"]
31
+
32
+ [tool.pytest.ini_options]
33
+ testpaths = ["tests"]
34
+ pythonpath = ["."]
35
+
36
+ [tool.ruff]
37
+ target-version = "py312"
38
+ line-length = 100
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,138 @@
1
+ """The roller is fair, and every roll it makes can be replayed.
2
+
3
+ Trust is the product here. A combat engine can assert that its dice were
4
+ fair; a module that ships its RNG, its fairness tests and its seed can prove
5
+ it. These are the tests that make the claim checkable.
6
+
7
+ Every test is SEEDED and therefore deterministic -- a fairness test that
8
+ fails once a fortnight teaches people to re-run CI, which is worse than not
9
+ having it. The seeds below are arbitrary but fixed; the critical values are
10
+ standard.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import math
15
+
16
+ import pytest
17
+
18
+ from kirby_dice import RandomRoller
19
+
20
+ #: Chi-square critical values, 5 degrees of freedom (a d6 has six outcomes).
21
+ #: At p=0.001 a fair die exceeds this once in a thousand runs; the seeds are
22
+ #: fixed, so for THESE runs it either passes forever or fails forever.
23
+ CHI2_DF5_P001 = 20.515
24
+
25
+ #: 35 degrees of freedom, for the 36 ordered pairs in the independence test.
26
+ CHI2_DF35_P001 = 66.619
27
+
28
+
29
+ def _counts(values, faces=6):
30
+ counts = [0] * faces
31
+ for v in values:
32
+ counts[v - 1] += 1
33
+ return counts
34
+
35
+
36
+ def _chi_square(counts):
37
+ """Pearson's chi-square against a uniform expectation."""
38
+ n = sum(counts)
39
+ expected = n / len(counts)
40
+ return sum((c - expected) ** 2 / expected for c in counts)
41
+
42
+
43
+ # ---------------------------------------------------------------------------
44
+ # The shape of what comes back
45
+ # ---------------------------------------------------------------------------
46
+
47
+ @pytest.mark.parametrize("count", [0, 1, 3, 12, 60])
48
+ def test_it_returns_exactly_the_dice_asked_for(count):
49
+ assert len(RandomRoller(seed=1).roll_dice(count)) == count
50
+
51
+
52
+ @pytest.mark.parametrize("sides", [2, 3, 6, 20])
53
+ def test_every_die_lands_in_range(sides):
54
+ rolls = RandomRoller(seed=2).roll_dice(2000, sides=sides)
55
+ assert min(rolls) >= 1
56
+ assert max(rolls) <= sides
57
+
58
+
59
+ def test_every_face_of_a_d6_actually_appears():
60
+ """Guards the guard: a roller stuck on one face would pass a range test."""
61
+ assert set(RandomRoller(seed=3).roll_dice(500)) == {1, 2, 3, 4, 5, 6}
62
+
63
+
64
+ # ---------------------------------------------------------------------------
65
+ # Fairness
66
+ # ---------------------------------------------------------------------------
67
+
68
+ def test_a_d6_is_uniform_over_sixty_thousand_rolls():
69
+ counts = _counts(RandomRoller(seed=4).roll_dice(60_000))
70
+ chi2 = _chi_square(counts)
71
+ assert chi2 < CHI2_DF5_P001, f"d6 not uniform: counts={counts}, chi2={chi2:.2f}"
72
+
73
+
74
+ def test_the_uniformity_test_can_actually_fail():
75
+ """Guards the guard. A loaded die must trip the same assertion, or the
76
+ test above proves nothing about the real roller."""
77
+ loaded = [1] * 10_000 + [2, 3, 4, 5, 6] * 1_000
78
+ assert _chi_square(_counts(loaded)) > CHI2_DF5_P001
79
+
80
+
81
+ def test_consecutive_rolls_are_independent():
82
+ """Ordered pairs (previous, next) are uniform over all 36 combinations.
83
+ A roller that never repeats a face, or alternates high and low, is in
84
+ range and uniform per-face yet obviously unfair."""
85
+ rolls = RandomRoller(seed=5).roll_dice(72_000)
86
+ pairs = [0] * 36
87
+ for a, b in zip(rolls, rolls[1:]):
88
+ pairs[(a - 1) * 6 + (b - 1)] += 1
89
+ chi2 = _chi_square(pairs)
90
+ assert chi2 < CHI2_DF35_P001, f"pairs not independent: chi2={chi2:.2f}"
91
+
92
+
93
+ def test_the_mean_of_a_d6_is_three_and_a_half():
94
+ rolls = RandomRoller(seed=6).roll_dice(60_000)
95
+ mean = sum(rolls) / len(rolls)
96
+ # Standard error of a d6 mean over 60k rolls is ~0.007; 5 sigma is ~0.035.
97
+ assert math.isclose(mean, 3.5, abs_tol=0.035), f"mean was {mean}"
98
+
99
+
100
+ # ---------------------------------------------------------------------------
101
+ # Seed capture -- the part that makes a fight reproducible
102
+ # ---------------------------------------------------------------------------
103
+
104
+ def test_the_same_seed_gives_the_same_sequence():
105
+ assert RandomRoller(seed=99).roll_dice(50) == RandomRoller(seed=99).roll_dice(50)
106
+
107
+
108
+ def test_different_seeds_give_different_sequences():
109
+ assert RandomRoller(seed=1).roll_dice(50) != RandomRoller(seed=2).roll_dice(50)
110
+
111
+
112
+ def test_a_roller_reports_the_seed_it_was_given():
113
+ assert RandomRoller(seed=4242).seed == 4242
114
+
115
+
116
+ def test_an_unseeded_roller_still_reports_a_real_seed():
117
+ """The point of the whole exercise. `RandomRoller()` used to draw from OS
118
+ entropy, so the seed did not exist as a value and no fight could be
119
+ replayed afterwards. It must now choose a seed it can hand back."""
120
+ roller = RandomRoller()
121
+ assert isinstance(roller.seed, int)
122
+
123
+
124
+ def test_unseeded_rollers_do_not_all_share_one_seed():
125
+ """Guards the guard: returning a constant would satisfy the test above
126
+ and make every fight in the system roll identically."""
127
+ seeds = {RandomRoller().seed for _ in range(20)}
128
+ assert len(seeds) == 20
129
+
130
+
131
+ def test_a_recorded_seed_replays_the_fight_exactly():
132
+ """The feature, stated as a test: record `.seed` on the event log, and
133
+ the whole sequence can be reproduced from the record alone."""
134
+ live = RandomRoller()
135
+ rolled = [live.roll_dice(6) for _ in range(40)]
136
+
137
+ replay = RandomRoller(seed=live.seed)
138
+ assert [replay.roll_dice(6) for _ in range(40)] == rolled
@@ -0,0 +1,71 @@
1
+ """Dice roller protocol tests."""
2
+ from kirby_dice import DiceRoller, RandomRoller, FakeRoller
3
+
4
+
5
+ def test_random_roller_in_range():
6
+ r = RandomRoller(seed=42)
7
+ for _ in range(100):
8
+ result = r.roll_dice(3, sides=6)
9
+ assert len(result) == 3
10
+ assert all(1 <= d <= 6 for d in result)
11
+
12
+
13
+ def test_random_roller_reproducible_with_seed():
14
+ a = RandomRoller(seed=12345)
15
+ b = RandomRoller(seed=12345)
16
+ for _ in range(10):
17
+ assert a.roll_dice(3, sides=6) == b.roll_dice(3, sides=6)
18
+
19
+
20
+ def test_fake_roller_returns_sequence():
21
+ f = FakeRoller([[3, 4, 5], [1, 2, 3]])
22
+ assert f.roll_dice(3, sides=6) == [3, 4, 5]
23
+ assert f.roll_dice(3, sides=6) == [1, 2, 3]
24
+
25
+
26
+ def test_fake_roller_raises_when_exhausted():
27
+ import pytest
28
+ f = FakeRoller([[3, 4, 5]])
29
+ f.roll_dice(3, sides=6)
30
+ with pytest.raises(IndexError):
31
+ f.roll_dice(3, sides=6)
32
+
33
+
34
+ def test_fake_roller_rejects_a_fixture_of_the_wrong_size():
35
+ """A fixture that does not match the call is a test authoring mistake,
36
+ and a silent mismatch would feed the resolver the wrong dice."""
37
+ import pytest
38
+ f = FakeRoller([[3, 4, 5]])
39
+ with pytest.raises(ValueError, match="asked for 2 dice"):
40
+ f.roll_dice(2, sides=6)
41
+
42
+
43
+ def test_fake_roller_isolates_inputs():
44
+ # After constructing FakeRoller, mutating the passed-in lists should not
45
+ # affect what FakeRoller yields.
46
+ dice_in = [[3, 4, 5], [1, 2, 3]]
47
+ f = FakeRoller(dice_in)
48
+ dice_in[0][0] = 99
49
+ dice_in[1] = [9, 9, 9]
50
+ assert f.roll_dice(3, sides=6) == [3, 4, 5]
51
+ assert f.roll_dice(3, sides=6) == [1, 2, 3]
52
+
53
+
54
+ def test_random_roller_accepts_whole_valued_float_count():
55
+ """Canon HDC imports compute dice counts from float stats — the
56
+ cost engine's characteristic_value() returns float, so e.g.
57
+ PRE 60.0 // 5 = 12.0 dice. Whole-valued float counts must roll."""
58
+ r = RandomRoller(seed=7)
59
+ result = r.roll_dice(12.0)
60
+ assert len(result) == 12
61
+ assert all(1 <= d <= 6 for d in result)
62
+
63
+
64
+ def test_random_roller_rejects_fractional_count():
65
+ """A fractional count means a half-die leaked into the d6 count.
66
+ A half die is an extra whole d6 that resolution.damage converts;
67
+ reject rather than silently truncate (truncation drops the half die)."""
68
+ import pytest
69
+ r = RandomRoller(seed=7)
70
+ with pytest.raises(ValueError, match="whole number"):
71
+ r.roll_dice(4.5)