Skip to content

Commit 0f1d975

Browse files
authored
Merge pull request #956 from Debilski/feature/jsonl
2 parents ff3a48e + fbc0c7b commit 0f1d975

3 files changed

Lines changed: 22 additions & 8 deletions

File tree

pelita/scripts/pelita_main.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -365,7 +365,7 @@ def main():
365365
if pelita.game.controller_await(viewer_state, await_action='set_initial'):
366366
sys.exit(0)
367367

368-
old_game = Path(args.replayfile).read_text().split("\x04")
368+
old_game = Path(args.replayfile).read_text().split("\n")
369369
for state in old_game:
370370
if not state.strip():
371371
continue

pelita/viewer.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -165,18 +165,18 @@ def show_state(self, game_state):
165165

166166

167167
class ReplayWriter:
168-
""" A viewer which dumps to a given stream.
168+
""" A viewer which writes JSONL to a given stream.
169169
"""
170170
def __init__(self, stream):
171171
self.stream = stream
172172

173173
def _send(self, message):
174-
as_json = json.dumps(message, cls=SetEncoder)
175-
self.stream.write(as_json)
176-
# We use 0x04 (EOT) as a separator between the events.
177-
# The additional newline is for improved readability
178-
# and should be ignored by the Python json reader.
179-
self.stream.write("\x04\n")
174+
# Write a record with minimal spacing
175+
# indent=None should ensure that no new lines are introduced
176+
json.dump(message, self.stream, cls=SetEncoder, indent=None, separators=(',', ':'))
177+
178+
# Separate records with a new line
179+
self.stream.write("\n")
180180
self.stream.flush()
181181

182182
def show_state(self, game_state):

test/test_game.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
"""Tests for Pelita game module"""
2+
import tempfile
23
import inspect
34
import itertools
45
import os
@@ -16,6 +17,7 @@
1617
play_turn, run_game, setup_game)
1718
from pelita.layout import parse_layout
1819
from pelita.player import stepping_player, stopping_player
20+
from pelita.viewer import ReplayWriter
1921

2022
_mswindows = (sys.platform == "win32")
2123

@@ -1420,3 +1422,15 @@ def test_games_have_different_uuid():
14201422

14211423
# remainder of the game state is equal
14221424
assert state1 == state2
1425+
1426+
1427+
def test_replay_writer_writes_jsonl():
1428+
with tempfile.TemporaryDirectory() as dir:
1429+
replay_file = Path(dir) / "replay"
1430+
with replay_file.open('w') as f:
1431+
replay_writer = ReplayWriter(f)
1432+
replay_writer.show_state({"a": "\n"})
1433+
replay_writer.show_state({"b": "\r"})
1434+
1435+
# Check that records with new lines are correct
1436+
assert replay_file.read_text().split("\n") == ['{"a":"\\n"}', '{"b":"\\r"}', '']

0 commit comments

Comments
 (0)