338 lines
9.5 kB
1import json
2import logging
3from dataclasses import dataclass
4from typing import Any
5
6logger = logging.getLogger(__name__)
7
8MIN_LEVELS = 10
9MAX_LEVELS = 100
10MIN_MAZE_SIDE = 7
11MAX_MAZE_SIDE = 50
12DEFAULT_HIGHSCORE_FILENAME = "highscores.json"
13
14KNOWN_KEYS = (
15 "highscore_filename",
16 "level",
17 "lives",
18 "pacgum",
19 "points_per_pacgum",
20 "points_per_super_pacgum",
21 "points_per_ghost",
22 "seed",
23 "level_max_time",
24)
25
26
27class ConfigError(Exception):
28 """Raised when the configuration file can't be used at all."""
29
30
31@dataclass(frozen=True)
32class LevelConfig:
33 """Size of one level's maze, in cells.
34
35 Attributes:
36 width: Cells from left to right.
37 height: Cells from top to bottom.
38 """
39
40 width: int
41 height: int
42
43
44DEFAULT_LEVELS = tuple(
45 LevelConfig(15 + index, 15 + index) for index in range(MIN_LEVELS)
46)
47
48
49@dataclass(frozen=True)
50class GameConfig:
51 """Validated game settings.
52
53 Attributes:
54 highscore_filename: File where highscores are saved.
55 levels: Levels in play order.
56 lives: Lives at the start of a game.
57 pacgum: Pacgums placed in each level.
58 points_per_pacgum: Points for a pacgum.
59 points_per_super_pacgum: Points for a super-pacgum.
60 points_per_ghost: Points for an edible ghost.
61 seed: Seed of the first level's maze.
62 level_max_time: Time limit per level, in seconds.
63 """
64
65 highscore_filename: str
66 levels: tuple[LevelConfig, ...]
67 lives: int
68 pacgum: int
69 points_per_pacgum: int
70 points_per_super_pacgum: int
71 points_per_ghost: int
72 seed: int
73 level_max_time: int
74
75
76def load_config(path: str) -> GameConfig:
77 """Read, parse and validate the configuration file.
78
79 Args:
80 path: Path of the JSON config file.
81
82 Returns:
83 The settings, with bad values replaced or clamped.
84
85 Raises:
86 ConfigError: If the file can't be read or parsed.
87 """
88 data = read_config_file(path)
89 for key in data:
90 if key not in KNOWN_KEYS:
91 logger.warning("config: unknown key '%s' ignored", key)
92 return GameConfig(
93 highscore_filename=read_filename(data),
94 levels=read_levels(data),
95 lives=read_int(data, "lives", default=3, low=1, high=10),
96 pacgum=read_int(data, "pacgum", default=42, low=1, high=2500),
97 points_per_pacgum=read_int(
98 data, "points_per_pacgum", default=10, low=0, high=100_000
99 ),
100 points_per_super_pacgum=read_int(
101 data, "points_per_super_pacgum", default=50, low=0, high=100_000
102 ),
103 points_per_ghost=read_int(
104 data, "points_per_ghost", default=200, low=0, high=100_000
105 ),
106 seed=read_int(data, "seed", default=42, low=1, high=2**31 - 1),
107 level_max_time=read_int(
108 data, "level_max_time", default=90, low=10, high=3600
109 ),
110 )
111
112
113def read_config_file(path: str) -> dict[str, Any]:
114 """Read the file and parse it as JSON with comment lines.
115
116 Args:
117 path: Path of the JSON config file.
118
119 Returns:
120 The top-level JSON object.
121
122 Raises:
123 ConfigError: If the file can't be read, isn't valid JSON, or isn't
124 a JSON object.
125 """
126 try:
127 with open(path, encoding="utf-8") as file:
128 text = file.read()
129 except FileNotFoundError:
130 raise ConfigError(f"config file '{path}' does not exist")
131 except IsADirectoryError:
132 raise ConfigError(f"'{path}' is a directory, not a config file")
133 except PermissionError:
134 raise ConfigError(f"no permission to read config file '{path}'")
135 except UnicodeDecodeError:
136 raise ConfigError(f"config file '{path}' is not UTF-8 text")
137 except OSError as error:
138 raise ConfigError(f"can't read config file '{path}': {error}")
139
140 try:
141 data = json.loads(strip_comments(text))
142 except json.JSONDecodeError as error:
143 raise ConfigError(
144 f"config file '{path}' is not valid JSON: {error.msg} "
145 f"(line {error.lineno}, column {error.colno})"
146 )
147 if not isinstance(data, dict):
148 raise ConfigError(
149 f"config file '{path}' must contain a JSON object: {{ ... }}"
150 )
151 return data
152
153
154def strip_comments(text: str) -> str:
155 """Empty the lines that start with '#' or '//'.
156
157 Lines are emptied, not removed, so JSON error line numbers still match
158 the file.
159
160 Args:
161 text: Content of the config file.
162
163 Returns:
164 The text without comments.
165 """
166 lines = []
167 for line in text.splitlines():
168 stripped = line.lstrip()
169 if stripped.startswith("#") or stripped.startswith("//"):
170 lines.append("")
171 else:
172 lines.append(line)
173 return "\n".join(lines)
174
175
176def read_int(
177 data: dict[str, Any],
178 key: str,
179 default: int,
180 low: int,
181 high: int,
182 label: str = "",
183) -> int:
184 """Return data[key] clamped to [low, high], or default if invalid.
185
186 Args:
187 data: JSON object to read from.
188 key: Key of the value.
189 default: Used when the value is missing or not a whole number.
190 low: Smallest allowed value.
191 high: Largest allowed value.
192 label: Name used in warnings. Defaults to the key.
193
194 Returns:
195 A valid value. Every correction is logged.
196 """
197 name = label or f"'{key}'"
198 if key not in data:
199 logger.warning("config: %s is missing, using %d", name, default)
200 return default
201 value = data[key]
202 # bool is a subclass of int in Python, so `true` would pass as 1.
203 if isinstance(value, bool) or not isinstance(value, int):
204 logger.warning(
205 "config: %s must be a whole number, not %s; using %d",
206 name,
207 json.dumps(value),
208 default,
209 )
210 return default
211 if value < low or value > high:
212 clamped = min(max(value, low), high)
213 logger.warning(
214 "config: %s = %d is outside %d..%d; using %d",
215 name,
216 value,
217 low,
218 high,
219 clamped,
220 )
221 return clamped
222 return value
223
224
225def read_filename(data: dict[str, Any]) -> str:
226 """Return the highscore file name, or the default if invalid.
227
228 Args:
229 data: Top-level JSON object.
230
231 Returns:
232 A non-empty file name.
233 """
234 key = "highscore_filename"
235 if key not in data:
236 logger.warning(
237 "config: '%s' is missing, using '%s'",
238 key,
239 DEFAULT_HIGHSCORE_FILENAME,
240 )
241 return DEFAULT_HIGHSCORE_FILENAME
242 value = data[key]
243 if not isinstance(value, str) or not value.strip():
244 logger.warning(
245 "config: '%s' must be a non-empty string, not %s; using '%s'",
246 key,
247 json.dumps(value),
248 DEFAULT_HIGHSCORE_FILENAME,
249 )
250 return DEFAULT_HIGHSCORE_FILENAME
251 return value.strip()
252
253
254def read_levels(data: dict[str, Any]) -> tuple[LevelConfig, ...]:
255 """Return the levels, completed to MIN_LEVELS and cut to MAX_LEVELS.
256
257 Args:
258 data: Top-level JSON object.
259
260 Returns:
261 Valid levels.
262 """
263 if "level" not in data:
264 logger.warning("config: 'level' is missing, using default levels")
265 return DEFAULT_LEVELS
266 entries = data["level"]
267 if not isinstance(entries, list) or not entries:
268 logger.warning(
269 "config: 'level' must be a non-empty list, using default levels"
270 )
271 return DEFAULT_LEVELS
272 if len(entries) > MAX_LEVELS:
273 logger.warning(
274 "config: %d levels given, keeping the first %d",
275 len(entries),
276 MAX_LEVELS,
277 )
278 entries = entries[:MAX_LEVELS]
279
280 levels = [
281 read_level(entry, number)
282 for number, entry in enumerate(entries, start=1)
283 ]
284 if len(levels) < MIN_LEVELS:
285 logger.warning(
286 "config: only %d levels given, at least %d are needed; "
287 "adding default levels %d to %d",
288 len(levels),
289 MIN_LEVELS,
290 len(levels) + 1,
291 MIN_LEVELS,
292 )
293 levels.extend(DEFAULT_LEVELS[len(levels):])
294 return tuple(levels)
295
296
297def read_level(entry: Any, number: int) -> LevelConfig:
298 """Return one level, using defaults for a bad entry or value.
299
300 Args:
301 entry: Value from the 'level' list.
302 number: Position of the level, starting at 1.
303
304 Returns:
305 A level with a valid width and height.
306 """
307 default = DEFAULT_LEVELS[min(number, MIN_LEVELS) - 1]
308 if not isinstance(entry, dict):
309 logger.warning(
310 "config: level %d must be an object like "
311 '{"width": 15, "height": 15}; using %dx%d',
312 number,
313 default.width,
314 default.height,
315 )
316 return default
317 for key in entry:
318 if key not in ("width", "height"):
319 logger.warning(
320 "config: unknown key '%s' in level %d ignored", key, number
321 )
322 width = read_int(
323 entry,
324 "width",
325 default.width,
326 MIN_MAZE_SIDE,
327 MAX_MAZE_SIDE,
328 label=f"level {number} 'width'",
329 )
330 height = read_int(
331 entry,
332 "height",
333 default.height,
334 MIN_MAZE_SIDE,
335 MAX_MAZE_SIDE,
336 label=f"level {number} 'height'",
337 )
338 return LevelConfig(width, height)