netris 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,30 @@
1
+ # Python caches and bytecode
2
+ __pycache__/
3
+ *.py[cod]
4
+ .pytest_cache/
5
+ .ruff_cache/
6
+ .mypy_cache/
7
+ .hypothesis/
8
+ .ipynb_checkpoints/
9
+
10
+ # Coverage
11
+ .coverage
12
+ .coverage.*
13
+ htmlcov/
14
+
15
+ # Virtual environments
16
+ venv/
17
+ .venv/
18
+ env/
19
+
20
+ # Build artifacts
21
+ dist/
22
+ build/
23
+ *.egg-info/
24
+
25
+ # Game Boy ROM (copyrighted, never commit)
26
+ *.gb
27
+ *.gb.ram
28
+
29
+ # Local logs
30
+ logs/
netris-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Javier Aranda
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
netris-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,96 @@
1
+ Metadata-Version: 2.5
2
+ Name: netris
3
+ Version: 0.1.0
4
+ Summary: Gymnasium environment for Game Boy Tetris emulated with PyBoy
5
+ Project-URL: Homepage, https://github.com/javi-aranda/netris
6
+ Author: Javier Aranda
7
+ License: MIT License
8
+
9
+ Copyright (c) 2026 Javier Aranda
10
+
11
+ Permission is hereby granted, free of charge, to any person obtaining a copy
12
+ of this software and associated documentation files (the "Software"), to deal
13
+ in the Software without restriction, including without limitation the rights
14
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15
+ copies of the Software, and to permit persons to whom the Software is
16
+ furnished to do so, subject to the following conditions:
17
+
18
+ The above copyright notice and this permission notice shall be included in all
19
+ copies or substantial portions of the Software.
20
+
21
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27
+ SOFTWARE.
28
+ License-File: LICENSE
29
+ Keywords: gameboy,gymnasium,pyboy,reinforcement-learning,tetris
30
+ Classifier: Development Status :: 3 - Alpha
31
+ Classifier: Intended Audience :: Science/Research
32
+ Classifier: License :: OSI Approved :: MIT License
33
+ Classifier: Programming Language :: Python :: 3
34
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
35
+ Requires-Python: >=3.11
36
+ Requires-Dist: gymnasium>=1.0
37
+ Requires-Dist: numpy>=1.23
38
+ Requires-Dist: pyboy>=2.6
39
+ Provides-Extra: dev
40
+ Requires-Dist: pytest>=8.0; extra == 'dev'
41
+ Requires-Dist: ruff>=0.6; extra == 'dev'
42
+ Description-Content-Type: text/markdown
43
+
44
+ # netris
45
+
46
+ A [Gymnasium](https://gymnasium.farama.org/) environment for **Game Boy Tetris**,
47
+ emulated with [PyBoy](https://github.com/Baekalfen/PyBoy).
48
+
49
+ - Placement-based action space: `rotation (0-3) * 10 + column (0-9)` (40 actions).
50
+ - Dict observation: board, current/next piece, row completion, holes,
51
+ bumpiness and aggregate height.
52
+ - Line clears are confirmed against the game's own on-screen counter, so
53
+ phantom clears (e.g. at game over) cannot happen.
54
+ - Optional 1-piece lookahead information via the on-screen NEXT panel
55
+ (`NetrisEnvConfig(include_next_piece=True)`).
56
+
57
+ ## Install
58
+
59
+ ```bash
60
+ pip install netris
61
+ ```
62
+
63
+ ## ROM
64
+
65
+ The Game Boy Tetris ROM is **not** distributed with this package. Provide your
66
+ own dump:
67
+
68
+ ```bash
69
+ export NETRIS_ROM=/path/to/tetris.gb
70
+ ```
71
+
72
+ ## Quickstart
73
+
74
+ ```python
75
+ import gymnasium as gym
76
+ import netris # registers "Netris/GameBoyTetris-v0"
77
+
78
+ env = gym.make("Netris/GameBoyTetris-v0") # uses NETRIS_ROM
79
+ obs, info = env.reset(seed=0)
80
+ obs, reward, terminated, truncated, info = env.step(env.action_space.sample())
81
+ env.close()
82
+ ```
83
+
84
+ Or directly:
85
+
86
+ ```python
87
+ from netris import NetrisEnvConfig, TetrisEnv
88
+
89
+ env = TetrisEnv("/path/to/tetris.gb", config=NetrisEnvConfig())
90
+ obs, info = env.reset()
91
+ ```
92
+
93
+ ## License
94
+
95
+ MIT. PyBoy is an LGPL-3.0 dependency; the Tetris ROM is copyrighted and must be
96
+ supplied by the user.
netris-0.1.0/README.md ADDED
@@ -0,0 +1,53 @@
1
+ # netris
2
+
3
+ A [Gymnasium](https://gymnasium.farama.org/) environment for **Game Boy Tetris**,
4
+ emulated with [PyBoy](https://github.com/Baekalfen/PyBoy).
5
+
6
+ - Placement-based action space: `rotation (0-3) * 10 + column (0-9)` (40 actions).
7
+ - Dict observation: board, current/next piece, row completion, holes,
8
+ bumpiness and aggregate height.
9
+ - Line clears are confirmed against the game's own on-screen counter, so
10
+ phantom clears (e.g. at game over) cannot happen.
11
+ - Optional 1-piece lookahead information via the on-screen NEXT panel
12
+ (`NetrisEnvConfig(include_next_piece=True)`).
13
+
14
+ ## Install
15
+
16
+ ```bash
17
+ pip install netris
18
+ ```
19
+
20
+ ## ROM
21
+
22
+ The Game Boy Tetris ROM is **not** distributed with this package. Provide your
23
+ own dump:
24
+
25
+ ```bash
26
+ export NETRIS_ROM=/path/to/tetris.gb
27
+ ```
28
+
29
+ ## Quickstart
30
+
31
+ ```python
32
+ import gymnasium as gym
33
+ import netris # registers "Netris/GameBoyTetris-v0"
34
+
35
+ env = gym.make("Netris/GameBoyTetris-v0") # uses NETRIS_ROM
36
+ obs, info = env.reset(seed=0)
37
+ obs, reward, terminated, truncated, info = env.step(env.action_space.sample())
38
+ env.close()
39
+ ```
40
+
41
+ Or directly:
42
+
43
+ ```python
44
+ from netris import NetrisEnvConfig, TetrisEnv
45
+
46
+ env = TetrisEnv("/path/to/tetris.gb", config=NetrisEnvConfig())
47
+ obs, info = env.reset()
48
+ ```
49
+
50
+ ## License
51
+
52
+ MIT. PyBoy is an LGPL-3.0 dependency; the Tetris ROM is copyrighted and must be
53
+ supplied by the user.
@@ -0,0 +1,42 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "netris"
7
+ version = "0.1.0"
8
+ description = "Gymnasium environment for Game Boy Tetris emulated with PyBoy"
9
+ readme = "README.md"
10
+ license = { file = "LICENSE" }
11
+ requires-python = ">=3.11"
12
+ authors = [{ name = "Javier Aranda" }]
13
+ keywords = ["reinforcement-learning", "gymnasium", "tetris", "gameboy", "pyboy"]
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "Intended Audience :: Science/Research",
17
+ "License :: OSI Approved :: MIT License",
18
+ "Programming Language :: Python :: 3",
19
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
20
+ ]
21
+ dependencies = [
22
+ "gymnasium>=1.0",
23
+ "pyboy>=2.6",
24
+ "numpy>=1.23",
25
+ ]
26
+
27
+ [project.optional-dependencies]
28
+ dev = ["pytest>=8.0", "ruff>=0.6"]
29
+
30
+ [project.urls]
31
+ Homepage = "https://github.com/javi-aranda/netris"
32
+
33
+ [tool.hatch.build.targets.wheel]
34
+ packages = ["src/netris"]
35
+
36
+ [tool.pytest.ini_options]
37
+ markers = ["rom: requires a GameBoy Tetris ROM"]
38
+ addopts = "-m \"not rom\""
39
+
40
+ [tool.ruff]
41
+ line-length = 100
42
+ target-version = "py311"
@@ -0,0 +1,10 @@
1
+ """Netris: a Gymnasium environment for GameBoy Tetris."""
2
+
3
+ from .envs import NetrisEnvConfig, TetrisEnv
4
+ from .registration import ENV_ID, register_env
5
+
6
+ __version__ = "0.1.0"
7
+
8
+ __all__ = ["ENV_ID", "NetrisEnvConfig", "TetrisEnv", "__version__", "register_env"]
9
+
10
+ register_env()
@@ -0,0 +1,4 @@
1
+ from .config import NetrisEnvConfig
2
+ from .tetris_env import TetrisEnv
3
+
4
+ __all__ = ["NetrisEnvConfig", "TetrisEnv"]
@@ -0,0 +1,36 @@
1
+ """Environment configuration."""
2
+
3
+ from dataclasses import dataclass, field
4
+
5
+
6
+ @dataclass
7
+ class NetrisEnvConfig:
8
+ """Knobs that do not change the observation/action spaces."""
9
+
10
+ include_next_piece: bool = False
11
+ watchdog_steps: int = 1000
12
+ collect_metrics: bool = True
13
+
14
+ line_clear_rewards: dict = field(
15
+ default_factory=lambda: {1: 5.0, 2: 15.0, 3: 40.0}
16
+ )
17
+ tetris_reward: float = 100.0
18
+ hole_penalty: float = 0.5
19
+ aggregate_height_penalty: float = 0.005
20
+ bumpiness_penalty: float = 0.01
21
+ game_over_penalty: float = -10.0
22
+ survival_bonus: float = 1.0
23
+
24
+ def to_dict(self):
25
+ return {
26
+ "include_next_piece": self.include_next_piece,
27
+ "watchdog_steps": self.watchdog_steps,
28
+ "collect_metrics": self.collect_metrics,
29
+ "line_clear_rewards": dict(self.line_clear_rewards),
30
+ "tetris_reward": self.tetris_reward,
31
+ "hole_penalty": self.hole_penalty,
32
+ "aggregate_height_penalty": self.aggregate_height_penalty,
33
+ "bumpiness_penalty": self.bumpiness_penalty,
34
+ "game_over_penalty": self.game_over_penalty,
35
+ "survival_bonus": self.survival_bonus,
36
+ }
@@ -0,0 +1,136 @@
1
+ import json
2
+ from collections import Counter
3
+ from datetime import UTC, datetime
4
+
5
+ import numpy as np
6
+
7
+
8
+ class MetricsCollector:
9
+ """In-memory per-episode metrics.
10
+
11
+ Persisting metrics to disk is the responsibility of the main-process
12
+ callbacks: environments may run in subprocesses (SubprocVecEnv) and must
13
+ not race on shared files.
14
+ """
15
+
16
+ def __init__(self):
17
+ self._reset_episode()
18
+
19
+ def _reset_episode(self):
20
+ self.episode_actions = Counter()
21
+ self.episode_rotations = 0
22
+ self.episode_placement_columns = []
23
+ self.episode_placement_heights = []
24
+ self.episode_reward_breakdowns = []
25
+ self.episode_line_clears = []
26
+ self.episode_max_height = 0
27
+ self.episode_bumpiness_values = []
28
+ self.episode_holes_values = []
29
+
30
+ def register_action(self, action):
31
+ self.episode_actions[int(action)] += 1
32
+
33
+ def register_rotation(self):
34
+ self.episode_rotations += 1
35
+
36
+ def register_piece_placed(self, column, height):
37
+ self.episode_placement_columns.append(column)
38
+ self.episode_placement_heights.append(height)
39
+
40
+ def register_reward_breakdown(self, *, reward_lines=0.0, reward_holes=0.0,
41
+ reward_height=0.0, reward_bumpiness=0.0,
42
+ reward_clean=0.0, reward_total=0.0):
43
+ self.episode_reward_breakdowns.append({
44
+ "lines": reward_lines,
45
+ "holes": reward_holes,
46
+ "height": reward_height,
47
+ "bumpiness": reward_bumpiness,
48
+ "clean": reward_clean,
49
+ "total": reward_total,
50
+ })
51
+
52
+ def register_line_clear(self, lines_delta):
53
+ self.episode_line_clears.append(lines_delta)
54
+
55
+ def update_max_height(self, height):
56
+ self.episode_max_height = max(self.episode_max_height, height)
57
+
58
+ def record_bumpiness(self, bumpiness):
59
+ self.episode_bumpiness_values.append(bumpiness)
60
+
61
+ def record_holes(self, holes):
62
+ self.episode_holes_values.append(holes)
63
+
64
+ def episode_summary(self, episode, steps, pieces, total_lines, total_reward):
65
+ total_lines_from_breakdown = sum(
66
+ d.get("lines", 0) for d in self.episode_reward_breakdowns
67
+ )
68
+ total_holes = sum(
69
+ d.get("holes", 0) for d in self.episode_reward_breakdowns
70
+ )
71
+ total_height = sum(
72
+ d.get("height", 0) for d in self.episode_reward_breakdowns
73
+ )
74
+ total_bumpiness = sum(
75
+ d.get("bumpiness", 0) for d in self.episode_reward_breakdowns
76
+ )
77
+
78
+ avg_placement_col = (
79
+ np.mean(self.episode_placement_columns)
80
+ if self.episode_placement_columns else 0.0
81
+ )
82
+ avg_placement_height = (
83
+ np.mean(self.episode_placement_heights)
84
+ if self.episode_placement_heights else 0.0
85
+ )
86
+ avg_bumpiness = (
87
+ np.mean(self.episode_bumpiness_values)
88
+ if self.episode_bumpiness_values else 0.0
89
+ )
90
+ avg_holes = (
91
+ np.mean(self.episode_holes_values)
92
+ if self.episode_holes_values else 0.0
93
+ )
94
+
95
+ return {
96
+ "timestamp": datetime.now(UTC).isoformat(),
97
+ "episode": episode,
98
+ "steps": steps,
99
+ "pieces": pieces,
100
+ "lines_cleared": total_lines,
101
+ "max_height": self.episode_max_height,
102
+ "avg_bumpiness": round(float(avg_bumpiness), 3),
103
+ "avg_holes": round(float(avg_holes), 3),
104
+ "reward_total": round(float(total_reward), 4),
105
+ "reward_lines": round(total_lines_from_breakdown, 4),
106
+ "reward_holes": round(total_holes, 4),
107
+ "reward_height": round(total_height, 4),
108
+ "reward_bumpiness": round(total_bumpiness, 4),
109
+ "rotations": self.episode_rotations,
110
+ "avg_placement_col": round(float(avg_placement_col), 3),
111
+ "avg_placement_height": round(float(avg_placement_height), 3),
112
+ "action_distribution": json.dumps(dict(self.episode_actions)),
113
+ "line_clear_distribution": json.dumps(dict(Counter(self.episode_line_clears))),
114
+ }
115
+
116
+ def reset_episode(self):
117
+ self._reset_episode()
118
+
119
+ def get_placement_heatmap(self):
120
+ heatmap = np.zeros((18, 10), dtype=np.int32)
121
+ for col, height in zip(self.episode_placement_columns, self.episode_placement_heights):
122
+ row = 18 - 1 - height
123
+ row = max(0, min(17, row))
124
+ col = max(0, min(9, col))
125
+ heatmap[row, col] += 1
126
+ return heatmap
127
+
128
+
129
+ class NullMetricsCollector:
130
+ """No-op collector used when metrics collection is disabled."""
131
+
132
+ def __getattr__(self, name):
133
+ return lambda *args, **kwargs: None
134
+
135
+ def episode_summary(self, **kwargs):
136
+ return {}