-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Function to transform a 2D matrix into Gridworld's serialization format
- Loading branch information
1 parent
630d01f
commit 0cd84ee
Showing
2 changed files
with
227 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
import re | ||
from collections import defaultdict | ||
|
||
from dlgr.griduniverse.experiment import Gridworld | ||
|
||
player_regex = re.compile(r"(p\d+)(c\d+)?") | ||
color_names = Gridworld.player_color_names | ||
|
||
|
||
def matrix2gridworld(matrix): | ||
"""Transform a 2D matrix representing an initial grid state | ||
into the serialized format used by Gridworld. | ||
""" | ||
result = defaultdict(list) | ||
|
||
result["rows"] = len(matrix) | ||
if matrix: | ||
result["columns"] = len(matrix[0]) | ||
else: | ||
result["columns"] = 0 | ||
|
||
for row_num, row in enumerate(matrix): | ||
for col_num, cell in enumerate(row): | ||
position = [col_num, row_num] | ||
cell = cell.strip() | ||
player_match = player_regex.match(cell) | ||
if not cell: | ||
# emtpy | ||
continue | ||
if cell == "w": | ||
result["walls"].append(position) | ||
elif player_match: | ||
id_str, color_str = player_match.groups() | ||
player_id = int(id_str.replace("p", "")) | ||
player_data = { | ||
"id": player_id, | ||
"position": position, | ||
} | ||
if color_str is not None: | ||
player_color_index = int(color_str.replace("c", "")) - 1 | ||
try: | ||
player_data["color"] = color_names[player_color_index] | ||
except IndexError: | ||
max_color = len(color_names) | ||
raise ValueError( | ||
f"Invalid player color specified in {cell}. Max color is {max_color}" | ||
) | ||
|
||
result["players"].append(player_data) | ||
else: | ||
# assume an Item | ||
id_and_maybe_uses = [s.strip() for s in cell.split("|")] | ||
item_data = { | ||
"item_id": id_and_maybe_uses[0], | ||
"position": position, | ||
} | ||
if len(id_and_maybe_uses) == 2: | ||
item_data["remaining_uses"] = int(id_and_maybe_uses[1]) | ||
result["items"].append(item_data) | ||
|
||
return dict(result) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters