forked from BattlesnakeOfficial/starter-snake-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkeywords.py
More file actions
59 lines (45 loc) · 2.05 KB
/
Copy pathkeywords.py
File metadata and controls
59 lines (45 loc) · 2.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import typing
# Validates and extracts keyword arguments passed to calculation methods.
# Ensures each keyword has the correct type before use.
class Keywords():
def __init__(self):
self.ALLOWED_KEYWORDS = [
"head", "game_state", "body", "neck", "snake",
"calls", "move", "new_head", "safe_moves", "memory_moves", "my_length"
]
self.TYPE_MAP = {
"head": dict,
"game_state": dict,
"neck": dict,
"new_head": dict,
"safe_moves": dict,
"snake": dict,
"body": list,
"memory_moves": list,
"move": str,
"calls": int,
"my_length": int,
}
# Filters kwargs to only include allowed keywords.
# Silently ignores any kwargs that are not in the allowed list.
def get_allowed_keywords(self, **kwargs):
return {key: kwargs[key] for key in self.ALLOWED_KEYWORDS if key in kwargs}
# Validates that each keyword matches its expected type.
# Raises TypeError if a keyword has the wrong type, RuntimeError if it is unlisted.
def check_datatype(self, keywords: typing.Dict):
for key, value in keywords.items():
if key not in self.TYPE_MAP:
raise RuntimeError(f"{key} is not a listed keyword")
if not isinstance(value, self.TYPE_MAP[key]):
raise TypeError(f"{key} requires type {self.TYPE_MAP[key].__name__}")
# Extracts and validates required keywords from kwargs.
# Raises KeyError if a required keyword is missing.
def extract_keywords(self, needed_keywords: typing.List[str], **kwargs):
keywords = self.get_allowed_keywords(**kwargs)
self.check_datatype(keywords)
found_keywords = []
for keyword in needed_keywords:
if keyword not in keywords:
raise KeyError(f"{keyword} is required!")
found_keywords.append(keywords[keyword])
return found_keywords