Made it work
This commit is contained in:
@@ -36,6 +36,9 @@ class NumberCard:
|
||||
"""Returns unique identifier representing this card"""
|
||||
return int(self.number - 1 + 9 ** int(self.suit.value))
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"NumberCard({self.suit.name} {self.number})"
|
||||
|
||||
|
||||
Card = Union[NumberCard, SpecialCard]
|
||||
|
||||
@@ -58,16 +61,38 @@ class Board:
|
||||
def __init__(self) -> None:
|
||||
self.field: List[List[Card]] = [[]] * Board.MAX_COLUMN_SIZE
|
||||
self.bunker: List[Union[Tuple[SpecialCard, int], Optional[Card]]] = [None] * 3
|
||||
self.goal: Dict[NumberCard.Suit, int] = {
|
||||
NumberCard.Suit.Red: 0,
|
||||
NumberCard.Suit.Green: 0,
|
||||
NumberCard.Suit.Black: 0,
|
||||
}
|
||||
self.goal: List[Optional[NumberCard]] = [None] * 3
|
||||
self.flower_gone: bool = False
|
||||
|
||||
def getGoal(self, suit: NumberCard.Suit) -> int:
|
||||
for card in self.goal:
|
||||
if card is not None and card.suit == suit:
|
||||
return card.number
|
||||
else:
|
||||
return 0
|
||||
|
||||
def getGoalId(self, suit: NumberCard.Suit) -> int:
|
||||
for index, card in enumerate(self.goal):
|
||||
if card is not None and card.suit == suit:
|
||||
return index
|
||||
else:
|
||||
return self.goal.index(None)
|
||||
|
||||
def setGoal(self, suit: NumberCard.Suit, value: int) -> None:
|
||||
assert len(self.goal) == 3
|
||||
assert 0 <= value
|
||||
assert value <= 9
|
||||
if value == 0:
|
||||
self.goal[self.getGoalId(suit)] = None
|
||||
else:
|
||||
self.goal[self.getGoalId(suit)] = NumberCard(suit, number=value)
|
||||
|
||||
def incGoal(self, suit: NumberCard.Suit) -> None:
|
||||
self.setGoal(suit, self.getGoal(suit) + 1)
|
||||
|
||||
def solved(self) -> bool:
|
||||
"""Returns true if the board is solved"""
|
||||
if any(x != 9 for x in self.goal.values()):
|
||||
if any(x.number != 9 for x in self.goal if x is not None):
|
||||
return False
|
||||
if any(not isinstance(x, tuple) for x in self.bunker):
|
||||
return False
|
||||
@@ -97,9 +122,14 @@ class Board:
|
||||
if self.flower_gone:
|
||||
result |= 1
|
||||
|
||||
for _, goal_count in self.goal.items():
|
||||
result <<= 4
|
||||
result |= goal_count
|
||||
assert len(self.goal) == 3
|
||||
suit_sequence = list(NumberCard.Suit)
|
||||
for card in self.goal:
|
||||
result <<= 5
|
||||
if card is None:
|
||||
result |= len(suit_sequence) * 10
|
||||
else:
|
||||
result |= suit_sequence.index(card.suit) * 10 + card.number
|
||||
|
||||
# Max stack size is 13
|
||||
# (4 random cards from the start, plus a stack from 9 to 1)
|
||||
@@ -146,7 +176,7 @@ class Board:
|
||||
number_cards[card.suit].add(card.number)
|
||||
|
||||
for suit, numbers in number_cards.items():
|
||||
if set(range(self.goal[suit] + 1, 10)) != numbers:
|
||||
if set(range(self.getGoal(suit) + 1, 10)) != numbers:
|
||||
return False
|
||||
|
||||
for cardtype, count in special_cards.items():
|
||||
|
||||
@@ -211,7 +211,7 @@ def parse_goal_field(
|
||||
return best_card_name
|
||||
|
||||
|
||||
def parse_goal(image: np.ndarray, conf: Configuration) -> Dict[NumberCard.Suit, int]:
|
||||
def parse_goal(image: np.ndarray, conf: Configuration) -> List[Optional[NumberCard]]:
|
||||
goal_squares = card_finder.get_field_squares(
|
||||
image, fake_adjustment(conf.goal_adjustment), count_x=1, count_y=3
|
||||
)
|
||||
@@ -219,11 +219,8 @@ def parse_goal(image: np.ndarray, conf: Configuration) -> Dict[NumberCard.Suit,
|
||||
parse_goal_field(square, conf.catalogue, conf.green_card)
|
||||
for square in goal_squares
|
||||
]
|
||||
base_goal_dict = {suit: 0 for suit in NumberCard.Suit}
|
||||
base_goal_dict.update(
|
||||
{x.suit: x.number for x in (x for x in goal_list if x is not None)}
|
||||
)
|
||||
return base_goal_dict
|
||||
|
||||
return goal_list
|
||||
|
||||
|
||||
def parse_board(image: np.ndarray, conf: Configuration) -> Board:
|
||||
|
||||
0
shenzhen_solitaire/clicker/__init__.py
Normal file
0
shenzhen_solitaire/clicker/__init__.py
Normal file
104
shenzhen_solitaire/clicker/main.py
Normal file
104
shenzhen_solitaire/clicker/main.py
Normal file
@@ -0,0 +1,104 @@
|
||||
import shenzhen_solitaire.solver.board_actions as board_actions
|
||||
import shenzhen_solitaire.card_detection.configuration as configuration
|
||||
import shenzhen_solitaire.card_detection.adjustment as adjustment
|
||||
import shenzhen_solitaire.board as board
|
||||
from typing import List, Tuple
|
||||
import pyautogui
|
||||
import time
|
||||
|
||||
|
||||
def drag(
|
||||
src: Tuple[int, int], dst: Tuple[int, int], offset: Tuple[int, int] = (0, 0)
|
||||
) -> None:
|
||||
|
||||
pyautogui.moveTo(x=src[0] + offset[0], y=src[1] + offset[1])
|
||||
pyautogui.dragTo(x=dst[0] + offset[0], y=dst[1] + offset[1],
|
||||
duration=0.4, tween=lambda x: 0 if x < 0.5 else 1)
|
||||
|
||||
|
||||
def click(point: Tuple[int, int], offset: Tuple[int, int] = (0, 0)) -> None:
|
||||
pyautogui.moveTo(x=point[0] + offset[0], y=point[1] + offset[1])
|
||||
pyautogui.mouseDown()
|
||||
time.sleep(0.2)
|
||||
pyautogui.mouseUp()
|
||||
|
||||
def handle_action(
|
||||
action: board_actions.Action,
|
||||
offset: Tuple[int, int],
|
||||
conf: configuration.Configuration,
|
||||
) -> None:
|
||||
if isinstance(action, board_actions.MoveAction):
|
||||
src_x, src_y, _, _ = adjustment.get_square(
|
||||
conf.field_adjustment,
|
||||
index_x=action.source_id,
|
||||
index_y=action.source_row_index,
|
||||
)
|
||||
dst_x, dst_y, _, _ = adjustment.get_square(
|
||||
conf.field_adjustment,
|
||||
index_x=action.destination_id,
|
||||
index_y=action.destination_row_index,
|
||||
)
|
||||
drag((src_x, src_y), (dst_x, dst_y), offset)
|
||||
return
|
||||
if isinstance(action, board_actions.HuaKillAction):
|
||||
time.sleep(1)
|
||||
return
|
||||
if isinstance(action, board_actions.BunkerizeAction):
|
||||
field_x, field_y, _, _ = adjustment.get_square(
|
||||
conf.field_adjustment,
|
||||
index_x=action.field_id,
|
||||
index_y=action.field_row_index,
|
||||
)
|
||||
bunker_x, bunker_y, _, _ = adjustment.get_square(
|
||||
conf.bunker_adjustment, index_x=action.bunker_id, index_y=0,
|
||||
)
|
||||
if action.to_bunker:
|
||||
drag((field_x, field_y), (bunker_x, bunker_y), offset)
|
||||
else:
|
||||
drag((bunker_x, bunker_y), (field_x, field_y), offset)
|
||||
return
|
||||
if isinstance(action, board_actions.DragonKillAction):
|
||||
dragon_sequence = [
|
||||
board.SpecialCard.Zhong,
|
||||
board.SpecialCard.Fa,
|
||||
board.SpecialCard.Bai,
|
||||
]
|
||||
field_x, field_y, size_x, size_y = adjustment.get_square(
|
||||
conf.special_button_adjustment,
|
||||
index_x=0,
|
||||
index_y=dragon_sequence.index(action.dragon),
|
||||
)
|
||||
click((field_x + (size_x - field_x) // 2, field_y + (size_y - field_y) // 2), offset)
|
||||
time.sleep(0.5)
|
||||
return
|
||||
if isinstance(action, board_actions.GoalAction):
|
||||
if action.obvious:
|
||||
time.sleep(1)
|
||||
return
|
||||
dst_x, dst_y, _, _ = adjustment.get_square(
|
||||
conf.goal_adjustment, index_x=action.goal_id, index_y=0,
|
||||
)
|
||||
if action.source_position == board.Position.Field:
|
||||
assert action.source_row_index is not None
|
||||
src_x, src_y, _, _ = adjustment.get_square(
|
||||
conf.field_adjustment,
|
||||
index_x=action.source_id,
|
||||
index_y=action.source_row_index,
|
||||
)
|
||||
else:
|
||||
assert action.source_position == board.Position.Bunker
|
||||
src_x, src_y, _, _ = adjustment.get_square(
|
||||
conf.bunker_adjustment, index_x=action.source_id, index_y=0,
|
||||
)
|
||||
drag((src_x, src_y), (dst_x, dst_y), offset)
|
||||
return
|
||||
raise AssertionError("You forgot an Action type")
|
||||
|
||||
|
||||
def handle_actions(
|
||||
actions: List[board_actions.Action],
|
||||
offset: Tuple[int, int],
|
||||
conf: configuration.Configuration,
|
||||
) -> None:
|
||||
for action in actions:
|
||||
handle_action(action, offset, conf)
|
||||
0
shenzhen_solitaire/solver/__init__.py
Normal file
0
shenzhen_solitaire/solver/__init__.py
Normal file
@@ -1,11 +1,12 @@
|
||||
"""Contains actions that can be used on the board"""
|
||||
from typing import List, Tuple
|
||||
from typing import List, Tuple, Optional
|
||||
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
|
||||
|
||||
@@ -36,26 +37,30 @@ class GoalAction(Action):
|
||||
|
||||
card: board.NumberCard
|
||||
source_id: int
|
||||
source_row_index: Optional[int]
|
||||
source_position: board.Position
|
||||
goal_id: int
|
||||
obvious: bool
|
||||
|
||||
def _apply(self, action_board: board.Board) -> None:
|
||||
"""Do action"""
|
||||
assert action_board.getGoalId(self.card.suit) == self.goal_id
|
||||
assert action_board.getGoal(self.card.suit) + 1 == self.card.number
|
||||
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
|
||||
action_board.incGoal(self.card.suit)
|
||||
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
|
||||
action_board.incGoal(self.card.suit)
|
||||
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
|
||||
assert action_board.getGoalId(self.card.suit) == self.goal_id
|
||||
assert action_board.getGoal(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:
|
||||
@@ -63,7 +68,7 @@ class GoalAction(Action):
|
||||
action_board.bunker[self.source_id] = self.card
|
||||
else:
|
||||
raise RuntimeError("Unknown position")
|
||||
action_board.goal[self.card.suit] -= 1
|
||||
action_board.setGoal(self.card.suit, action_board.getGoal(self.card.suit) - 1)
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -73,6 +78,7 @@ class BunkerizeAction(Action):
|
||||
card: board.Card
|
||||
bunker_id: int
|
||||
field_id: int
|
||||
field_row_index: int
|
||||
to_bunker: bool
|
||||
|
||||
def _move_from_bunker(self, action_board: board.Board) -> None:
|
||||
@@ -107,21 +113,17 @@ class MoveAction(Action):
|
||||
|
||||
cards: List[board.Card]
|
||||
source_id: int
|
||||
source_row_index: int
|
||||
destination_id: int
|
||||
destination_row_index: int
|
||||
|
||||
def _shift(
|
||||
self,
|
||||
action_board: board.Board,
|
||||
source: int,
|
||||
dest: int) -> None:
|
||||
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)):
|
||||
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[source] = action_board.field[source][: -len(self.cards)]
|
||||
action_board.field[dest].extend(self.cards)
|
||||
|
||||
def _apply(self, action_board: board.Board) -> None:
|
||||
@@ -174,8 +176,7 @@ class DragonKillAction(Action):
|
||||
|
||||
def _undo(self, action_board: board.Board) -> None:
|
||||
"""Undo action"""
|
||||
assert action_board.bunker[self.destination_bunker_id] == (
|
||||
self.dragon, 4)
|
||||
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:
|
||||
@@ -192,12 +193,12 @@ class HuaKillAction(Action):
|
||||
"""Remove the flower card"""
|
||||
|
||||
source_field_id: int
|
||||
source_field_row_index: 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)
|
||||
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
|
||||
|
||||
|
||||
@@ -2,19 +2,22 @@
|
||||
from typing import Iterator, List, Tuple
|
||||
from .. import board
|
||||
from . import board_actions
|
||||
import pdb
|
||||
|
||||
|
||||
def possible_huakill_action(
|
||||
search_board: board.Board
|
||||
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)
|
||||
yield board_actions.HuaKillAction(
|
||||
source_field_id=index, source_field_row_index=len(stack) - 1
|
||||
)
|
||||
|
||||
|
||||
def possible_dragonkill_actions(
|
||||
search_board: board.Board
|
||||
search_board: board.Board,
|
||||
) -> Iterator[board_actions.DragonKillAction]:
|
||||
"""Enumerate all possible dragon kills"""
|
||||
possible_dragons = [
|
||||
@@ -30,8 +33,7 @@ def possible_dragonkill_actions(
|
||||
possible_dragons = new_possible_dragons
|
||||
|
||||
for dragon in possible_dragons:
|
||||
bunker_dragons = [i for i, d in
|
||||
enumerate(search_board.bunker) if d == dragon]
|
||||
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
|
||||
]
|
||||
@@ -46,8 +48,7 @@ def possible_dragonkill_actions(
|
||||
][0]
|
||||
|
||||
source_stacks = [(board.Position.Bunker, i) for i in bunker_dragons]
|
||||
source_stacks.extend([(board.Position.Field, i)
|
||||
for i in field_dragons])
|
||||
source_stacks.extend([(board.Position.Field, i) for i in field_dragons])
|
||||
|
||||
yield board_actions.DragonKillAction(
|
||||
dragon=dragon,
|
||||
@@ -57,12 +58,10 @@ def possible_dragonkill_actions(
|
||||
|
||||
|
||||
def possible_bunkerize_actions(
|
||||
search_board: board.Board
|
||||
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]
|
||||
open_bunker_list = [i for i, x in enumerate(search_board.bunker) if x is None]
|
||||
|
||||
if not open_bunker_list:
|
||||
return
|
||||
@@ -74,13 +73,14 @@ def possible_bunkerize_actions(
|
||||
yield board_actions.BunkerizeAction(
|
||||
card=stack[-1],
|
||||
field_id=index,
|
||||
field_row_index=len(stack) - 1,
|
||||
bunker_id=open_bunker,
|
||||
to_bunker=True
|
||||
to_bunker=True,
|
||||
)
|
||||
|
||||
|
||||
def possible_debunkerize_actions(
|
||||
search_board: board.Board
|
||||
search_board: board.Board,
|
||||
) -> Iterator[board_actions.BunkerizeAction]:
|
||||
"""Enumerates all possible card moves from the bunker to the field"""
|
||||
bunker_number_cards = [
|
||||
@@ -102,12 +102,13 @@ def possible_debunkerize_actions(
|
||||
card=card,
|
||||
bunker_id=index,
|
||||
field_id=other_index,
|
||||
to_bunker=False
|
||||
field_row_index=len(other_stack),
|
||||
to_bunker=False,
|
||||
)
|
||||
|
||||
|
||||
def possible_goal_move_actions(
|
||||
search_board: board.Board
|
||||
search_board: board.Board,
|
||||
) -> Iterator[board_actions.GoalAction]:
|
||||
"""Enumerates all possible moves from anywhere to the goal"""
|
||||
field_cards = [
|
||||
@@ -117,20 +118,30 @@ def possible_goal_move_actions(
|
||||
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)
|
||||
(board.Position.Bunker, index, card)
|
||||
for index, card in enumerate(search_board.bunker)
|
||||
if isinstance(card, 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
|
||||
for source, index, card in top_cards:
|
||||
if not (card.number == search_board.getGoal(card.suit) + 1):
|
||||
continue
|
||||
obvious = all(
|
||||
search_board.getGoal(other_suit) >= search_board.getGoal(card.suit)
|
||||
for other_suit in set(board.NumberCard.Suit) - {card.suit}
|
||||
)
|
||||
yield board_actions.GoalAction(
|
||||
card=card,
|
||||
source_id=index,
|
||||
source_row_index=len(search_board.field[index]) - 1
|
||||
if source == board.Position.Field
|
||||
else None,
|
||||
source_position=source,
|
||||
goal_id=search_board.getGoalId(card.suit),
|
||||
obvious=obvious,
|
||||
)
|
||||
break
|
||||
|
||||
|
||||
def _can_stack(bottom: board.Card, top: board.Card) -> bool:
|
||||
@@ -163,42 +174,44 @@ def _get_cardstacks(search_board: board.Board) -> List[List[board.Card]]:
|
||||
|
||||
|
||||
def possible_field_move_actions(
|
||||
search_board: board.Board
|
||||
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 = [x for x in enumerate(_get_cardstacks(search_board)) 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))))
|
||||
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:
|
||||
for source_index, source_substack in substacks:
|
||||
for destination_index, destination_stack in enumerate(search_board.field):
|
||||
if source_index == destination_index:
|
||||
continue
|
||||
if other_stack:
|
||||
if not _can_stack(other_stack[-1], substack[0]):
|
||||
if destination_stack:
|
||||
if not _can_stack(destination_stack[-1], source_substack[0]):
|
||||
continue
|
||||
elif len(substack) == len(search_board.field[index]):
|
||||
elif len(source_substack) == len(search_board.field[source_index]):
|
||||
continue
|
||||
elif first_empty_field_id == -1:
|
||||
first_empty_field_id = other_index
|
||||
elif other_index != first_empty_field_id:
|
||||
first_empty_field_id = destination_index
|
||||
elif destination_index != first_empty_field_id:
|
||||
continue
|
||||
yield board_actions.MoveAction(
|
||||
cards=substack, source_id=index, destination_id=other_index
|
||||
cards=source_substack,
|
||||
source_id=source_index,
|
||||
source_row_index=len(search_board.field[source_index])
|
||||
- len(source_substack),
|
||||
destination_id=destination_index,
|
||||
destination_row_index=len(destination_stack),
|
||||
)
|
||||
|
||||
|
||||
def possible_actions(
|
||||
search_board: board.Board) -> Iterator[board_actions.Action]:
|
||||
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)
|
||||
|
||||
@@ -84,7 +84,7 @@ def solve(board: Board) -> Iterator[List[board_actions.Action]]:
|
||||
count += 1
|
||||
if count > 5000:
|
||||
count = 0
|
||||
print(f"{len(stack)} {sum(board.goal.values())}")
|
||||
print(f"{len(stack)} {board.goal}")
|
||||
|
||||
# _limit_stack_size(80)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user