-
Notifications
You must be signed in to change notification settings - Fork 0
/
helltaker_solver.py
1458 lines (1252 loc) · 46 KB
/
helltaker_solver.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import abc
import enum
import fileinput
import itertools
import sys
from dataclasses import dataclass
from typing import Tuple, List, Set, Dict, Optional, Union, Generator
import pycosat
from collections import Counter
########################################################################################################################
# Sat Solver
class ILiteral(abc.ABC):
@abc.abstractmethod
def pos(self) -> Literal:
pass
@abc.abstractmethod
def neg(self) -> Literal:
pass
@dataclass(frozen=True)
class Variable(ILiteral):
name: str
def __repr__(self):
return repr(f'V[{self.name}]')
def __str__(self):
return self.name
def __hash__(self):
return hash((self.name))
def pos(self) -> Literal:
return Literal(variable=self, sign=True)
def neg(self) -> Literal:
return Literal(variable=self, sign=False)
def __invert__(self):
return self.neg()
def __lt__(self, other):
if isinstance(other, Variable):
return self.name < other.name
@dataclass(frozen=True)
class Literal(ILiteral):
variable: Variable
sign: bool
def __str__(self):
sign_str = '' if self.sign else '-'
return sign_str + str(self.variable)
def __hash__(self):
return hash((self.variable, self.sign))
def __invert__(self):
return Literal(variable=self.variable, sign=not self.sign)
def pos(self) -> Literal:
return self
def neg(self) -> Literal:
return Literal(variable=self.variable, sign=not self.sign)
@dataclass(frozen=True)
class Clause:
literals: List[Literal]
def __repr__(self):
return str(self)
def __str__(self):
return ' '.join(map(str, self.literals))
def __iter__(self):
return iter(self.literals)
def extend(self, rest):
return Clause(literals=rest + self.literals)
class SatProblem:
variables: Set[Variable]
clauses: List[Clause]
def __init__(self):
self.variables = set()
self.clauses = []
def add_variable(self, name: str) -> Variable:
var = Variable(name=name)
if var in self.variables:
raise ValueError(f'duplicated name: {name}')
self.variables.add(var)
return var
def add_clauses(self, clauses: List[Clause]):
self.clauses.extend(clauses)
def solve(self) -> Union[str, Dict[Variable, bool]]:
variables = enumerate(sorted(self.variables, key=str), start=1)
variable2id = {
v: _id
for _id, v in variables
}
id2variable = {v: k for k, v in variable2id.items()}
cnf = self._convert_to_cnf(variable2id)
solution = pycosat.solve(cnf)
if solution == 'UNSAT':
return 'UNSAT'
return {
id2variable[abs(s)]: s > 0
for s in solution
}
def _convert_to_cnf(self, variable2id: Dict[Variable, int]):
return [
[
(1 if sv.sign else -1) *
variable2id.get(sv.variable)
for sv in c
]
for c in self.clauses
]
########################################################################################################################
# Helltaker Stage Representation
class CellType(enum.Enum):
EMPTY = enum.auto()
STONE = enum.auto()
ENEMY = enum.auto()
WALL = enum.auto()
KEY = enum.auto()
LOCK = enum.auto()
STONE_SPIKE = enum.auto()
SPIKE = enum.auto()
SPIKE_TOGGLE_ACTIVE = enum.auto()
SPIKE_TOGGLE_INACTIVE = enum.auto()
STONE_SPIKE_TOGGLE_INACTIVE = enum.auto()
START = enum.auto()
GOAL = enum.auto()
@classmethod
def from_string(cls, char) -> CellType:
cell = {
'.': cls.EMPTY,
'*': cls.STONE,
'$': cls.STONE_SPIKE,
'E': cls.ENEMY,
'W': cls.WALL,
'K': cls.KEY,
'L': cls.LOCK,
'G': cls.GOAL,
'S': cls.START,
'|': cls.SPIKE,
'A': cls.SPIKE_TOGGLE_ACTIVE,
'_': cls.SPIKE_TOGGLE_INACTIVE,
'2': cls.STONE_SPIKE_TOGGLE_INACTIVE,
}.get(char)
assert cell is not None, f'unexpected char: {char}'
return cell
def is_spike(self):
return self in [
self.SPIKE,
self.STONE_SPIKE,
self.SPIKE_TOGGLE_ACTIVE,
self.SPIKE_TOGGLE_INACTIVE,
self.STONE_SPIKE_TOGGLE_INACTIVE,
]
def is_spike_toggle(self):
return self in [
self.SPIKE_TOGGLE_ACTIVE,
self.SPIKE_TOGGLE_INACTIVE,
self.STONE_SPIKE_TOGGLE_INACTIVE,
]
def is_spike_toggle_inactive(self):
return self in [
self.SPIKE_TOGGLE_INACTIVE,
self.STONE_SPIKE_TOGGLE_INACTIVE,
]
def is_constant_spike(self):
return self in [
self.SPIKE,
self.STONE_SPIKE,
]
def is_stone(self):
return self in [
self.STONE,
self.STONE_SPIKE,
self.STONE_SPIKE_TOGGLE_INACTIVE,
]
class StageDataValidator:
@staticmethod
def validate(data: StageData) -> None:
"""
:raises ValueError: if invalid
"""
same_all_line_length = len(set(len(line) for line in data)) == 1
assert same_all_line_length, "Data shape should be rectangle"
# for simplicity, this solver restricts the number of keys,
# To mitigate this restriction, change HelltakerSatProblemGenerator to support multiple keys.
# To do that, needs to hold the number of keys/locks somehow.
cell_type2num = Counter(cell for line in data for cell in line)
assert cell_type2num.get(CellType.KEY, 0) <= 1, 'number of keys must be up to 1.'
assert cell_type2num.get(CellType.LOCK, 0) <= 1, 'number of locks must be up to 1.'
@dataclass(frozen=True)
class StageData:
MapData = Tuple[Tuple[CellType, ...], ...]
map: MapData
width: int
height: int
steps: int
@classmethod
def from_string(cls, body: str):
lines = body.splitlines()
steps = int(lines[0])
map_lines = lines[1:]
data = tuple([
tuple(
[
CellType.from_string(char)
for char in line
]
)
for line in map_lines
])
instance = cls(
steps=steps,
map=data,
width=len(data[0]),
height=len(data),
)
StageDataValidator.validate(instance)
return instance
def get_cell(self, x: int, y: int) -> CellType:
assert 0 <= x < self.width and 0 <= y < self.height
return self.map[y][x]
def __iter__(self):
return iter(self.map)
def items(self) -> Generator[Tuple[Tuple[XCoord, YCoord], CellType], None, None]:
return (
((x, y), cell)
for y, y_data in enumerate(self.map)
for x, cell in enumerate(y_data)
)
########################################################################################################################
# Helltaker Solver
Step = int
XCoord = int
YCoord = int
StepPos = Tuple[Step, XCoord, YCoord]
GenericVariable = Union[Literal, Variable]
def gen_any_rules(variables: List[ILiteral]) -> List[Clause]:
return [
Clause([v.pos() for v in variables]) # not all false
]
def gen_no_two_true_rules(variables: List[ILiteral]) -> List[Clause]:
return [
Clause([v1.neg(), v2.neg()])
for (v1, v2) in itertools.product(variables, repeat=2)
if v1 != v2
]
def gen_unique_true_rules(variables: List[ILiteral]) -> List[Clause]:
is_not_all_false = [Clause([v.pos() for v in variables])]
no_two_trues = gen_no_two_true_rules(variables)
return is_not_all_false + no_two_trues
def gen_exists_then_true_rule(conditions: List[ILiteral], then: ILiteral):
return [
Clause([cond.neg(), then.pos()])
for cond in conditions
] + [
Clause([c.pos() for c in conditions] + [then.neg()])
]
def all_then(conditions: List[ILiteral],
then: Union[ILiteral, List[ILiteral]]):
if not isinstance(then, list):
then = [then]
return [
Clause(
[
cond.neg()
for cond in conditions
] + [
_then.pos()
]
)
for _then in then
]
def gen_single_false_and_then_true_rule(conditions: List[ILiteral], then: ILiteral):
return [
Clause(
[
c.neg()
for c in conditions
if c != focus_cond
] + [
focus_cond.pos()
] + [
then.pos()
]
)
for focus_cond in conditions
]
def gen_all_and_then_no_two_true_rules(
conditions: List[ILiteral],
then_uniques: List[ILiteral],
) -> List[Clause]:
return [
c.extend([
v.neg()
for v in conditions
])
for c in gen_no_two_true_rules(then_uniques)
]
@dataclass(frozen=True)
class CellState:
steppos: StepPos
is_empty: Variable
is_stone: Variable
is_enemy: Variable
is_player: Variable
is_wall: Variable
is_goal: Variable
is_lock: Variable
is_lock_next: Variable
is_spike: Variable
is_spike_active: Variable
is_enemy_pre: Variable
# Util variables
is_blocker: Variable
is_not_kickable: Variable
@classmethod
def create(cls, steppos: StepPos, problem: SatProblem) -> CellState:
step, x, y = steppos
prefix = f'S{step:02d}:S:X{x:02d}Y{y:02d}'
return cls(
steppos=steppos,
is_empty=problem.add_variable(f'{prefix}:empty'),
is_stone=problem.add_variable(f'{prefix}:stone'),
is_enemy=problem.add_variable(f'{prefix}:enemy'),
is_player=problem.add_variable(f'{prefix}:player'),
is_wall=problem.add_variable(f'{prefix}:wall'),
is_goal=problem.add_variable(f'{prefix}:goal'),
is_lock=problem.add_variable(f'{prefix}:lock'),
is_lock_next=problem.add_variable(f'{prefix}:lock_next'),
is_blocker=problem.add_variable(f'{prefix}:blocker'),
is_not_kickable=problem.add_variable(f'{prefix}:notkickable'),
is_spike=problem.add_variable(f'{prefix}:spike'),
is_spike_active=problem.add_variable(f'{prefix}:spike_a'),
is_enemy_pre=problem.add_variable(f'{prefix}:enemy_pre'),
)
def gen_rules(self) -> List[Clause]:
return gen_unique_true_rules([
self.is_empty,
self.is_stone,
self.is_enemy,
self.is_player,
self.is_wall,
self.is_goal,
self.is_lock_next,
]) + gen_exists_then_true_rule(
conditions=[self.is_wall, self.is_enemy, self.is_stone, self.is_goal, self.is_lock_next],
then=self.is_blocker,
) + self.gen_kickable_rules() + self.gen_enemy_pre_rules()
def gen_kickable_rules(self):
return \
gen_exists_then_true_rule(
conditions=[self.is_wall, self.is_goal],
then=self.is_not_kickable,
)
def gen_spike_rules(self):
return \
all_then(
conditions=[self.is_spike.neg()],
then=self.is_spike_active.neg(),
)
def gen_enemy_pre_rules(self):
return \
all_then(
conditions=[self.is_spike, self.is_spike_active, self.is_enemy_pre],
then=self.is_enemy.neg(),
) + all_then(
conditions=[self.is_spike, self.is_spike_active.neg(), self.is_enemy_pre],
then=self.is_enemy.pos(),
) + all_then(
conditions=[self.is_spike.neg(), self.is_enemy_pre.neg()],
then=self.is_enemy.neg(),
) + all_then(
conditions=[self.is_spike.neg(), self.is_enemy_pre.pos()],
then=self.is_enemy.pos(),
)
@dataclass(frozen=True)
class UserInput:
step: Step
is_left: Variable
is_up: Variable
is_right: Variable
is_down: Variable
skip: Variable
def gen_rules(self) -> List[Clause]:
return gen_unique_true_rules([
self.is_left,
self.is_up,
self.is_right,
self.is_down,
self.skip,
])
@classmethod
def create(cls, step: Step, problem: SatProblem):
return cls(
step=step,
is_down=problem.add_variable(f'S{step:02d}:C:down'),
is_left=problem.add_variable(f'S{step:02d}:C:left'),
is_right=problem.add_variable(f'S{step:02d}:C:right'),
is_up=problem.add_variable(f'S{step:02d}:C:up'),
skip=problem.add_variable(f'S{step:02d}:C:skip'),
)
StageStates: Dict[StepPos, CellState]
ControlStates: Dict[Step, UserInput]
@dataclass(frozen=True)
class AuxStates:
has_key: Dict[Step, Variable]
@classmethod
def create(cls, steps: int, problem: SatProblem):
return cls(
has_key={
step: problem.add_variable(f'S{step:02d}:Aux:has_key')
for step in range(steps + 1)
},
)
class HelltakerProblem:
stage_data: StageData
stage_states: StageStates
control_states: ControlStates
aux_states: AuxStates
problem: SatProblem
solution: Optional[Union[Dict[Variable, bool], str]]
def __init__(
self,
stage_data: StageData,
stage_states: StageStates,
control_states: ControlStates,
aux_states: AuxStates,
problem: SatProblem):
self.stage_data = stage_data
self.stage_states = stage_states
self.control_states = control_states
self.aux_states = aux_states
self.problem = problem
self.solution = None
def solve(self):
self.solution = self.problem.solve()
def visualize(self):
for step in range(self.stage_data.steps, -1, -1):
print(f'Step: {step:02d}, {self._format_control(step):<6s} {self._format_aux_state(step)}')
print(self._format_step(step=step))
print()
def show_steps(self):
steps_range = range(self.stage_data.steps, -1, -1)
controls = [['', 0]]
for control in (f'{self._format_control(step)}' for step in steps_range):
if control == 'Skip':
continue
if controls[-1][0] == control:
controls[-1][1] += 1
else:
controls.append([control, 1])
# omit fake initial value
controls = controls[1:]
print('\n'.join(f'{control:<5s} x{num}' for control, num in controls))
def get_solution(self) -> Union[str, List[Tuple[str, str]]]:
assert self.solution is not None, 'call solve'
if self.solution == 'UNSAT':
return 'UNSAT'
return [
(
self._format_control(step),
self._format_step(step=step)
)
for step in range(self.stage_data.steps, -1, -1)
]
def _format_control(self, step: Step) -> str:
if step == 0:
return 'N/A'
control_state: UserInput = self.control_states[step]
if self.solution[control_state.is_up]:
return 'Up'
if self.solution[control_state.is_down]:
return 'Down'
if self.solution[control_state.is_left]:
return 'Left'
if self.solution[control_state.is_right]:
return 'Right'
if self.solution[control_state.skip]:
return 'Skip'
return '-----'
def _format_step(self, step: Step) -> str:
return '\n'.join(
''.join(
self._format_cell(steppos=(step, x, y))
for x in range(self.stage_data.width)
)
for y in range(self.stage_data.height)
)
def _format_cell(self, steppos: StepPos) -> str:
cell_state: CellState = self.stage_states[steppos]
step, x, y = steppos
if self.solution[cell_state.is_stone]:
return '*'
if self.solution[cell_state.is_wall]:
return 'W'
if self.solution[cell_state.is_enemy]:
return 'E'
if self.solution[cell_state.is_player]:
return 'P'
if self.solution[cell_state.is_lock]:
return 'L'
if self.stage_data.get_cell(x=x, y=y) == CellType.KEY:
return 'K'
if self.solution[cell_state.is_spike_active]:
return 'A'
if self.solution[cell_state.is_spike]:
return '_'
if self.stage_data.get_cell(x=x, y=y) == CellType.START:
return 'S'
if self.stage_data.get_cell(x=x, y=y) == CellType.GOAL:
return 'G'
if self.solution[cell_state.is_lock]:
return 'L'
if self.solution[cell_state.is_empty]:
return '.'
return '?'
def _format_aux_state(self, step):
has_key = self.aux_states.has_key[step]
if self.solution[has_key]:
return 'Key'
return ''
def _next_steppos(steppos: StepPos) -> StepPos:
step, x, y = steppos
return (step - 1, x, y)
def _prev_steppos(steppos: StepPos) -> StepPos:
step, x, y = steppos
return (step + 1, x, y)
class HelltakerProblemFactory:
_stage_data: StageData
def __init__(self, stage_data: StageData):
self._stage_data = stage_data
def generate_problem(self) -> HelltakerProblem:
sat_problem = SatProblem()
helltaker_problem = HelltakerProblem(
stage_data=self._stage_data,
stage_states=self._create_stage_states(sat_problem),
control_states=self._create_control_states(sat_problem),
aux_states=self._create_aux_states(sat_problem),
problem=sat_problem,
)
self._setup_init_state(helltaker_problem=helltaker_problem)
self._setup_final_state(helltaker_problem=helltaker_problem)
self._setup_movement_rules(helltaker_problem=helltaker_problem)
self._setup_kickable_rules(helltaker_problem=helltaker_problem)
self._setup_skip_rules(helltaker_problem=helltaker_problem)
self._setup_spike_state(helltaker_problem=helltaker_problem)
self._setup_stone_available_rules(helltaker_problem=helltaker_problem)
self._setup_stone_rules(helltaker_problem=helltaker_problem)
self._setup_has_key_rules(helltaker_problem=helltaker_problem)
self._setup_lock_rules(helltaker_problem=helltaker_problem)
self._setup_enemy_rules(helltaker_problem=helltaker_problem)
return helltaker_problem
def _create_stage_states(self, problem: SatProblem) -> StageStates:
stage_states: StageStates = {}
height = self._stage_data.height
width = self._stage_data.width
for step in range(self._stage_data.steps + 1):
for y in range(height):
for x in range(width):
steppos = (step, x, y)
state = CellState.create(steppos=steppos, problem=problem)
stage_states[steppos] = state
problem.add_clauses(state.gen_rules())
for step in range(self._stage_data.steps + 1):
# single player state
rules = gen_unique_true_rules([
stage_states[(step, x, y)].is_player
for y in range(height)
for x in range(width)
])
problem.add_clauses(rules)
return stage_states
def _create_control_states(self, problem: SatProblem) -> ControlStates:
control_states: ControlStates = {}
for step in range(1, self._stage_data.steps + 1):
state = UserInput.create(step=step, problem=problem)
control_states[step] = state
problem.add_clauses(state.gen_rules())
return control_states
def _create_aux_states(self, sat_problem: SatProblem):
return AuxStates.create(self._stage_data.steps, sat_problem)
def _setup_movement_rules(self, helltaker_problem: HelltakerProblem):
problem: SatProblem = helltaker_problem.problem
control_states: ControlStates = helltaker_problem.control_states
stage_states: StageStates = helltaker_problem.stage_states
stage_data: StageData = helltaker_problem.stage_data
clauses = []
for steppos, state in stage_states.items():
(step, x, y) = steppos
if step <= 0:
continue
control: UserInput = control_states[step]
y_minus = max(y - 1, 0)
y_plus = min(y + 1, stage_data.height - 1)
x_minus = max(x - 1, 0)
x_plus = min(x + 1, stage_data.width - 1)
pos_up = (step, x, y_minus)
pos_down = (step, x, y_plus)
pos_right = (step, x_plus, y)
pos_left = (step, x_minus, y)
clauses.extend([
# up no move
all_then(
conditions=[stage_states.get(pos_up).is_blocker, stage_states.get(steppos).is_player, control.is_up],
then=stage_states.get(_next_steppos(steppos)).is_player,
),
# up move
all_then(
conditions=[~stage_states.get(pos_up).is_blocker, stage_states.get(steppos).is_player, control.is_up],
then=[
stage_states.get(_next_steppos(steppos)).is_empty,
stage_states.get(_next_steppos(pos_up)).is_player,
],
),
# down no move
all_then(
conditions=[stage_states.get(pos_down).is_blocker, stage_states.get(steppos).is_player, control.is_down],
then=stage_states.get(_next_steppos(steppos)).is_player,
),
# down move
all_then(
conditions=[~stage_states.get(pos_down).is_blocker, stage_states.get(steppos).is_player, control.is_down],
then=[
stage_states.get(_next_steppos(steppos)).is_empty,
stage_states.get(_next_steppos(pos_down)).is_player,
],
),
# left no move
all_then(
conditions=[stage_states.get(pos_left).is_blocker, stage_states.get(steppos).is_player, control.is_left],
then=stage_states.get(_next_steppos(steppos)).is_player,
),
# left move
all_then(
conditions=[~stage_states.get(pos_left).is_blocker, stage_states.get(steppos).is_player, control.is_left],
then=[
stage_states.get(_next_steppos(steppos)).is_empty,
stage_states.get(_next_steppos(pos_left)).is_player,
],
),
# right no move
all_then(
conditions=[stage_states.get(pos_right).is_blocker, stage_states.get(steppos).is_player, control.is_right],
then=stage_states.get(_next_steppos(steppos)).is_player,
),
# right move
all_then(
conditions=[~stage_states.get(pos_right).is_blocker, stage_states.get(steppos).is_player, control.is_right],
then=[
stage_states.get(_next_steppos(steppos)).is_empty,
stage_states.get(_next_steppos(pos_right)).is_player,
],
),
# skip
all_then(
conditions=[stage_states.get(steppos).is_player, control.skip],
then=stage_states.get(_next_steppos(steppos)).is_player,
)
])
problem.add_clauses(sum(clauses, []))
def _setup_movement_available_rules(self, helltaker_problem: HelltakerProblem):
problem: SatProblem = helltaker_problem.problem
stage_states: StageStates = helltaker_problem.stage_states
stage_data: StageData = helltaker_problem.stage_data
clauses = []
for steppos, state in stage_states.items():
(step, x, y) = steppos
if stage_data.steps > step:
clauses.extend(
all_then(
conditions=[stage_states.get(c).is_player.neg() for c in self._adjacent_cells(step + 1, x, y)],
then=stage_states.get(steppos).is_player.neg(),
)
)
problem.add_clauses(clauses)
def _setup_stone_available_rules(self, helltaker_problem: HelltakerProblem):
problem: SatProblem = helltaker_problem.problem
stage_states: StageStates = helltaker_problem.stage_states
stage_data: StageData = helltaker_problem.stage_data
clauses = []
for steppos, state in stage_states.items():
(step, x, y) = steppos
if stage_data.steps > step:
clauses.extend(
all_then(
conditions=[stage_states.get(c).is_stone.neg() for c in self._adjacent_cells(step + 1, x, y)],
then=stage_states.get(steppos).is_stone.neg(),
)
)
problem.add_clauses(clauses)
def _setup_enemy_rules(self, helltaker_problem: HelltakerProblem):
problem: SatProblem = helltaker_problem.problem
control_states: ControlStates = helltaker_problem.control_states
stage_states: StageStates = helltaker_problem.stage_states
def _gen_rule(ctrl: Variable, steppos_from: StepPos, steppos_player: StepPos, steppos_to: StepPos):
clauses = []
next_steppos_from = _next_steppos(steppos_from)
next_steppos_player = _next_steppos(steppos_player)
next_steppos_to = _next_steppos(steppos_to)
if not all(map(self._is_in_stage, [steppos_from, steppos_player, next_steppos_from, next_steppos_player])):
return []
# Kill/move enemy when kicked.
move_conditions: List[Literal] = [
ctrl.pos(),
stage_states.get(steppos_from).is_player.pos(),
stage_states.get(steppos_player).is_enemy.pos()
]
clauses.extend(all_then(
conditions=move_conditions,
then=stage_states.get(next_steppos_player).is_enemy_pre.neg(),
))
# Move enemy if `to` is empty.
if self._is_in_stage(steppos_to):
clauses.extend(all_then(
conditions=move_conditions + [stage_states.get(steppos_to).is_empty.pos()],
then=stage_states.get(next_steppos_to).is_enemy_pre.pos(),
))
# Stay if control is not applicable
clauses.extend(all_then(
conditions=[
ctrl.neg(),
stage_states.get(steppos_from).is_player.pos(),
stage_states.get(steppos_player).is_enemy.pos(),
],
then=stage_states.get(next_steppos_player).is_enemy_pre.pos(),
))
clauses.extend(all_then(
conditions=[
ctrl.neg(),
stage_states.get(steppos_from).is_player.pos(),
stage_states.get(steppos_player).is_enemy.neg(),
],
then=stage_states.get(next_steppos_player).is_enemy_pre.neg(),
))
# Keep empty in player cell if control is not applicable
clauses.extend(all_then(
conditions=[
ctrl.neg(),
stage_states.get(steppos_from).is_player.pos(),
stage_states.get(steppos_player).is_enemy.neg(),
],
then=stage_states.get(next_steppos_player).is_enemy_pre.neg(),
))
clauses.extend(all_then(
conditions=[
ctrl.neg(),
stage_states.get(steppos_from).is_player.pos(),
stage_states.get(steppos_player).is_enemy.pos(),
],
then=stage_states.get(steppos_player).is_enemy_pre.pos(),
))
if self._is_in_stage(steppos_to):
# keep `to` state if not applicable
clauses.extend(all_then(
conditions=[
ctrl.neg(),
stage_states.get(steppos_from).is_player.pos(),
stage_states.get(steppos_to).is_enemy.neg(),
],
then=stage_states.get(next_steppos_to).is_enemy_pre.neg(),
))
clauses.extend(all_then(
conditions=[
ctrl.pos(),
stage_states.get(steppos_from).is_player.pos(),
stage_states.get(steppos_player).is_enemy.neg(),
stage_states.get(steppos_to).is_enemy.neg(),
],
then=stage_states.get(next_steppos_to).is_enemy_pre.neg(),
))
return clauses
clauses = []
for steppos, state in stage_states.items():
(step, x, y) = steppos
next_steppos = (step - 1, x, y)
if step == 0:
continue
# Enemy do not pop up from void
clauses.extend(
all_then(
conditions=[stage_states.get(c).is_enemy.neg() for c in self._adjacent_cells(*steppos)],
then=[
stage_states.get(next_steppos).is_enemy_pre.neg(),
stage_states.get(next_steppos).is_enemy.neg(),
]
)
)
# Enemy stey keep if player is not in adj
clauses.extend(
all_then(
conditions=[
stage_states.get(c).is_player.neg() for c in self._adjacent_cells(*steppos)
] + [stage_states.get(steppos).is_enemy],
then=stage_states.get(next_steppos).is_enemy_pre,
)
)
clauses.extend(
all_then(
conditions=[
stage_states.get(c).is_player.neg() for c in self._adjacent_cells(*steppos, delta=2)
] + [stage_states.get(steppos).is_enemy.neg()],
then=stage_states.get(next_steppos).is_enemy_pre.neg(),
)
)
control = control_states[step]
steppos_left = (step, x - 1, y)
steppos_right = (step, x + 1, y)
steppos_up = (step, x, y - 1)
steppos_down = (step, x, y + 1)
clauses.extend(_gen_rule(control.is_right, steppos_left, steppos, steppos_right))
clauses.extend(_gen_rule(control.is_left, steppos_right, steppos, steppos_left))
clauses.extend(_gen_rule(control.is_down, steppos_up, steppos, steppos_down))
clauses.extend(_gen_rule(control.is_up, steppos_down, steppos, steppos_up))
problem.add_clauses(clauses)
def _setup_stone_rules(self, helltaker_problem: HelltakerProblem):
problem: SatProblem = helltaker_problem.problem
control_states: ControlStates = helltaker_problem.control_states
stage_states: StageStates = helltaker_problem.stage_states
def _gen_rule(ctrl: Variable, steppos_from: StepPos, steppos_player: StepPos, steppos_to: StepPos):
clauses = []
next_steppos_from = _next_steppos(steppos_from)
next_steppos_player = _next_steppos(steppos_player)
next_steppos_to = _next_steppos(steppos_to)
if not all(map(self._is_in_stage, [steppos_from, steppos_player, next_steppos_from, next_steppos_player])):
return []
# Move/stay stone when kicked.
move_conditions: List[Literal] = [
ctrl.pos(),
stage_states.get(steppos_from).is_player.pos(),
stage_states.get(steppos_player).is_stone.pos()
]
if self._is_in_stage(steppos_to):
# move if empty
clauses.extend(all_then(
conditions=move_conditions + [stage_states.get(steppos_to).is_empty.pos()],
then=stage_states.get(next_steppos_to).is_stone.pos(),
))
# stay if not empty
clauses.extend(all_then(
conditions=move_conditions + [stage_states.get(steppos_to).is_empty.neg()],
then=stage_states.get(next_steppos_player).is_stone.pos(),
))
else:
# stay
clauses.extend(all_then(
conditions=move_conditions,
then=stage_states.get(next_steppos_player).is_stone.pos(),
))
# Stay if control is not applicable
clauses.extend(all_then(
conditions=[
ctrl.neg(),
stage_states.get(steppos_from).is_player.pos(),
stage_states.get(steppos_player).is_stone.pos(),