|
| 1 | +import os |
| 2 | +import re |
| 3 | + |
| 4 | +import pacai.util.file |
| 5 | +import pacai.util.json |
| 6 | +import pacai.util.reflection |
| 7 | + |
| 8 | +THIS_DIR: str = os.path.join(os.path.dirname(os.path.realpath(__file__))) |
| 9 | +BOARDS_DIR: str = os.path.join(THIS_DIR, '..', 'boards') |
| 10 | + |
| 11 | +SEPARATOR_PATTERN: re.Pattern = re.compile(r'^\s*-{3,}\s*$') |
| 12 | + |
| 13 | +DEFAULT_BOARD_CLASS = 'pacai.core.board.Board' |
| 14 | + |
1 | 15 | class Board: |
2 | 16 | """ |
3 | 17 | A board represents the static (non-agent) components of a game. |
4 | | - For example, a layout contains the walls and collectable items. |
| 18 | + For example, a board contains the walls and collectable items. |
| 19 | +
|
| 20 | + Most types of games (anything that would subclass pacai.core.game.Game) should probably |
| 21 | + also subclass this to make their own type of board. |
| 22 | +
|
| 23 | + On disk, boards are represented in files that have two sections (divided by a '---' line). |
| 24 | + The first section is a JSON object that holds any options for the board. |
| 25 | + The second section is a textual representation of the board. |
| 26 | + The specific board class (usually specified by the board options) should know how to interpret the text-based board. |
5 | 27 | """ |
6 | 28 |
|
7 | | - # TEST |
8 | | - pass |
| 29 | + def __init__(self, marker_wall = '%', **kwargs) -> None: |
| 30 | + # TEST |
| 31 | + pass |
| 32 | + |
| 33 | +def load_path(path: str) -> Board: |
| 34 | + """ Load a board from a file. """ |
| 35 | + |
| 36 | + text = pacai.util.file.read(path, strip = False) |
| 37 | + return load_string(text) |
| 38 | + |
| 39 | +def load_string(text: str) -> Board: |
| 40 | + """ Load a board from a string. """ |
| 41 | + |
| 42 | + separator_index = -1 |
| 43 | + lines = text.split("\n") |
| 44 | + |
| 45 | + for i in range(len(lines)): |
| 46 | + if (SEPARATOR_PATTERN.match(lines[i])): |
| 47 | + separator_index = i |
| 48 | + break |
| 49 | + |
| 50 | + if (separator_index == -1): |
| 51 | + # No separator was found. |
| 52 | + options_text = '' |
| 53 | + board_text = "\n".join(lines) |
| 54 | + else: |
| 55 | + options_text = "\n".join(lines[:i]) |
| 56 | + board_text = "\n".join(lines[(i + 1):]) |
| 57 | + |
| 58 | + options_text = options_text.strip() |
| 59 | + if (len(options_text) == 0): |
| 60 | + options = {} |
| 61 | + else: |
| 62 | + options = pacai.util.json.loads(options_text) |
| 63 | + |
| 64 | + board_class = options.get('class', DEFAULT_BOARD_CLASS) |
| 65 | + return pacai.util.reflection.new_object(board_class, **options) |
0 commit comments