Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/games.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ jobs:
strategy:
fail-fast: false
matrix:
benchmark: [common, minigrid, crafter, textworld, babaisai, minihack]
benchmark: [common, minigrid, crafter, textworld, babaisai, minihack, tetris]
steps:
- uses: actions/checkout@v4
with: {persist-credentials: false}
Expand Down
49 changes: 49 additions & 0 deletions game_first_exam/benchmarks/tetris/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# Tetris Gymnasium native integration

This change adds the native Tetris Gymnasium adapter, trusted schema, metric validation, files-only image and native/contract tests. Frozen Harbor tasks and a game suite are intentionally deferred.

## Reference and compatibility

The repository baseline is LAMDA-NeSy/Game_exam commit `7998e10f62811de00a0145ab90480a254a3fc827`. The integration uses the MIT-licensed [Max-We/Tetris-Gymnasium](https://github.com/Max-We/Tetris-Gymnasium) project and does not use an NES/Atari emulator or a ROM.

Version 0.2.1 is pinned because the single-reset profile used here has the same `step` dynamics, actions and rewards as 0.3.1 without making the unrelated JAX functional API a simulator dependency. Version 0.3.1 also changes repeated-reset handling and RGB observation-space metadata; this adapter does not claim those paths are identical. `SOURCE.json` records the upstream tag commit and official PyPI wheel digest.

| Area | Implementation |
|---|---|
| Execution | Harbor native agent, existing GameClient, shared runtime/server.py |
| Native backend | `gym.make("tetris_gymnasium/Tetris")`, one reset and one native step per accepted request |
| Board profile | Native 10×20 board, gravity enabled, four-piece queue, one-piece holder |
| Observation | Upstream `RgbObservation`: padded board, active piece, queue and holder; PNG transport |
| Actions | All eight native actions exposed as descriptive enum strings |
| Seeding | Native `reset(seed=...)`; seed 0 is rejected because upstream 0.2.1 treats it as unseeded |
| Reward | Native placement survival reward plus native quadratic line-clear score |
| Metrics | Total cleared lines, native return, rewarded placements and line-clear score |
| Completion | Native game-over terminates; future tasks must provide a public action cap |

## Isolation and audit

Only `image_png_base64` is returned in adapter observations. The image is produced by the upstream RGB wrapper and contains information normally visible in Tetris: the board, active piece, next-piece queue and held piece. Exact arrays, active coordinates, random bag contents and RNG state stay inside the simulator and are used only by `fingerprint()` for audit integrity.

The adapter is designed for the existing standard-mode main/sim/verifier boundary. A future frozen task must keep its instance in sim/verifier, expose only the public client to main, and use a separate no-network verifier. No frozen Tetris task, target instance, solution or reference trajectory is included in this change.

## Native semantics

Tetris Gymnasium has no native time-limit truncation. The episode terminates when a new tetromino cannot spawn. A future frozen instance must set the shared public `max_steps` cap; reaching that cap remains a budget end rather than a native termination.

The primary metric profile is total native lines cleared. `target_lines` supplies a binary compatibility success label without changing native dynamics or ending the episode early. The adapter preserves each native reward increment and checks the pinned placement reward formula before recording it.

## Validation commands

```bash
python game_first_exam/tests/test_tetris_contract.py
python game_first_exam/tests/test_tetris_native.py
```

The native test requires the pinned Tetris Gymnasium environment and compares direct native calls with the adapter across seeds, all actions, observations, rewards, termination and read-only methods. Contract tests use a deterministic engine double to exercise the shared service and grader without publishing a task.

## Sources

- https://github.com/Max-We/Tetris-Gymnasium/tree/0.2.1
- https://max-we.github.io/Tetris-Gymnasium/environments/tetris/
- https://max-we.github.io/Tetris-Gymnasium/utilities/wrappers/
- https://pypi.org/project/tetris-gymnasium/0.2.1/
9 changes: 9 additions & 0 deletions game_first_exam/benchmarks/tetris/SOURCE.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"repository": "https://github.com/Max-We/Tetris-Gymnasium",
"commit": "b09ac36b55a532f030a3b71f90e2c94fb14f26b5",
"release": "0.2.1",
"distribution": "tetris_gymnasium-0.2.1-py3-none-any.whl",
"sha256": "e7a154c58cdc14abd02b3f97dbf2e3806c362d12bbfc6e18c078b7bad55c0dc6",
"license": "MIT",
"interface": "Gymnasium reset/step with the upstream RgbObservation wrapper"
}
146 changes: 146 additions & 0 deletions game_first_exam/benchmarks/tetris/adapter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
"""Tetris Gymnasium backend using its native RGB observation wrapper."""
import importlib.metadata
import numbers

import gymnasium as gym
from tetris_gymnasium.envs import Tetris as _Tetris # noqa: F401 - registers the environment
from tetris_gymnasium.wrappers.observation import RgbObservation

from contracts import Capabilities, Transition
from encoding import png, state_hash


ACTIONS = {
'MOVE_LEFT': 0,
'MOVE_RIGHT': 1,
'MOVE_DOWN': 2,
'ROTATE_CLOCKWISE': 3,
'ROTATE_COUNTERCLOCKWISE': 4,
'HARD_DROP': 5,
'SWAP': 6,
'NO_OP': 7,
}


def make_native_env(instance):
native = gym.make(
instance['env_id'], render_mode='rgb_array',
width=instance['board_width'], height=instance['board_height'],
gravity=instance['gravity'],
)
return RgbObservation(native)


class Adapter:
def __init__(self, instance, assets=None):
self.instance = instance
for name, version in instance['engine_versions'].items():
if importlib.metadata.version(name) != version:
raise ValueError('Tetris dependency version mismatch: ' + name)
self.env = make_native_env(instance)
try:
native = self.env.unwrapped
if (native.width != instance['board_width']
or native.height != instance['board_height']
or native.gravity_enabled is not instance['gravity']
or native.queue.size != instance['native_queue_size']
or native.holder.size != instance['native_holder_size']):
raise ValueError('native Tetris profile mismatch')
image, _ = self.env.reset(seed=instance['seed'])
expected_shape = (native.height_padded,
native.width_padded + native.queue.size * native.padding, 3)
if image.shape != expected_shape or str(image.dtype) != 'uint8':
raise ValueError('native Tetris RGB observation changed')
self.image = image.copy()
except Exception:
self.env.close()
raise
self.total_return = 0.0
self.lines_cleared = 0
self.rewarded_placements = 0
self.line_clear_score = 0
self.ended = False

def spec(self):
return {
'adapter_version': '1.0.0',
'capabilities': Capabilities(images=True, action_mode='enum').to_dict(),
'action_schema': {'type': 'string', 'enum': list(ACTIONS)},
'action_indices': dict(ACTIONS),
'observation': ('Native RGB observation containing the padded board, active piece, '
'four-piece preview queue and one-piece holder; PNG transport only.'),
'goal': 'Clear lines and keep the native Tetris episode alive.',
}

def observe(self):
return {'image_png_base64': png(self.image)}

def step(self, action):
if self.ended:
raise ValueError('episode closed')
if action not in ACTIONS:
raise ValueError('unknown Tetris action')
image, reward, terminated, truncated, info = self.env.step(ACTIONS[action])
reward = float(reward)
lines = info.get('lines_cleared')
if isinstance(lines, bool) or not isinstance(lines, numbers.Integral):
raise ValueError('invalid native line-clear count')
lines = int(lines)
if not 0 <= lines <= 4:
raise ValueError('invalid native line-clear count')
if terminated:
if reward != 0:
raise ValueError('native game-over reward changed')
elif reward:
expected = 1 + (lines ** 2) * self.instance['board_width']
if reward != expected:
raise ValueError('native placement reward changed')
self.rewarded_placements += 1
self.line_clear_score += (lines ** 2) * self.instance['board_width']
self.image = image.copy()
self.total_return += reward
self.lines_cleared += lines
self.ended = bool(terminated or truncated)
return Transition(reward, bool(terminated), bool(truncated))

def success(self):
return self.lines_cleared >= self.instance['target_lines']

def metrics(self):
return {
'success': int(self.success()),
'lines_cleared': self.lines_cleared,
'native_return': self.total_return,
'rewarded_placements': self.rewarded_placements,
'line_clear_score': self.line_clear_score,
}

def fingerprint(self):
native = self.env.unwrapped
randomizer = native.randomizer
holder = [{'id': piece.id, 'matrix': piece.matrix}
for piece in native.holder.queue]
return state_hash({
'board': native.board,
'active': {'id': native.active_tetromino.id,
'matrix': native.active_tetromino.matrix},
'position': [native.x, native.y],
'queue': list(native.queue.queue),
'holder': holder,
'bag': randomizer.bag,
'bag_index': randomizer.index,
'rng': randomizer.rng.bit_generator.state,
'has_swapped': native.has_swapped,
'game_over': native.game_over,
'return': self.total_return,
'lines_cleared': self.lines_cleared,
'rewarded_placements': self.rewarded_placements,
'line_clear_score': self.line_clear_score,
'image': self.image,
})

def frame(self):
return self.image.copy()

def close(self):
self.env.close()
40 changes: 40 additions & 0 deletions game_first_exam/benchmarks/tetris/instance_schema.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
"""Trusted stdlib-only schema for the native Tetris Gymnasium profile."""
from config_schema import validate_engine_versions

SCHEMA_VERSION = '1.0.0'
BENCHMARK = 'tetris'
FIELDS = {'engine_versions', 'board_width', 'board_height', 'gravity',
'native_queue_size', 'native_holder_size', 'target_lines'}
METRICS = {'success', 'lines_cleared', 'native_return', 'rewarded_placements', 'line_clear_score'}
PROFILES = {'native-rgb-board-queue-holder-v1'}
REDUCERS = {('family_macro', '1.0.0')}
ENGINE_VERSIONS = {
'tetris-gymnasium': '0.2.1',
'gymnasium': '1.4.0',
'numpy': '1.26.4',
'opencv-python': '4.10.0.84',
}


def validate(value):
validate_engine_versions(value['engine_versions'], ENGINE_VERSIONS)
if value['env_id'] != 'tetris_gymnasium/Tetris' or value['family'] != 'tetris-classic':
raise ValueError('unsupported Tetris environment/family')
if value['seed'] < 1:
# Upstream 0.2.1 treats seed=0 as an unseeded reset.
raise ValueError('Tetris seed must be positive')
if (value['board_width'], value['board_height'], value['gravity']) != (10, 20, True):
raise ValueError('unsupported Tetris board or gravity profile')
if (value['native_queue_size'], value['native_holder_size']) != (4, 1):
raise ValueError('unsupported native queue/holder profile')
if type(value['target_lines']) is not int or not 1 <= value['target_lines'] <= 1000:
raise ValueError('target_lines must be an integer in [1, 1000]')
if value['max_steps'] is None:
raise ValueError('Tetris requires a public action cap')
if value['capabilities'] != {'images': True, 'action_mode': 'enum',
'timing': 'action-stepped', 'native_truncation': False}:
raise ValueError('unsupported Tetris capabilities')
if value['metric_spec'] != {'primary': 'lines_cleared', 'reducer': 'family_macro',
'reducer_version': '1.0.0',
'success_label': 'target_lines_reached'}:
raise ValueError('unsupported Tetris scoring profile')
25 changes: 25 additions & 0 deletions game_first_exam/benchmarks/tetris/metric_rules.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
"""Validate native Tetris line and reward accounting."""


def validate_metrics(final, instance):
metrics = final['metrics']
expected = {'success', 'lines_cleared', 'native_return',
'rewarded_placements', 'line_clear_score'}
if set(metrics) != expected:
raise ValueError('wrong Tetris metric fields')
for key in ('success', 'lines_cleared', 'rewarded_placements', 'line_clear_score'):
if type(metrics[key]) is not int or metrics[key] < 0:
raise ValueError('invalid Tetris integer metric: ' + key)
if metrics['success'] not in (0, 1):
raise ValueError('invalid Tetris success metric')
if metrics['native_return'] != final['return']:
raise ValueError('inconsistent native Tetris return')
if metrics['native_return'] != metrics['rewarded_placements'] + metrics['line_clear_score']:
raise ValueError('inconsistent native Tetris reward accounting')
success = metrics['lines_cleared'] >= instance['target_lines']
if metrics['success'] != int(success) or final['success'] != (success and not final['sim_error']):
raise ValueError('inconsistent Tetris target success')
if final['steps'] == 0 and any(metrics[key] for key in expected):
raise ValueError('Tetris metrics without an action')
if final['truncated']:
raise ValueError('Tetris declared no native truncation')
10 changes: 10 additions & 0 deletions game_first_exam/benchmarks/tetris/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
cloudpickle==3.1.2
Farama-Notifications==0.0.6
gymnasium==1.4.0
ImageIO==2.38.1
imageio-ffmpeg==0.8.1
numpy==1.26.4
opencv-python==4.10.0.84
pillow==13.0.0
tetris-gymnasium==0.2.1
typing_extensions==4.16.0
11 changes: 11 additions & 0 deletions game_first_exam/images/tetris-files/FILES.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"image": "ghcr.io/mll-lab-nu/efe:tetris-files-0.1.0@sha256:77fd0a3da6746150941ed2072e84555df5ed1c31de7f69afabf36b07218b97ab",
"source": "game_first_exam/benchmarks/tetris",
"files": {
"adapter.py": "69f08c46195cd9e4db7b79ef141043b16956ee55439dc911c241d9ab80537320",
"instance_schema.py": "a46eacce97d460192e39b180ce8d99e5314dd12966f5aa9dca4f2117cc2c3045",
"metric_rules.py": "293c46e15b53ef8eb37ac7b7ea5585f25f6041ac08a46c08ee62544dae29e666",
"requirements.txt": "f7382c7e150ec033919edc7e3f0774f384cc156b764bbda6917a8a768623bb6c",
"SOURCE.json": "2d1d227563329fae4018a96d586398c6c98704e2e8674b8a3458f4a82919bcff"
}
}
3 changes: 3 additions & 0 deletions game_first_exam/images/tetris-files/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Tetris files-only image

Built locally by scripts/files_image.py from the pinned Tetris Gymnasium adapter sources.
1 change: 1 addition & 0 deletions game_first_exam/images/tetris-files/VERSION
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
0.1.0
10 changes: 10 additions & 0 deletions game_first_exam/tests/envs/locks/tetris.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
cloudpickle==3.1.2
Farama-Notifications==0.0.6
gymnasium==1.4.0
ImageIO==2.38.1
imageio-ffmpeg==0.8.1
numpy==1.26.4
opencv-python==4.10.0.84
pillow==13.0.0
tetris-gymnasium==0.2.1
typing_extensions==4.16.0
7 changes: 7 additions & 0 deletions game_first_exam/tests/envs/tetris.Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
FROM docker.io/library/python:3.12.10-slim-bookworm@sha256:fd95fa221297a88e1cf49c55ec1828edd7c5a428187e67b5d1805692d11588db
ENV PYTHONUNBUFFERED=1
RUN apt-get update && apt-get install -y --no-install-recommends libglib2.0-0 libgl1 ca-certificates && rm -rf /var/lib/apt/lists/*
COPY game_first_exam/tests/envs/locks/tetris.txt /requirements.txt
RUN pip install --no-cache-dir --no-deps -r /requirements.txt
RUN pip check
WORKDIR /repo
4 changes: 4 additions & 0 deletions game_first_exam/tests/run.sh
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ case "${1:-common}" in
python3 game_first_exam/tests/test_minihack.py
python3 game_first_exam/tests/test_game_modes_native.py
;;
tetris)
python3 game_first_exam/tests/test_tetris_native.py
python3 game_first_exam/tests/test_tetris_contract.py
;;
minigrid|crafter|textworld|babaisai)
export GAME_TEST_BENCHMARK="$1"
python3 game_first_exam/tests/test_game_adapters.py
Expand Down
Loading