-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandheld_game_console.py
63 lines (49 loc) · 1.75 KB
/
handheld_game_console.py
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
60
61
62
63
import typing
class Arg:
def __init__(self, value: str) -> None:
self._value = value
def value(self, computer: "HandheldGameConsole") -> int:
return int(self._value)
class HandheldGameConsole:
def __init__(self, instructions: list[tuple[str, list[Arg]]]) -> None:
self.accumulator = 0
self.ip = 0
self.instructions = instructions
self.last_instruction = ""
@property
def halted(self) -> bool:
return self.ip >= len(self.instructions)
@classmethod
def load_from_string(cls, instructions: str):
return cls(
[
(opc, list(map(Arg, opr.split(","))))
for opc, opr in [
line.split(maxsplit=1) for line in instructions.splitlines()
]
]
)
def acc(self, operand: Arg) -> None:
self.accumulator += operand.value(self)
self.ip += 1
def jmp(self, operand: Arg) -> None:
self.ip += operand.value(self)
def nop(self, _: Arg) -> None:
self.ip += 1
def step(self) -> None:
opc, opr = self.instructions[self.ip]
self.last_instruction = opc
getattr(self, opc)(*opr)
def run_until_opcode(self, opcode: str) -> None:
self.step() # ensure that we run at least one instruction
while self.last_instruction != opcode and not self.halted:
self.step()
def run_until_condition(
self, condition: typing.Callable[["HandheldGameConsole"], bool]
) -> None:
self.step() # ensure that we run at least one instruction
while (not condition(self)) and not self.halted:
self.step()
def run_until_complete(self) -> None:
while not self.halted:
self.step()