Example #1
0
 def create_deck(game_title, data):
     deck = Deck('Starter Deck')
     for item in data[game_title]:
         if item['color'] not in Card.valid_colors:
             raise ValueError(f"Invalid color '{item['color']}' in "
                              f"'{game_title} : {item['name']}'")
         else:
             card = Card(item['name'], item['color'])
             for i in range(item['count']):
                 deck.add(card)
     return deck
 def create():
     main_deck = Deck(id=const.MAIN_DECK_ID,
                      name='main',
                      conn=self.conn,
                      parent=None)
     decks = {main_deck.id: main_deck}  # maps ids to decks
     for deck_row in self.deck_rows[1:]:  # skip main deck row
         id, name, parent_id = deck_row
         parent = decks[parent_id]
         deck = Deck(id=id, name=name, conn=self.conn, parent=parent)
         parent.add_subdeck(deck)
         decks[id] = deck
     return main_deck, decks
Example #3
0
    def initialise(self, game):
        """Prepare the initial state for the game. Initialise all decks.
        This is run once at the start of every game."""

        # Create a list with the Draw Deck and the 2 other empty decks
        game_decks = [
            self.initialise_draw_deck(game),
            Deck('discard'),
            Deck('exclude')
        ]

        self.deck = {deck.name: deck for deck in game_decks}
        self.stats = Stats(self.deck)
        self.epidemic_count = 0
        self.log.clear()
        self.log.log(f'<b>New game: {game}</b>\n')
Example #4
0
def decks_from_tsv(filename):
    decks = []
    with open(filename) as tsvfile:
        reader = csv.DictReader(tsvfile, dialect='excel-tab')
        for row in reader:
            deck = Deck(id=row['Deck Id'], name=row['Deck Name'])
            decks.append(deck)
    return decks
Example #5
0
    def epidemic(self, card):
        """Draw a card from the bottom of the Draw Deck, discard it
        and shuffle the discard pile back onto the top of the Draw Deck."""
        new_card = self.deck['draw'].get_card_from_bottom(card)
        self.deck['draw'].remove_from_bottom(new_card)
        self.deck['discard'].add(new_card)
        self.epidemic_count += 1

        # Create new card pool
        new_cards = Deck(f'Epidemic #{self.epidemic_count}')
        for card in self.deck['discard'].cards.copy():
            new_cards.add(card)
        self.deck['draw'].add(new_cards)

        # Clear the discard pile
        self.deck['discard'].clear()
        self.log.log(f'<b>Epidemic #{self.epidemic_count} ({new_card.name})\
                shuffled</b>')
Example #6
0
 def __init__(self):
     while True:
         try:
             num_decks = int(
                 input("How many decks would you like to play with? "))
             if not 1 <= num_decks <= 10:
                 raise ValueError
             break
         except ValueError:
             print("The number of cards should be between 1 and 10.")
     self.deck = Deck(num_decks, True)
     self.dealer = Player("Dealer", 0)
     self.players()
     game_continues = True
     while game_continues:
         self.game()
         for plr in self.players:
             if plr.total_money <= 1:
                 print('{} does not have any money.'.format(plr.name))
                 print("Game over! The dealer wins :P")
                 game_continues = False
Example #7
0
 def __init__(self,
              *names,
              console,
              bet=100,
              cash=500,
              players=2,
              mode=Mode.dark):
     self.__mode = mode
     self.__bet = bet
     self.__csl = console
     if players < len(names):
         players = len(names) + 1
     self.players = [
         BJPlayer(name=nome, npc=False, cash=cash) for nome in names
     ]
     for i in range(players - len(self.players)):
         self.players.append(BJPlayer(name=f'NPC-{i}', npc=True, cash=cash))
     if len(self.players) > 7:
         raise Exception("No more than 7 players, please...")
     if mode in [self.Mode.dark_dealer, self.Mode.one_up_dealer]:
         self.players.append(
             BJPlayer(name="Dealer", npc=True, cash=float('inf')))
     self.deck = Deck()
    def _create_deck(self, name, parent):
        """
        Just a utility for self._create_deck_path.
        Creates the deck instance and writes it to the database
        """

        deck = Deck(id=utils.getid(self.conn, 'deck'),
                    name=name,
                    conn=self.conn,
                    parent=parent)
        parent.add_subdeck(deck)
        parent_id = parent.id
        deck.conn.execute(
            'INSERT INTO deck(id, name, parent_id) VALUES (?, ?, ?)',
            (deck.id, deck.name, parent_id))
        deck.conn.commit()
        return deck
Example #9
0
class TestDeck(unittest.TestCase):
    def setUp(self):
        self.deck = Deck()
        self.fake_cards = [ FakeCard(), FakeCard(), FakeCard() ]
        self.deck.cards = self.fake_cards[:]

    def test_shuffle_randomizes_card_order(self):
        # arrange
        sorted_cards = []
        for i in xrange(10000):
            sorted_cards.append(FakeCard())
        self.deck.cards = sorted_cards[:]
        # act
        self.deck.shuffle()
        # assert
        self.assertEqual(len(self.deck.cards), len(sorted_cards))
        self.assertNotEqual(self.deck.cards, sorted_cards)
    
    def test_shuffle_flips_cards(self):
        # arrange
        Deck.SHUFFLE_FLIP_PROBABILITY = 1.0
        # act
        self.deck.shuffle()
        # assert
        for card in self.fake_cards:
            self.assertTrue(card.flip_called)
    
    def test_nextCard_returns_cards_in_correct_order(self):
        # arrange
        next_cards = []
        # act
        for i in range(len(self.fake_cards)):
            next_cards.append(self.deck.nextCard())
        # assert
        self.assertEqual(next_cards, self.fake_cards)

    def test_nextCard_throws_exception_when_deck_empty(self):
        # arrange
        try:
            # act
            for i in range(len(self.fake_cards) + 1):
                self.deck.nextCard()
        except DeckEmptyException:
            pass
Example #10
0
def new_game():
    # создаем колоду
    d = Deck()
    # задаем "руки" для игрока и дилера
    player_hand = Hand("Player")
    dealer_hand = Hand("Dealer")
    # сдаем две карты игроку
    player_hand.add_card(d.deal_card())
    player_hand.add_card(d.deal_card())
    # сдаем одну карту дилеру
    dealer_hand.add_card(d.deal_card())
    print(dealer_hand)
    print("=" * 20)
    print(player_hand)
    # Флаг проверки необходимости продолжать игру
    in_game = True
    # набирать карты игроку имеет смысл только если у него на руке меньше 21 очка
    while player_hand.get_value() < 21:
        ans = input("Hit or stand? (h/s) ")
        if ans == "h":
            player_hand.add_card(d.deal_card())
            print(player_hand)
            # Если у игрока перебор - дилеру нет смысла набирать карты
            if player_hand.get_value() > 21:
                print("You lose")
                in_game = False
        else:
            print("You stand!")
            break
    print("=" * 20)
    if in_game:
        # По правилам дилер обязан набирать карты пока его счет меньше 17
        while dealer_hand.get_value() < 17:
            dealer_hand.add_card(d.deal_card())
            print(dealer_hand)
            # Если у дилера перебор играть дальше нет смысла - игрок выиграл
            if dealer_hand.get_value() > 21:
                print("Dealer bust")
                in_game = False
    if in_game:
        # Ни у кого не было перебора - сравниваем количество очков у игрока и дилера.
        # В нашей версии если у дилера и игрока равное количество очков - выигрывает казино
        if player_hand.get_value() > dealer_hand.get_value():
            print("You win")
        else:
            print("Dealer win")
Example #11
0
 def test_moving_card_to_a_deck(self):
     deck2 = Deck('exclude')
     self.deck.add(self.card1)
     self.deck.move(self.card1, deck2)
     self.assertNotIn(self.card1, self.deck)
     self.assertIn(self.card1, deck2)
Example #12
0
class BlackJack:
    """ BlackJackClass - Main actions for the game """
    class Mode:
        dark = 0
        one_up = 1
        dark_dealer = 2
        one_up_dealer = 3

    def __init__(self,
                 *names,
                 console,
                 bet=100,
                 cash=500,
                 players=2,
                 mode=Mode.dark):
        self.__mode = mode
        self.__bet = bet
        self.__csl = console
        if players < len(names):
            players = len(names) + 1
        self.players = [
            BJPlayer(name=nome, npc=False, cash=cash) for nome in names
        ]
        for i in range(players - len(self.players)):
            self.players.append(BJPlayer(name=f'NPC-{i}', npc=True, cash=cash))
        if len(self.players) > 7:
            raise Exception("No more than 7 players, please...")
        if mode in [self.Mode.dark_dealer, self.Mode.one_up_dealer]:
            self.players.append(
                BJPlayer(name="Dealer", npc=True, cash=float('inf')))
        self.deck = Deck()

    def __enter__(self):
        self.start()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        if exc_val is not None:
            raise exc_val

    # ------------------- functions for playing ----------------------------------
    def start(self):
        # Initialize each player hand with 2 cards
        self.deck.shuffle()
        while sum(len(player)
                  for player in self.players) < 2 * len(self.players):
            for player in self.players:
                player.get_card(self.deck.draw())
        for player in self.players:
            if player.name == 'Dealer' and player.is_npc:
                while abs(
                        player
                ) < 17:  # For dealer type games, dealer cannot start with less than 17 points
                    player.get_card(self.deck.draw())

    def roll(self):  # Play a round
        plays = 0
        for player in self.players:
            if not player.burn:
                if not (player.name == 'Dealer' and player.is_npc):
                    plays += 1
        result = {
            'asks': 0,
            'non-asks': 0,
            'unknown': plays
        }  # plays counts the number of players in the roll
        while result['unknown'] > 0:
            for player in self.players:
                if player.name == 'Dealer' and player.is_npc:  # Dealers only draw cards in the game start
                    continue
                if not player.burn:
                    if player.is_npc:
                        draws = round(random())
                        if draws == 1:  # Modify with machine learning decision making in future version
                            result['asks'] += 1
                            result['unknown'] -= 1
                            player.get_card(self.deck.draw())
                            if player.burn:
                                self.__csl.print(
                                    f'\n==========\n{player.name} BURNS\n===========\n',
                                    self.__csl.textColor.RED)
                        else:
                            result['non-asks'] += 1
                            result['unknown'] -= 1
                    else:
                        if self.__mode == self.Mode.dark or self.__mode == self.Mode.dark_dealer:
                            adver = {
                                play.name: f"{len(play)} cards"
                                for play in self.players
                            }
                        else:
                            adver = {
                                play.name:
                                f"{play.hand[0]} => {len(play)} cards"
                                for play in self.players
                            }
                        self.__csl.print(
                            str("\n\n"
                                f"Player: {player.name}\n\n"
                                f"Opponent:\n"
                                f"{adver}\n"
                                f"Your cards {[card for card in player.hand]} Sum = {abs(player)}\n\n"
                                f"Draw a card? (y/n):\n"))
                        ask = input()
                        while ask.lower() not in ['y', 'n']:
                            ask = input(
                                f"{self.__csl.textColor.YELLOW}Sorry?!\n{self.__csl.style.RESET_ALL}"
                                f"Wanna draw a card? (y/n):\n")
                        if ask.lower() == 'y':
                            result['asks'] += 1
                            result['unknown'] -= 1
                            player.get_card(self.deck.draw())
                            if player.burn:
                                self.__csl.print(
                                    f'\n==========\n{player.name} BURNS\n===========\n',
                                    self.__csl.textColor.RED)
                        else:  # if 'n'
                            result['non-asks'] += 1
                            result['unknown'] -= 1
                player.last_roll = result
            asks = result['asks']
        return result

    def play(self):
        res = 1
        while res > 0:
            self.__csl.clear()
            res = self.roll()['asks']
        self.__csl.clear()
        result = {
            player.name: ('Burn' if player.burn else
                          'BlackJack' if abs(player) == 21 else abs(player))
            for player in self.players
        }
        self.__csl.print(result)
        val = max(abs(player) for player in self.players if not player.burn)
        lista = [player for player in self.players if abs(player) == val]
        for player in self.players:
            if player in lista:
                player += self.__bet * len(self.players) / len(lista)
            else:
                player -= self.__bet

    # ------------------- TODO ----------------------------------
    def showTable():
        pass

    def showPlayerOptions():
        pass

    def showResults():
        pass
Example #13
0
def test_decks():
    return [
        Deck(id='18736cb4-88f4-47af-92f2-4172fb3586a2'),
        Deck(id='869ecc00-4527-4061-b9cb-6c1e1bf4910d'),
        Deck(id='87220b2f-6f59-4095-abb0-14a50d1c53b8')
    ]
Example #14
0
class TestDeck(TestCase):
    def setUp(self):
        self.card1 = Card('Card A', 'black')
        self.card2 = Card('Card B', 'blue')
        self.card3 = Card('Card C', 'red')
        self.deck = Deck('discard')

    def tearDown(self):
        self.card1 = None
        self.card2 = None
        self.deck = None

    def test__len__(self):
        self.deck.add(self.card1)
        self.assertEqual(len(self.deck), 1)
        self.deck.add(self.card2)
        self.assertEqual(len(self.deck), 2)

    def test__iter__(self):
        self.deck.add(self.card1)
        self.deck.add(self.card2)
        i = 0
        for card in self.deck:
            i += 1
        self.assertEqual(i, 2)

    def test_instantiation_parameters(self):
        with self.assertRaises(ValueError):
            self.deck = Deck(0)

    def test_adding_card_to_deck(self):
        self.deck.add(self.card1)
        self.assertIn(self.card1, self.deck)

    def test_removing_card_from_a_deck(self):
        with self.assertRaises(ValueError):  # Check removal from empty deck
            self.deck.remove(self.card1)
        self.deck.add(self.card1)
        self.deck.remove(self.card1)
        self.assertNotIn(self.card1, self.deck)

    def test_moving_card_to_a_deck(self):
        deck2 = Deck('exclude')
        self.deck.add(self.card1)
        self.deck.move(self.card1, deck2)
        self.assertNotIn(self.card1, self.deck)
        self.assertIn(self.card1, deck2)

    def test_clear_a_deck_and_check_if_empty(self):
        self.deck.add(self.card1)
        self.deck.clear()
        self.assertTrue(self.deck.is_empty())

    def test_deck_has_no_parent(self):
        self.assertFalse(self.deck.has_parent())

    def test_get_sorted_deck(self):
        self.deck.add(self.card2)
        self.deck.add(self.card1)
        self.deck.add(self.card3)
        self.assertEqual(self.deck.cards[0], self.card2)
        sorted = self.deck.sorted()
        self.assertEqual(sorted[0], self.card1)
        self.assertEqual(sorted[1], self.card2)
        self.assertEqual(sorted[2], self.card3)
Example #15
0
class Blackjack(object):
    list_of_players = []

    def __init__(self):
        while True:
            try:
                num_decks = int(
                    input("How many decks would you like to play with? "))
                if not 1 <= num_decks <= 10:
                    raise ValueError
                break
            except ValueError:
                print("The number of cards should be between 1 and 10.")
        self.deck = Deck(num_decks, True)
        self.dealer = Player("Dealer", 0)
        self.players()
        game_continues = True
        while game_continues:
            self.game()
            for plr in self.players:
                if plr.total_money <= 1:
                    print('{} does not have any money.'.format(plr.name))
                    print("Game over! The dealer wins :P")
                    game_continues = False

    def players(self):
        while True:
            try:
                num_players = int(input("How many players are playing? "))
                if num_players < 1 or num_players > 9:
                    raise ValueError
                break
            except ValueError:
                print("The number of players should be between 1 and 9.")

        for i in range(num_players):
            name = input("Please write your name: ")
            money = int(
                input("{}, which is the amount that you start with: ".format(
                    name)))
            self.list_of_players.append(player(name, money))

    def game(self):
        self.start_turn(self.players)
        self.play(self.players)
        self.end_turn(self.players)

    def start_turn(self, players):
        for plr in players:
            plr.initialize()
            plr.ask_bet()
            plr.draw_card(self.deck.next_card())
        self.dealer.draw_card(self.deck.next_card())
        for plr in players:
            plr.draw_card(self.deck.next_card())

    def end_turn(self, players):
        for plr in players:
            plr.initialize()
        self.dealer.initialize()

    def play(self, players):
        game_on = False
        for plr in players:
            print(plr)
            self.draw(plr)
            if plr.score <= 21:
                game_on = True
        while self.dealer.score < 17 and game_on:
            self.dealer.draw_card(self.deck.next_card())
        if self.dealer.score > 21:
            print("The dealer has busted!")
            print("All players win their bet.")
            for plr in players:
                plr.total_money += 2 * plr.bet
                print(plr)
        elif game_on:
            for plr in players:
                if plr.score > self.dealer.score:
                    plr.total_money += 2 * plr.bet
                    print("{} won the bet".format(plr.name))
                else:
                    print("{} lost the bet".format(plr.name))
                if plr.score2 > self.dealer.score and plr.score2 > 0:
                    plr.total_money += 2 * plr.bet
                    print("{} won the bet for the side hand".format(plr.name))
                elif plr.score2 > 0:
                    print("{} lost the bet for the side hand".format(plr.name))
                print(plr)

    def draw(self, player):
        end_turn = self.end_condition(player)
        while not end_turn:
            string = "{} has: ".format(player.name)
            for card in player.hand:
                string += str(card) + " "
            print(string)
            print("With total sum {}".format(str(player.score)))
            answer = player.ask_user()
            if answer == 'Hit':
                player.draw_card(self.deck.next_card())
            if answer == 'Stand':
                end_turn = True
            if answer == 'Surrender':
                player.total_money += round(player.bet / 2, 2)
                player.initialize()
                end_turn = True
            if answer == 'Double':
                player.total_money -= player.bet
                player.bet *= 2
                player.draw_card(self.deck.next_card())
                end_turn = True
            if answer == 'Split':
                card1 = self.deck.next_card()
                card2 = self.deck.next_card()
                player.do_split(card1, card2)
                player.total_money -= player.bet
            if self.end_condition(player):
                end_turn = True
            if player.splitted and not player.played_splitted:
                player.score2 = player.score
                player.hand = player.splitted_hand
                player.aces = 0

    def end_condition(self, player):
        if player.score > 21:
            print("{} has busted.".format(player.name))
            player.initialize()
            return True
        if player.score == 21 and len(player.hand) == 2:
            print("Congratulations {}, you made a BlackJack!".format(
                player.name))
            player.total_money += 2.3 * player.bet
            player.initialize()
            return True
        if player.score == 21 and not len(player.hand) == 2:
            print("Congratulations {}, you have a 21!".format(player.name))
            return True
        return False
Example #16
0
 def setUp(self):
     self.card1 = Card('Card A', 'black')
     self.card2 = Card('Card B', 'blue')
     self.card3 = Card('Card C', 'red')
     self.deck = Deck('discard')
Example #17
0
 def test_instantiation_parameters(self):
     with self.assertRaises(ValueError):
         self.deck = Deck(0)
Example #18
0
 def setUp(self):
     self.deck = Deck()
     self.fake_cards = [ FakeCard(), FakeCard(), FakeCard() ]
     self.deck.cards = self.fake_cards[:]