Esempio n. 1
0
def main():
    if sys.version_info[0] < 3:
        print('bridgebot only works with python 3')
        return 1

    deck = Deck()
    deck.shuffle()

    # Todo add in bid getting
    contract = Contracts.FIVE_CLUBS # get_input_enum(Contracts, "contract")
    doubled = Doubles.DOUBLE # get_input_enum(Doubles, "doubled status")
    declarer = Players.EAST # get_input_enum(Players, "declarer")
    vulnerability = Vulnerabilities.BOTH # get_input_enum(Vulnerabilities, "vulnerability")
    vulnerability = vulnerability.is_declarer_vulnerable(declarer)

    # Todo, link in bid history
    bid_history = None

    users = {
        Players.NORTH: RandomBotUser(),
        Players.SOUTH: RandomBotUser(),
        Players.WEST: RandomBotUser(),
        Players.EAST: RandomBotUser()
    }

    for i in range(0, NUMBER_OF_PLAYTHROUGHS):
        deal = deck.deal()

        trick_winners = cardplay.play(users, deal, contract, declarer, bid_history)

        score = get_score_from_result(contract, doubled, trick_winners, vulnerability)

        print("The declarer " + declarer.name + " has a score of " + str(score))
Esempio n. 2
0
    def __init__(self):
        """Class constructor. Defines instance attributes.

        Args:
            self (Dealer): An instance of the Dealer class.
        """
        self.deck = Deck()
        self.current_card = self.deck.draw_card()
        self.prev_card = 0
Esempio n. 3
0
    def test_removes_specified_number_of_cards_from_deck(self):
        ace = Card(rank="Ace", suit="Spades"),
        eight = Card(rank="8", suit="Diamonds")
        cards = [ace, eight]

        deck = Deck()
        deck.add_cards(cards)

        self.assertEqual(deck.remove_cards(1), [ace])

        self.assertEqual(deck.cards, [eight])
Esempio n. 4
0
 def init_game(self):
     Side((565, 50), ["rotlung_reanimator",
                      "necromancien_de_xathrid", "wild_evocation", "recycle",
                      "privileged_position", "vigor", "archonte_brulant"], (7, 1), self)
     Side((565, 730), ["rotlung_reanimator", "cloak_of_invisibility",
                       "roue_du_soleil_et_de_la_lune", "gains_illusoires", "fungus_sliver",
                       "steely_resolve", "dread_of_night", "shared_triumph", "vigor",
                       "archonte_brulant", "ancient_tomb", "mesmeric_orb",
                       "augure_prismatique", "choke"], (7, 2), self)
     handler = Handler(self.argv)
     self.tape = Tape(handler.get_init(), (960, 360), self)
     # state_changed, symbol, direction = handler.next() # bool, char, int
     self.deck = Deck((1600, 650), self.tape, handler, self)
Esempio n. 5
0
class Dealer():
    """
    This class of objects is for a dealer who draws the cards, keeps track
    of the previous card, and determines if the drawn card is hi or lo.

    Attributes:
        deck: instance of Deck class
        current_card: a random card drawn from the deck
        prev_card: the previous card, used to evaluate hi/lo
    """
    def __init__(self):
        """Class constructor. Defines instance attributes.

        Args:
            self (Dealer): An instance of the Dealer class.
        """
        self.deck = Deck()
        self.current_card = self.deck.draw_card()
        self.prev_card = 0

    def draw_card(self):
        """Gets a new card and retains the previous card.

        Args:
            self (Dealer): An instance of the Dealer class.
        """
        self.prev_card = self.current_card
        # TODO: get the deck.function to draw a card
        self.current_card = self.deck.draw_card()

        if not self.deck.deck:
            self.deck.create_deck()

    def determine_result(self):
        """ Determines if the drawn (current) card is higher or lower than
        the previous card.

        Args:
            self (Dealer): An instance of the Dealer class.
        Returns:
            str: if higher, returns 'hi'
                 if lower, returns 'lo'
                 if equal, returns 'equal'
        """
        if self.current_card > self.prev_card:
            result = 'h'
        elif self.current_card < self.prev_card:
            result = 'l'
        elif self.current_card:
            result = 'equal'
        return result
Esempio n. 6
0
def test_lead():
    card_list = [
        Deck.generate_card_from_index(card_index) for card_index in test_list
    ]
    hand = BridgeHand.generate_partially_played_hand(card_list)
    hand.lead(Card(Suits.DIAMONDS, Ranks.KING))
    assert not hand.contains_card(Card(Suits.DIAMONDS, Ranks.KING))
Esempio n. 7
0
def test_legal_cards():
    card_list = [
        Deck.generate_card_from_index(card_index) for card_index in test_list
    ]
    hand = BridgeHand.generate_partially_played_hand(card_list)
    legal = hand.legal_cards(Suits.DIAMONDS)
    assert Card(Suits.DIAMONDS, Ranks.ACE) in legal
Esempio n. 8
0
def test_follow_raises(led_suit, card, expected_except):
    card_list = [
        Deck.generate_card_from_index(card_index) for card_index in test_list
    ]
    hand = BridgeHand.generate_partially_played_hand(card_list)
    with expected_except:
        hand.follow(led_suit, card)
Esempio n. 9
0
def test_follow(led_suit, card):
    card_list = [
        Deck.generate_card_from_index(card_index) for card_index in test_list
    ]
    hand = BridgeHand.generate_partially_played_hand(card_list)
    hand.follow(led_suit, card)
    assert not hand.contains_card(card)
Esempio n. 10
0
 def __init__(self, game):
     self.winPot = 0
     self.boardBids = {}
     self.playerHands = {}
     self.deck = Deck()
     self.game = game
     self.round = 0
Esempio n. 11
0
def test_lead_when_card_is_missing():
    card_list = [
        Deck.generate_card_from_index(card_index) for card_index in test_list
    ]
    hand = BridgeHand.generate_partially_played_hand(card_list)
    with pytest.raises(CardNotInHandException):
        hand.lead(Card(Suits.SPADES, Ranks.ACE))
Esempio n. 12
0
    def __init__(self, deck_file: Path, hp: int, name: str):

        self.name = name
        self.deck = Deck(deck_file=deck_file, name="{}_deck".format(name))
        self.health_points = hp

        self.hand = []
        self.lands = []
        self.mana_pool = 0
        self.land_spells = 0
        self.creatures = []
        self.cemetery = []

        self.board = [self.lands, self.creatures]

        self.attacking_creatures = []
        self.blocking_creatures = []
Esempio n. 13
0
class Player(object):
    def __init__(self, deck_file: Path, hp: int, name: str):

        self.name = name
        self.deck = Deck(deck_file=deck_file, name="{}_deck".format(name))
        self.health_points = hp

        self.hand = []
        self.lands = []
        self.mana_pool = 0
        self.land_spells = 0
        self.creatures = []
        self.cemetery = []

        self.board = [self.lands, self.creatures]

        self.attacking_creatures = []
        self.blocking_creatures = []

    def draw_card(self, cards_count: int = 1):
        for i in range(cards_count):
            draw_card = self.deck.draw_card()
            draw_card.location = "hand"
            self.hand.append(draw_card)

    def refresh_land_spells(self, lands_turn: int):
        self.land_spells = lands_turn

    def untap_lands(self):
        for land_card in self.lands:
            land_card.status = "ready"

    def untap_creatures(self):
        for creature in self.creatures:
            creature.status = "ready"

    def clear_attacking_creatures(self):
        self.attacking_creatures = []

    def destroy_creatures(self, creatures_list: List[CreatureCard]):
        for creature in creatures_list:
            self.creatures.remove(creature)
            self.cemetery.append(creature)
            creature.location = "cemetery"

    def reset_creatures(self):
        for creature in self.creatures:
            creature.reset()
Esempio n. 14
0
    def test_shuffles_cards_in_random_order(self, mock_shuffle):
        deck = Deck()

        cards = [
            Card(rank="Ace", suit="Spades"),
            Card(rank="8", suit="Diamonds")
        ]

        deck.add_cards(cards)

        deck.shuffle()

        mock_shuffle.assert_called_once_with(cards)
Esempio n. 15
0
 def restore(cls, data_store, data_model, **kwargs):
     kwargs.update({
         'discards': {
             'A': CardHolder.restore(data_store, data_model.discards['A']),
             'B': CardHolder.restore(data_store, data_model.discards['B'])},
         'kitty': [Card(c) if c else None for c in data_model.kitty],
         'active_cards':
             [Card(c) if c else None for c in data_model.active],
         'state': data_model.state,
         'player_turn': data_model.player_turn,
         'bet_team': data_model.bet_team,
         'bet_amount': data_model.bet_amount,
         '_prev_state': data_model['_prev_state'],
         'trump_suit': data_model.trump_suit,
         'round_start_player': data_model.round_start_player,
         'round': data_model.round,
         'deck': Deck.restore(data_store, data_model.deck),
         'players': data_model.players
     })
     return super(Table, cls).restore(data_model, data_store, **kwargs)
Esempio n. 16
0
 def __init__(self, lst=[]):
     Deck.__init__(self, lst=lst)
     self.visible = False
     self.visible_to_player = True
Esempio n. 17
0
 def __init__(self, lst=[]):
     Deck.__init__(self, lst=lst)
     self.visible = True
Esempio n. 18
0
import pytest
import sys

sys.path.insert(0, '../bridgebot')
sys.path.insert(0, '..')

from contextlib import contextmanager

from game.deck import Deck
from game.bridgehand import Card, BridgeHand, CardDoesntFollowSuitException, CardNotInHandException, RepeatedCardException, WrongSizeHandException

from game.card import InvalidSuitException, InvalidRankException

from game.enums import Ranks, Suits

deck = Deck()
seven_of_hearts = Card(Suits.HEARTS, Ranks.SEVEN)
eight_of_clubs = Card(Suits.CLUBS, Ranks.EIGHT)


@contextmanager
def does_not_raise():
    yield


def test_deck():
    indices = deck.get_card_indices()
    print(indices)  # Will be suppressed unless pytest is called with -s
    assert len(indices) == 52

Esempio n. 19
0
 def __init__(self, name):
     Person.__init__(self)
     self.name = name
     self.deck = Deck()
Esempio n. 20
0
class Dealer(Person):
    """
        This class inherits from Person which has a lot of stuff in common with the player
    """
    def __init__(self, name):
        Person.__init__(self)
        self.name = name
        self.deck = Deck()

    def show_hand(self):
        """
            Show the current hand
        """
        generic_msg = Person.show_hand(self)
        return f"{self.name} (Dealer) : \t" + generic_msg

    def show_first_hand(self):
        """
            Show the first hand because for the dealer
            until it's his turn we only see one card
        """
        generic_msg = str(self.hand[0]) + " | "
        return f"{self.name} (Dealer) : \t" + generic_msg

    def shuffle(self):
        """
            Shuffle all the cards before the round starts
        """
        self.deck.shuffle_deck()

    def has_enough_cards(self):
        """
            Check if there's enough cards left in the deck for a round
        """
        enough = len(self.deck.full_deck) > 6

        return enough

    def give_card(self):
        """
            Give a card from the deck to a player
        """
        has_enough = self.has_enough_cards()

        if has_enough:
            return self.deck.full_deck.pop(0)

        raise NotEnoughCards("No more cards, need new deck!")

    def pay_player(self, amount):
        """
            This would be a method that would pay the player.
            With a multiplier according to the hand in play.
        """

    def collect_from_player(self):
        """
            This would be if the player had to pay the dealer
        """

    def __str__(self):
        return f"Hi! I'm {self.name}, I will be your dealer for the evening."
Esempio n. 21
0
def test_generate_hand(list, expected_except):
    card_list = [
        Deck.generate_card_from_index(card_index) for card_index in list
    ]
    with expected_except:
        hand = BridgeHand.generate_complete_hand(card_list)
Esempio n. 22
0
 def __init__(self):
     self._game_state = InitState(self)
     self._deck = Deck()
Esempio n. 23
0
 def test_stores_no_cards_at_start(self):
     deck = Deck()
     self.assertEqual(deck.cards, [])
Esempio n. 24
0
def test_bridge_hand_constructor(list, expected_except):
    card_list = [
        Deck.generate_card_from_index(card_index) for card_index in list
    ]
    with expected_except:
        bridge_hand = BridgeHand(card_list)
Esempio n. 25
0
def test_map_index_to_card(index, expected_except):
    with expected_except:
        card = Deck.generate_card_from_index(index)
        assert card == seven_of_hearts
Esempio n. 26
0
def test_partial_hand_fill_and_contains(suit, rank, expected):
    card_list = [
        Deck.generate_card_from_index(card_index) for card_index in test_list
    ]
    hand = BridgeHand.generate_partially_played_hand(card_list)
    assert hand.contains_card(Card(suit, rank)) == expected
Esempio n. 27
0
    def test_add_cards_to_collection(self):
        card = Card(rank="Ace", suit="Spades")
        deck = Deck()
        deck.add_cards([card])

        self.assertEqual(deck.cards, [card])
Esempio n. 28
0
 def __init__(self):
     attackers = Deck()
     blockers = Deck()
Esempio n. 29
0
 def __init__(self) -> None:
     self._deck = Deck()
Esempio n. 30
0
from game.card import Card
from game.deck import Deck
from game.game_round import GameRound
from game.hand import Hand
from game.player import Player

deck = Deck()
cards = Card.create_standard_52_cards()
deck.add_cards(cards)

hand1 = Hand()
hand2 = Hand()

player1 = Player(name="Razak", hand=hand1)
player2 = Player(name="Sue", hand=hand2)

players = [player1, player2]

game_round = GameRound(deck=deck, players=players)
game_round.play()

for player in players:
    print(f"{player.name} receives a {player.hand}.")
    index, hand_name, hand_cards = player.best_hand()

    hand_cards_strings = [str(card) for card in hand_cards]
    hand_cards_sting = " and ".join(hand_cards_strings)
    print(f"{player.name} has a {hand_name} with a {hand_cards_sting}.")
winning_player = max(players)

print(f"{winning_player.name} wins.")
Esempio n. 31
0
class App:
    def __init__(self, argv, size, background=(0, 0, 0)):
        pygame.init()
        pygame.font.init()
        self.argv = argv
        self.size = size
        self.background = background
        self.screen = pygame.display.set_mode(self.size, pygame.RESIZABLE)
        pygame.display.set_caption('UTMagic')
        self.game_objects = []
        self.clock = pygame.time.Clock()
        self.font = pygame.font.SysFont('FreeMono.ttf', 40)
        self.mouse = (0, 0)
        self.mouse_click = False
        self.images = {}
        self.tape = None
        self.deck = None

    def load_images(self):
        all_names = [f for f in listdir("../images") if isfile(join("../images", f))]
        for name in all_names:
            self.images[name] = pygame.image.load(join("../images", name))

    def init_game(self):
        Side((565, 50), ["rotlung_reanimator",
                         "necromancien_de_xathrid", "wild_evocation", "recycle",
                         "privileged_position", "vigor", "archonte_brulant"], (7, 1), self)
        Side((565, 730), ["rotlung_reanimator", "cloak_of_invisibility",
                          "roue_du_soleil_et_de_la_lune", "gains_illusoires", "fungus_sliver",
                          "steely_resolve", "dread_of_night", "shared_triumph", "vigor",
                          "archonte_brulant", "ancient_tomb", "mesmeric_orb",
                          "augure_prismatique", "choke"], (7, 2), self)
        handler = Handler(self.argv)
        self.tape = Tape(handler.get_init(), (960, 360), self)
        # state_changed, symbol, direction = handler.next() # bool, char, int
        self.deck = Deck((1600, 650), self.tape, handler, self)

    def spawn(self, obj):
        self.game_objects.append(obj)

    def handle_input(self):
        self.mouse = pygame.mouse.get_pos()
        self.mouse_click = False
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    self.deck.flip_mode()
                if event.key == pygame.K_LEFT:
                    self.tape.index = 0
                if event.key == pygame.K_RIGHT:
                    self.deck.next_phase()
            if event.type == pygame.MOUSEBUTTONDOWN:
                self.mouse_click = True

    def run(self):
        while True:
            self.handle_input()
            delta_time = self.clock.tick()
            self.screen.fill(self.background)
            for obj in self.game_objects:
                obj.update(delta_time)
                self.game_objects.sort(key=lambda o: o.layer)
                obj.draw(self.screen)
            pygame.display.flip()