Skip to content

How to create a custom hand for your bot? (untested code)

Michael Cochez edited this page Jan 24, 2023 · 1 revision

At the bottom of game.py, you find how the SchnapsenGamePlayEngine is created:

class SchnapsenGamePlayEngine(GamePlayEngine):
    """
    A GamePlayEngine configured according to the rules of Schnapsen
    """

    def __init__(self) -> None:
        super().__init__(
            deck_generator=SchnapsenDeckGenerator(),
            hand_generator=SchnapsenHandGenerator(),
            trick_implementer=SchnapsenTrickImplementer(),
            move_requester=SimpleMoveRequester(),
            move_validator=SchnapsenMoveValidator(),
            trick_scorer=SchnapsenTrickScorer()
        )

The part which decides what goes in the hand is SchnapsenHandGenerator. This will get a shuffled deck and return the hands and the deck. The code looks like this:

class SchnapsenHandGenerator(HandGenerator):
    @classmethod
    def generateHands(self, cards: OrderedCardCollection) -> Tuple[Hand, Hand, Talon]:
        the_cards = list(cards.get_cards())
        hand1 = Hand([the_cards[i] for i in range(0, 10, 2)], max_size=5)
        hand2 = Hand([the_cards[i] for i in range(1, 11, 2)], max_size=5)
        rest = Talon(the_cards[10:])
        return (hand1, hand2, rest)

You can modify this to what you would want to have. For example, say you want all hearts for hand1 (the hand for bot1).

class ModifiedHandGenerator(HandGenerator):
    @classmethod
    def generateHands(self, cards: OrderedCardCollection) -> Tuple[Hand, Hand, Talon]:
        the_cards = list(cards.get_cards())
        hearts = cards.filter_suit(Suit.HEARTS)
        hand1 = Hand(hearts, max_size=5)
        left = filter(lambda card: not card in hand1, cards)
        hand2 = Hand(left[0:5], max_size=5)
        rest = Talon(the_cards[5:])
        return (hand1, hand2, rest)

Then, you can make you modified engine:

class ModifiedGamePlayEngine(GamePlayEngine):
    """
    A GamePlayEngine configured according to the rules of Schnapsen
    """

    def __init__(self) -> None:
        super().__init__(
            deck_generator=SchnapsenDeckGenerator(),
            hand_generator=ModifiedHandGenerator(),
            trick_implementer=SchnapsenTrickImplementer(),
            move_requester=SimpleMoveRequester(),
            move_validator=SchnapsenMoveValidator(),
            trick_scorer=SchnapsenTrickScorer()
        )

And then use this as you normally would:

    engine = ModifiedGamePlayEngine()
    bot1 = RandBot(12112121)
    bot2 = RandBot(464566)
    winner_id, game_points, score = engine.play_game(bot1, bot2, random.Random(45))
    print(f"Game ended. Winner is {winner_id} with {game_points} points, score {score}")