Restructured code
This commit is contained in:
208
shenzhen_solitaire/solver/board_actions.py
Normal file
208
shenzhen_solitaire/solver/board_actions.py
Normal file
@@ -0,0 +1,208 @@
|
||||
"""Contains actions that can be used on the board"""
|
||||
from typing import List, Tuple
|
||||
from dataclasses import dataclass
|
||||
from .. import board
|
||||
|
||||
|
||||
class Action:
|
||||
"""Base class for a card move action on a solitaire board"""
|
||||
_before_state: int = 0
|
||||
_after_state: int = 0
|
||||
|
||||
def _apply(self, action_board: board.Board) -> None:
|
||||
pass
|
||||
|
||||
def _undo(self, action_board: board.Board) -> None:
|
||||
pass
|
||||
|
||||
def apply(self, action_board: board.Board) -> None:
|
||||
"""Apply action to board"""
|
||||
if __debug__:
|
||||
self._before_state = action_board.state_identifier
|
||||
self._apply(action_board)
|
||||
if __debug__:
|
||||
self._after_state = action_board.state_identifier
|
||||
|
||||
def undo(self, action_board: board.Board) -> None:
|
||||
"""Undo action to board"""
|
||||
assert action_board.state_identifier == self._after_state
|
||||
self._undo(action_board)
|
||||
assert action_board.state_identifier == self._before_state
|
||||
|
||||
|
||||
@dataclass
|
||||
class GoalAction(Action):
|
||||
"""Move card from field to goal"""
|
||||
|
||||
card: board.NumberCard
|
||||
source_id: int
|
||||
source_position: board.Position
|
||||
|
||||
def _apply(self, action_board: board.Board) -> None:
|
||||
"""Do action"""
|
||||
if self.source_position == board.Position.Field:
|
||||
assert action_board.field[self.source_id][-1] == self.card
|
||||
assert action_board.goal[self.card.suit] + 1 == self.card.number
|
||||
action_board.field[self.source_id].pop()
|
||||
action_board.goal[self.card.suit] += 1
|
||||
elif self.source_position == board.Position.Bunker:
|
||||
assert action_board.bunker[self.source_id] == self.card
|
||||
assert action_board.goal[self.card.suit] + 1 == self.card.number
|
||||
action_board.bunker[self.source_id] = None
|
||||
action_board.goal[self.card.suit] += 1
|
||||
else:
|
||||
raise RuntimeError("Unknown position")
|
||||
|
||||
def _undo(self, action_board: board.Board) -> None:
|
||||
"""Undo action"""
|
||||
assert action_board.goal[self.card.suit] == self.card.number
|
||||
if self.source_position == board.Position.Field:
|
||||
action_board.field[self.source_id].append(self.card)
|
||||
elif self.source_position == board.Position.Bunker:
|
||||
assert action_board.bunker[self.source_id] is None
|
||||
action_board.bunker[self.source_id] = self.card
|
||||
else:
|
||||
raise RuntimeError("Unknown position")
|
||||
action_board.goal[self.card.suit] -= 1
|
||||
|
||||
|
||||
@dataclass
|
||||
class BunkerizeAction(Action):
|
||||
"""Move card from bunker to field"""
|
||||
|
||||
card: board.Card
|
||||
bunker_id: int
|
||||
field_id: int
|
||||
to_bunker: bool
|
||||
|
||||
def _move_from_bunker(self, action_board: board.Board) -> None:
|
||||
assert action_board.bunker[self.bunker_id] == self.card
|
||||
action_board.bunker[self.bunker_id] = None
|
||||
action_board.field[self.field_id].append(self.card)
|
||||
|
||||
def _move_to_bunker(self, action_board: board.Board) -> None:
|
||||
assert action_board.field[self.field_id][-1] == self.card
|
||||
assert action_board.bunker[self.bunker_id] is None
|
||||
action_board.bunker[self.bunker_id] = self.card
|
||||
action_board.field[self.field_id].pop()
|
||||
|
||||
def _apply(self, action_board: board.Board) -> None:
|
||||
"""Do action"""
|
||||
if self.to_bunker:
|
||||
self._move_to_bunker(action_board)
|
||||
else:
|
||||
self._move_from_bunker(action_board)
|
||||
|
||||
def _undo(self, action_board: board.Board) -> None:
|
||||
"""Undo action"""
|
||||
if self.to_bunker:
|
||||
self._move_from_bunker(action_board)
|
||||
else:
|
||||
self._move_to_bunker(action_board)
|
||||
|
||||
|
||||
@dataclass
|
||||
class MoveAction(Action):
|
||||
"""Moving a card from one field stack to another"""
|
||||
|
||||
cards: List[board.Card]
|
||||
source_id: int
|
||||
destination_id: int
|
||||
|
||||
def _shift(
|
||||
self,
|
||||
action_board: board.Board,
|
||||
source: int,
|
||||
dest: int) -> None:
|
||||
"""Shift a card from the field id 'source' to field id 'dest'"""
|
||||
|
||||
for stack_offset, card in enumerate(
|
||||
self.cards, start=-len(self.cards)):
|
||||
assert action_board.field[source][stack_offset] == card
|
||||
|
||||
action_board.field[source] = action_board.field[
|
||||
source][:-len(self.cards)]
|
||||
action_board.field[dest].extend(self.cards)
|
||||
|
||||
def _apply(self, action_board: board.Board) -> None:
|
||||
"""Do action"""
|
||||
if action_board.field[self.destination_id]:
|
||||
dest_card = action_board.field[self.destination_id][-1]
|
||||
if not all(isinstance(x, board.NumberCard) for x in self.cards):
|
||||
raise AssertionError()
|
||||
if not isinstance(dest_card, board.NumberCard):
|
||||
raise AssertionError()
|
||||
if not isinstance(self.cards[0], board.NumberCard):
|
||||
raise AssertionError()
|
||||
if dest_card.suit == self.cards[0].suit:
|
||||
raise AssertionError()
|
||||
if dest_card.number != self.cards[0].number + 1:
|
||||
raise AssertionError()
|
||||
self._shift(action_board, self.source_id, self.destination_id)
|
||||
|
||||
def _undo(self, action_board: board.Board) -> None:
|
||||
"""Undo action"""
|
||||
self._shift(action_board, self.destination_id, self.source_id)
|
||||
|
||||
|
||||
@dataclass
|
||||
class DragonKillAction(Action):
|
||||
"""Removing four dragons from the top of the stacks to a bunker"""
|
||||
|
||||
dragon: board.SpecialCard
|
||||
source_stacks: List[Tuple[board.Position, int]]
|
||||
destination_bunker_id: int
|
||||
|
||||
def _apply(self, action_board: board.Board) -> None:
|
||||
"""Do action"""
|
||||
assert (
|
||||
action_board.bunker[self.destination_bunker_id] is None
|
||||
or action_board.bunker[self.destination_bunker_id] == self.dragon
|
||||
)
|
||||
assert len(self.source_stacks) == 4
|
||||
for position, index in self.source_stacks:
|
||||
if position == board.Position.Field:
|
||||
assert action_board.field[index]
|
||||
assert action_board.field[index][-1] == self.dragon
|
||||
action_board.field[index].pop()
|
||||
elif position == board.Position.Bunker:
|
||||
assert action_board.bunker[index] == self.dragon
|
||||
action_board.bunker[index] = None
|
||||
else:
|
||||
raise RuntimeError("Can only kill dragons in field and bunker")
|
||||
action_board.bunker[self.destination_bunker_id] = (self.dragon, 4)
|
||||
|
||||
def _undo(self, action_board: board.Board) -> None:
|
||||
"""Undo action"""
|
||||
assert action_board.bunker[self.destination_bunker_id] == (
|
||||
self.dragon, 4)
|
||||
assert len(self.source_stacks) == 4
|
||||
action_board.bunker[self.destination_bunker_id] = None
|
||||
for position, index in self.source_stacks:
|
||||
if position == board.Position.Field:
|
||||
action_board.field[index].append(self.dragon)
|
||||
elif position == board.Position.Bunker:
|
||||
action_board.bunker[index] = self.dragon
|
||||
else:
|
||||
raise RuntimeError("Can only kill dragons in field and bunker")
|
||||
|
||||
|
||||
@dataclass
|
||||
class HuaKillAction(Action):
|
||||
"""Remove the flower card"""
|
||||
|
||||
source_field_id: int
|
||||
|
||||
def _apply(self, action_board: board.Board) -> None:
|
||||
"""Do action"""
|
||||
assert not action_board.flower_gone
|
||||
assert (action_board.field[self.source_field_id][-1]
|
||||
== board.SpecialCard.Hua)
|
||||
action_board.field[self.source_field_id].pop()
|
||||
action_board.flower_gone = True
|
||||
|
||||
def _undo(self, action_board: board.Board) -> None:
|
||||
"""Undo action"""
|
||||
assert action_board.flower_gone
|
||||
action_board.field[self.source_field_id].append(board.SpecialCard.Hua)
|
||||
action_board.flower_gone = False
|
||||
208
shenzhen_solitaire/solver/board_possibilities.py
Normal file
208
shenzhen_solitaire/solver/board_possibilities.py
Normal file
@@ -0,0 +1,208 @@
|
||||
"""Contains function to iterate different kinds of possible actions"""
|
||||
from typing import Iterator, List, Tuple
|
||||
from .. import board
|
||||
from . import board_actions
|
||||
|
||||
|
||||
def possible_huakill_action(
|
||||
search_board: board.Board
|
||||
) -> Iterator[board_actions.HuaKillAction]:
|
||||
"""Check if the flowercard can be eliminated"""
|
||||
for index, stack in enumerate(search_board.field):
|
||||
if stack and stack[-1] == board.SpecialCard.Hua:
|
||||
yield board_actions.HuaKillAction(source_field_id=index)
|
||||
|
||||
|
||||
def possible_dragonkill_actions(
|
||||
search_board: board.Board
|
||||
) -> Iterator[board_actions.DragonKillAction]:
|
||||
"""Enumerate all possible dragon kills"""
|
||||
possible_dragons = [
|
||||
board.SpecialCard.Zhong,
|
||||
board.SpecialCard.Fa,
|
||||
board.SpecialCard.Bai,
|
||||
]
|
||||
if not any(x is None for x in search_board.bunker):
|
||||
new_possible_dragons = []
|
||||
for dragon in possible_dragons:
|
||||
if any(x == dragon for x in search_board.bunker):
|
||||
new_possible_dragons.append(dragon)
|
||||
possible_dragons = new_possible_dragons
|
||||
|
||||
for dragon in possible_dragons:
|
||||
bunker_dragons = [i for i, d in
|
||||
enumerate(search_board.bunker) if d == dragon]
|
||||
field_dragons = [
|
||||
i for i, f in enumerate(search_board.field) if f if f[-1] == dragon
|
||||
]
|
||||
if len(bunker_dragons) + len(field_dragons) != 4:
|
||||
continue
|
||||
destination_bunker_id = 0
|
||||
if bunker_dragons:
|
||||
destination_bunker_id = bunker_dragons[0]
|
||||
else:
|
||||
destination_bunker_id = [
|
||||
i for i, x in enumerate(search_board.bunker) if x is None
|
||||
][0]
|
||||
|
||||
source_stacks = [(board.Position.Bunker, i) for i in bunker_dragons]
|
||||
source_stacks.extend([(board.Position.Field, i)
|
||||
for i in field_dragons])
|
||||
|
||||
yield board_actions.DragonKillAction(
|
||||
dragon=dragon,
|
||||
source_stacks=source_stacks,
|
||||
destination_bunker_id=destination_bunker_id,
|
||||
)
|
||||
|
||||
|
||||
def possible_bunkerize_actions(
|
||||
search_board: board.Board
|
||||
) -> Iterator[board_actions.BunkerizeAction]:
|
||||
"""Enumerates all possible card moves from the field to the bunker"""
|
||||
open_bunker_list = [
|
||||
i for i, x in enumerate(
|
||||
search_board.bunker) if x is None]
|
||||
|
||||
if not open_bunker_list:
|
||||
return
|
||||
|
||||
open_bunker = open_bunker_list[0]
|
||||
for index, stack in enumerate(search_board.field):
|
||||
if not stack:
|
||||
continue
|
||||
yield board_actions.BunkerizeAction(
|
||||
card=stack[-1],
|
||||
field_id=index,
|
||||
bunker_id=open_bunker,
|
||||
to_bunker=True
|
||||
)
|
||||
|
||||
|
||||
def possible_debunkerize_actions(
|
||||
search_board: board.Board
|
||||
) -> Iterator[board_actions.BunkerizeAction]:
|
||||
"""Enumerates all possible card moves from the bunker to the field"""
|
||||
bunker_number_cards = [
|
||||
(i, x)
|
||||
for i, x in enumerate(search_board.bunker)
|
||||
if isinstance(x, board.NumberCard)
|
||||
]
|
||||
for index, card in bunker_number_cards:
|
||||
for other_index, other_stack in enumerate(search_board.field):
|
||||
if not other_stack:
|
||||
continue
|
||||
if not isinstance(other_stack[-1], board.NumberCard):
|
||||
continue
|
||||
if other_stack[-1].suit == card.suit:
|
||||
continue
|
||||
if other_stack[-1].number != card.number + 1:
|
||||
continue
|
||||
yield board_actions.BunkerizeAction(
|
||||
card=card,
|
||||
bunker_id=index,
|
||||
field_id=other_index,
|
||||
to_bunker=False
|
||||
)
|
||||
|
||||
|
||||
def possible_goal_move_actions(
|
||||
search_board: board.Board
|
||||
) -> Iterator[board_actions.GoalAction]:
|
||||
"""Enumerates all possible moves from anywhere to the goal"""
|
||||
field_cards = [
|
||||
(board.Position.Field, index, stack[-1])
|
||||
for index, stack in enumerate(search_board.field)
|
||||
if stack
|
||||
if isinstance(stack[-1], board.NumberCard)
|
||||
]
|
||||
bunker_cards = [
|
||||
(board.Position.Bunker, index, stack)
|
||||
for index, stack in enumerate(search_board.bunker)
|
||||
if isinstance(stack, board.NumberCard)
|
||||
]
|
||||
top_cards = field_cards + bunker_cards
|
||||
|
||||
for suit, number in search_board.goal.items():
|
||||
for source, index, stack in top_cards:
|
||||
if not (stack.suit == suit and stack.number == number + 1):
|
||||
continue
|
||||
yield board_actions.GoalAction(
|
||||
card=stack, source_id=index, source_position=source
|
||||
)
|
||||
break
|
||||
|
||||
|
||||
def _can_stack(bottom: board.Card, top: board.Card) -> bool:
|
||||
if not isinstance(bottom, board.NumberCard):
|
||||
return False
|
||||
if not isinstance(top, board.NumberCard):
|
||||
return False
|
||||
if bottom.suit == top.suit:
|
||||
return False
|
||||
if bottom.number != top.number + 1:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _get_cardstacks(search_board: board.Board) -> List[List[board.Card]]:
|
||||
"""Returns all cards on one stack that can be moved at once"""
|
||||
result: List[List[board.Card]] = []
|
||||
for stack in search_board.field:
|
||||
result.append([])
|
||||
if not stack:
|
||||
continue
|
||||
result[-1].append(stack[-1])
|
||||
for card in stack[-2::-1]:
|
||||
if not _can_stack(card, result[-1][0]):
|
||||
break
|
||||
if not isinstance(card, board.NumberCard):
|
||||
break
|
||||
result[-1].insert(0, card)
|
||||
return result
|
||||
|
||||
|
||||
def possible_field_move_actions(
|
||||
search_board: board.Board
|
||||
) -> Iterator[board_actions.MoveAction]:
|
||||
"""Enumerate all possible move actions
|
||||
from one field stack to another field stack"""
|
||||
first_empty_field_id = -1
|
||||
cardstacks = [(index, stack)
|
||||
for index, stack in enumerate(_get_cardstacks(search_board))]
|
||||
cardstacks = [x for x in cardstacks if x[1]]
|
||||
cardstacks = sorted(cardstacks, key=lambda x: len(x[1]))
|
||||
substacks: List[Tuple[int, List[board.Card]]] = []
|
||||
|
||||
for index, stack in cardstacks:
|
||||
substacks.extend((index, substack)
|
||||
for substack in (stack[i:]
|
||||
for i in range(len(stack))))
|
||||
|
||||
for index, substack in substacks:
|
||||
for other_index, other_stack in enumerate(search_board.field):
|
||||
if index == other_index:
|
||||
continue
|
||||
if other_stack:
|
||||
if not _can_stack(other_stack[-1], substack[0]):
|
||||
continue
|
||||
elif len(substack) == len(search_board.field[index]):
|
||||
continue
|
||||
elif first_empty_field_id == -1:
|
||||
first_empty_field_id = other_index
|
||||
elif other_index != first_empty_field_id:
|
||||
continue
|
||||
yield board_actions.MoveAction(
|
||||
cards=substack, source_id=index, destination_id=other_index
|
||||
)
|
||||
|
||||
|
||||
def possible_actions(
|
||||
search_board: board.Board) -> Iterator[board_actions.Action]:
|
||||
"""Enumerate all possible actions on the current search_board"""
|
||||
yield from possible_huakill_action(search_board)
|
||||
yield from possible_dragonkill_actions(search_board)
|
||||
yield from possible_goal_move_actions(search_board)
|
||||
yield from possible_debunkerize_actions(search_board)
|
||||
yield from possible_field_move_actions(search_board)
|
||||
yield from possible_bunkerize_actions(search_board)
|
||||
121
shenzhen_solitaire/solver/solver.py
Normal file
121
shenzhen_solitaire/solver/solver.py
Normal file
@@ -0,0 +1,121 @@
|
||||
"""Contains solver for solitaire"""
|
||||
from typing import List, Iterator, Optional
|
||||
from ..board import Board
|
||||
from . import board_actions
|
||||
from .board_possibilities import possible_actions
|
||||
from .board_actions import (
|
||||
MoveAction,
|
||||
GoalAction,
|
||||
HuaKillAction,
|
||||
DragonKillAction)
|
||||
|
||||
|
||||
class ActionStack:
|
||||
"""Stack of chosen actions on the board"""
|
||||
iterator_stack: List[Iterator[board_actions.Action]]
|
||||
action_stack: List[Optional[board_actions.Action]]
|
||||
index_stack: List[int]
|
||||
state_stack: List[int]
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.iterator_stack = []
|
||||
self.index_stack = []
|
||||
self.action_stack = []
|
||||
self.state_stack = []
|
||||
|
||||
def push(self, board: Board) -> None:
|
||||
"""Append another board state to stack"""
|
||||
self.iterator_stack.append(possible_actions(board))
|
||||
self.action_stack.append(None)
|
||||
self.index_stack.append(0)
|
||||
self.state_stack.append(board.state_identifier)
|
||||
|
||||
def get(self) -> Optional[board_actions.Action]:
|
||||
"""Get next iteration of top action iterator"""
|
||||
try:
|
||||
self.action_stack[-1] = next(self.iterator_stack[-1])
|
||||
except StopIteration:
|
||||
return None
|
||||
self.index_stack[-1] += 1
|
||||
return self.action_stack[-1]
|
||||
|
||||
def pop(self) -> None:
|
||||
"""Pop one action from stack"""
|
||||
self.action_stack.pop()
|
||||
self.iterator_stack.pop()
|
||||
self.index_stack.pop()
|
||||
self.state_stack.pop()
|
||||
|
||||
def __len__(self) -> int:
|
||||
return len(self.index_stack)
|
||||
|
||||
|
||||
def solve(board: Board) -> Iterator[List[board_actions.Action]]:
|
||||
"""Solve a solitaire puzzle"""
|
||||
state_set = {board.state_identifier}
|
||||
stack = ActionStack()
|
||||
stack.push(board)
|
||||
|
||||
def _limit_stack_size(stack_size: int) -> None:
|
||||
if len(stack) == stack_size:
|
||||
stack.pop()
|
||||
assert stack.action_stack[-1] is not None
|
||||
stack.action_stack[-1].undo(board)
|
||||
assert (board.state_identifier
|
||||
in state_set)
|
||||
|
||||
def _backtrack_action() -> None:
|
||||
stack.pop()
|
||||
assert stack.action_stack[-1] is not None
|
||||
stack.action_stack[-1].undo(board)
|
||||
assert (board.state_identifier
|
||||
in state_set)
|
||||
|
||||
def _skip_loop_move(action: board_actions.Action) -> bool:
|
||||
if isinstance(action, MoveAction):
|
||||
for prev_action in stack.action_stack[-2::-1]:
|
||||
if isinstance(prev_action, MoveAction):
|
||||
if prev_action.cards == action.cards:
|
||||
return True
|
||||
return False
|
||||
|
||||
count = 0
|
||||
while stack:
|
||||
count += 1
|
||||
if count > 5000:
|
||||
count = 0
|
||||
print(f"{len(stack)} {sum(board.goal.values())}")
|
||||
|
||||
# _limit_stack_size(80)
|
||||
|
||||
assert (board.state_identifier ==
|
||||
stack.state_stack[-1])
|
||||
action = stack.get()
|
||||
|
||||
if not action:
|
||||
_backtrack_action()
|
||||
continue
|
||||
|
||||
if _skip_loop_move(action):
|
||||
continue
|
||||
|
||||
action.apply(board)
|
||||
|
||||
if board.solved():
|
||||
yield stack.action_stack
|
||||
stack.action_stack[-1].undo(board)
|
||||
while isinstance(
|
||||
stack.action_stack[-1], (GoalAction,
|
||||
HuaKillAction,
|
||||
DragonKillAction)):
|
||||
stack.pop()
|
||||
stack.action_stack[-1].undo(board)
|
||||
continue
|
||||
|
||||
if board.state_identifier in state_set:
|
||||
action.undo(board)
|
||||
assert board.state_identifier in state_set
|
||||
continue
|
||||
|
||||
state_set.add(board.state_identifier)
|
||||
stack.push(board)
|
||||
Reference in New Issue
Block a user