Example #1
0
 def __init__(self):
     Card.__init__(self)
     self.cardtype = 'action'
     self.base = 'intrigue'
     self.desc = "Choose: +2 cards, +2 coin, trash 2 cards"
     self.name = 'Steward'
     self.cost = 3
Example #2
0
 def __init__(self):
     Card.__init__(self)
     self.cardtype = 'action'
     self.desc = "Reveal a provice to gain gold else gain silver"
     self.name = 'Explorer'
     self.base = 'seaside'
     self.cost = 5
Example #3
0
 def __init__(self):
     Card.__init__(self)
     self.cardtype = 'action'
     self.base = 'dominion'
     self.desc = "Trash a card and gain one costing 2 more"
     self.name = 'Remodel'
     self.cost = 2
Example #4
0
 def __init__(self):
     Card.__init__(self)
     self.cardtype = 'treasure'
     self.base = 'renaissance'
     self.buys = 1
     self.name = 'Ducat'
     self.cost = 2
Example #5
0
 def __init__(self):
     Card.__init__(self)
     self.cardtype = ['action', 'gathering']
     self.base = 'empires'
     self.name = "Farmers' Market"
     self.buys = 1
     self.cost = 3
Example #6
0
 def __init__(self):
     Card.__init__(self)
     self.cardtype = ['action']
     self.base = 'hinterlands'
     self.desc = "Reveal your hand. +1 Card per Victory card revealed. If this is the first time you played a Crossroads this turn, +3 Actions."
     self.name = 'Crossroads'
     self.cost = 2
Example #7
0
 def __init__(self):
     Card.__init__(self)
     self.cardtype = 'action'
     self.base = 'dominion'
     self.desc = "Trash a treasure, gain a better treasure"
     self.name = 'Mine'
     self.cost = 5
Example #8
0
 def __init__(self):
     Card.__init__(self)
     self.cardtype = 'action'
     self.base = 'prosperity'
     self.desc = "Trash cards from hand and gain one worth the sum of the trashed cards"
     self.name = 'Forge'
     self.cost = 7
Example #9
0
 def __init__(self):
     Card.__init__(self)
     self.cardtype = ['action', 'reaction']
     self.desc = """Draw until you have 6 cards in hand.
     When you gain a card, you may reveal this from your hand. If you do, either trash that card, or put it on top of your deck."""
     self.name = 'Watchtower'
     self.cost = 3
Example #10
0
 def __init__(self):
     Card.__init__(self)
     self.cardtype = 'action'
     self.base = 'cornucopia'
     self.desc = """Reveal the top 4 cards of your deck, then discard them. Coin per differently named card revealed."""
     self.name = 'Harvest'
     self.cost = 5
Example #11
0
 def __init__(self):
     Card.__init__(self)
     self.cardtype = 'action'
     self.base = 'dominion'
     self.desc = "Trash a copper from hand for +3 coin"
     self.name = 'Money Lender'
     self.cost = 4
Example #12
0
 def __init__(self):
     Card.__init__(self)
     self.cardtype = 'action'
     self.base = 'intrigue'
     self.desc = "Copper produces an extra +1 this turn"
     self.name = 'Coppersmith'
     self.cost = 4
Example #13
0
 def __init__(self):
     Card.__init__(self)
     self.cardtype = ['action', 'attack', 'night', 'doom']
     self.base = 'nocturne'
     self.desc = "If it's your Night phase, each other player receives the next Hex.  Otherwise, +3 Cards."
     self.name = 'Werewolf'
     self.cost = 5
 def straightFlush(self, leastValue, suit):
     card = Card(leastValue, suit)
     cards = [card]
     for _ in range(0, 4):
         card = card.getNext()
         cards.append(card)
     return Hand(cards)
Example #15
0
 def __init__(self):
     Card.__init__(self)
     self.cardtype = ['night', 'duration', 'attack']
     self.base = 'nocturne'
     self.desc = "Each other player with 5 or more cards in hand discards a copy of a card you have in play (or reveals they can't). At the start of your next turn, +3 Coins"
     self.name = 'Raider'
     self.cost = 6
Example #16
0
 def __init__(self):
     Card.__init__(self)
     self.cardtype = ['action', 'duration']
     self.base = 'seaside'
     self.desc = "Discard hand; +5 cards, +1 buy and +1 action next turn"
     self.name = 'Tactician'
     self.cost = 5
Example #17
0
 def __init__(self):
     Card.__init__(self)
     self.cardtype = 'action'
     self.base = 'darkages'
     self.desc = """Trash a card from your hand. Gain a card costing up to 5 Coin."""
     self.name = 'Altar'
     self.cost = 6
Example #18
0
 def __init__(self):
     Card.__init__(self)
     self.cardtype = 'action'
     self.base = 'dominion'
     self.desc = "Dig through deck for two treasures"
     self.name = 'Adventurer'
     self.cost = 6
Example #19
0
 def __init__(self):
     Card.__init__(self)
     self.cardtype = 'action'
     self.base = 'renaissance'
     self.desc = """Discard your hand. +7 Cards."""
     self.name = 'Scholar'
     self.cost = 5
Example #20
0
 def __init__(self):
     Card.__init__(self)
     self.cardtype = 'action'
     self.base = 'dominion'
     self.desc = "Gain a card costing up to 4"
     self.name = 'Workshop'
     self.cost = 3
Example #21
0
 def __init__(self):
     Card.__init__(self)
     self.cardtype = ['action', 'attack']
     self.base = 'darkages'
     self.desc = """+4 Coin. Reveal your hand. -1 Coin per Treasure card in your hand, to a minimum of 0."""
     self.name = 'Poor House'
     self.cost = 1
Example #22
0
 def __init__(self):
     Card.__init__(self)
     self.cardtype = 'action'
     self.base = 'hinterlands'
     self.desc = """You may trash a Treasure from your hand. If you do, choose one: +2 Cards and +1 Action; or +2 Coins and +1 Buy."""
     self.name = 'Spice Merchant'
     self.cost = 4
Example #23
0
 def __init__(self):
     Card.__init__(self)
     self.cardtype = 'action'
     self.base = 'renaissance'
     self.desc = "Gain a card costing up to 4, then cards cost 1 less this turn (but not less than 0)."
     self.name = 'Inventor'
     self.cost = 4
Example #24
0
 def __init__(self):
     Card.__init__(self)
     self.cardtype = 'action'
     self.base = 'darkages'
     self.desc = "Gain a card costing up to 4 putting it on top of your deck"
     self.name = 'Armory'
     self.cost = 4
Example #25
0
 def __init__(self):
     Card.__init__(self)
     self.cardtype = ['action', 'gathering']
     self.base = 'empires'
     self.desc = """Choose one: +3 Cards and add 1 VP to the Wild Hunt Supply pile; or gain an Estate, and if you do, take the VP from the pile."""
     self.name = 'Wild Hunt'
     self.cost = 5
Example #26
0
 def __init__(self):
     Card.__init__(self)
     self.cardtype = 'action'
     self.base = 'renaissance'
     self.desc = """Gain a card to your hand costing up to 4. If it's a Treasure, +1 Villager."""
     self.name = 'Sculptor'
     self.cost = 5
Example #27
0
 def __init__(self):
     Card.__init__(self)
     self.cardtype = ['action', 'attack']
     self.base = 'dominion'
     self.desc = "Gain a Gold. Each other player reveals the top 2 cards of their deck, trashes a revealed Treasure other than Copper, and discards the rest."
     self.name = 'Bandit'
     self.cost = 5
Example #28
0
 def __init__(self):
     Card.__init__(self)
     self.cardtype = 'action'
     self.base = 'renaissance'
     self.name = 'Acting Troupe'
     self.desc = "+4 Villagers. Trash this."
     self.cost = 3
Example #29
0
 def __init__(self):
     Card.__init__(self)
     self.cardtype = ['action', 'attack', 'doom']
     self.base = 'nocturne'
     self.name = 'Skulk'
     self.buys = 1
     self.cost = 4
Example #30
0
 def __init__(self):
     Card.__init__(self)
     self.cardtype = 'action'
     self.base = 'hinterlands'
     self.name = 'Mandarin'
     self.coin = 3
     self.cost = 5
Example #31
0
    def CreateUser(self):
        username = input('请输入您的真实姓名:')
        IdCard = input('请输入您的IdCard:')
        phone = input('请输入您的电话号码:')
        while True:
            prestoreMoney = input('请输入预存款')
            if not self.CheckprestoreMoney(prestoreMoney):
                break
        password = input('请设置您的密码:')
        if not self.PwdCheck(password):
            print('密码错误,开户失败')
            return -1

        cardId = self.RandomCardId()

        card = Card(cardId, password, prestoreMoney)
        user = User(username, IdCard, phone, card)
        self.users[cardId] = user
        print('开通成功,请牢记卡号%s' % cardId)
Example #32
0
    def __init__(self):
        self.cards = []

        for i in range(1, 14):
            for index in range(1, 5):
                num = i
                card_type = self.card_types[index]

                if i == 1:
                    point_val = (1, 11)
                elif i >= 11:
                    point_val = 10
                else:
                    point_val = i

                card = Card(num, card_type, point_val)
                self.cards.append(card)

        shuffle(self.cards)
Example #33
0
 def validate_deck(self, deck):
     assert (len(deck) == 52), 'Not a 52 card deck.'
     for card in deck:
         try:
             Card(
                 card.get_rank(), card.get_suit()
             )  # Get the rank and suit and try to remake the card. If a error happens and catch it and raise another error giving a general reason why.
         except:
             raise Exception('Found an invalid card in the deck')
     for card in deck:
         already_occured = False  # I need this so when I compare a card with the rest of the card in the deck, a card won't a raise an error for finding itself.
         for other_card in deck:
             if card.get() == other_card.get(
             ) and already_occured:  # If already_occured is true and another 2 cards are equal, then that means there's duplicates.
                 raise Exception('Duplicate cards in the deck.')
             elif card.get() == other_card.get(
             ):  # This will allow a card to be okay with finding itself once in the deck.
                 already_occured = True
     return True
Example #34
0
    def would_have_left_bower(self, top_card: Card) -> bool:
        """
        Determine if the player would have the left bower, given that the top card is picked up.

        This function should only be used in bidding. It tries to determine that if the player ordered up the top card,
        that they would now have a left bower in their hand.

        :attention unit tests written.

        :param top_card: The top card on the deck, used in bidding.
        :return: True if the player would have the left bower. False otherwise, including the situation where the player
        would have the right bower. For that information call would_have_right_bower().
        """
        for card in self.hand:
            # Note: card.suit is used here since this is only used in bidding, and therefore the trump card is not set.
            if card.value == Card.JACK and Card.get_matching(
                    top_card._suit) == card._suit:
                return True
        return False
Example #35
0
 def pick_card(self,data):
     cadidate_cards=data['self']['candidateCards']
     cards = data['self']['cards']
     self.my_hand_cards = []
     for card_str in cards:
         card = Card(card_str)
         self.my_hand_cards.append(card)
     message = "My Cards:{}".format(self.my_hand_cards)
     system_log.show_message(message)
     card_index=0
     message = "Pick Card Event Content:{}".format(data)
     system_log.show_message(message)
     message = "Candidate Cards:{}".format(cadidate_cards)
     system_log.show_message(message)
     system_log.save_logs(message)
     message = "Pick Card:{}".format(cadidate_cards[card_index])
     system_log.show_message(message)
     system_log.save_logs(message)
     return cadidate_cards[card_index]
Example #36
0
def main():
    #make a temporary object

    deck = Deck()
    hand = Hand()
    deck.shuffle()
    #print deck.toString()

    card1 = Card("", "")
    card1 = deck.drawNext()
    hand.AddCard(card1)
    print hand.toString()

    card1 = deck.drawNext()
    hand.AddCard(card1)
    print hand.toString()

    total = hand.totalValue()
    print "Your hand is worth " + str(total)
Example #37
0
 def __init__(self):
     #初始化扑克牌类型
     self.cards_type = [
         'A-方块-12-1', 'A-梅花-12-14', 'A-红桃-12-27', 'A-黑桃-12-40', '2-方块-13-2',
         '2-梅花-13-15', '2-红桃-13-28', '2-黑桃-13-41', '3-方块-1-3', '3-梅花-1-16',
         '3-红桃-1-29', '3-黑桃-1-42', '4-方块-2-4', '4-梅花-2-17', '4-红桃-2-30',
         '4-黑桃-2-43', '5-方块-3-5', '5-梅花-3-18', '5-红桃-3-31', '5-黑桃-3-44',
         '6-方块-4-6', '6-梅花-4-19', '6-红桃-4-32', '6-黑桃-4-45', '7-方块-5-7',
         '7-梅花-5-20', '7-红桃-5-33', '7-黑桃-5-46', '8-方块-6-8', '8-梅花-6-21',
         '8-红桃-6-34', '8-黑桃-6-47', '9-方块-7-9', '9-梅花-7-22', '9-红桃-7-35',
         '9-黑桃-7-48', '10-方块-8-10', '10-梅花-8-23', '10-红桃-8-36',
         '10-黑桃-8-49', 'J-方块-9-11', 'J-梅花-9-24', 'J-红桃-9-37', 'J-黑桃-9-50',
         'Q-方块-10-12', 'Q-梅花-10-25', 'Q-红桃-10-38', 'Q-黑桃-10-51',
         'K-方块-11-13', 'K-梅花-11-26', 'K-红桃-11-39', 'K-黑桃-11-52',
         'w-小王-14-53', 'W-大王-15-54'
     ]
     self.cards = []
     for card_type in self.cards_type:
         self.cards.append(Card(card_type))
Example #38
0
    def addCard(self, card, index):

        if self.cardsInTrick == 0:  # if this is the first card added, set the trick suit
            self.setTrickSuit(card)
            if Variables.printsOn:
                print 'Current trick suit:', self.suit

        self.trick[index] = card
        self.cardsInTrick += 1

        if card.suit == Suit(hearts):
            self.points += 1
        elif card == Card(queen, spades):
            self.points += 13

        if card.suit == self.suit:
            if card.rank.rank > self.highest:
                self.highest = card.rank.rank
                self.winner = index
Example #39
0
    def doubleMore(self):
        if not self.playing:
            print("Bet for new round first. [doubleMore called]")
            return False

        if self.player.total() > 21:
            print("Already exceed 21 [doubleMore called]")
            return False

        if self.player.doubleBet(
        ):  # if enough money for doubleBet, spend it and return True
            c = Card(self.dealer.draw())
            self.player.addCard(c)
            self.stop()
            return True

        else:
            print("Not enough money to double. [doubleMore called]")
            return False
Example #40
0
def get_second_card(first_card):
    """
    Generates a pseudo-random second card; improves likelihood of two same numbers showing up to 20%
    :param first_card: Randomly generated first card
    :return: Card object
    """
    possible_cards = []
    first_val = first_card.val
    possible_cards.append(first_val)
    for i in range(0, 3):
        rand = randint(2, 14)
        # Ensure only a non-first_val number is inserted, to maintain 20% probability
        while rand != first_val:
            possible_cards.append(rand)
            break

    suit = choice(suit_list)
    number = get_number_from_val(choice(possible_cards))
    return Card(suit, number)
Example #41
0
    def getStockPile(self):
        stockPile = []
        isStockPile = False
        reader = open(self.fileName, "r")
        try:
            for line in reader:
                for word in line.split():
                    if word == "Stock":
                        isStockPile = True
                    if word == "Pile:" and isStockPile == True:
                        line = line.replace("Stock Pile:", "")
                        for word in line.split():
                            card = Card(0, 0, word)
                            stockPile.append(card)
                        isStockPile = False

        finally:
            reader.close()
            return stockPile
 def test_draw_21(self):
     player = Player(
         [Card('Hearts', 'J'),
          Card('Clubs', '5'),
          Card('Clubs', '6')], False, False, 500, 0)
     dealer = Dealer(
         [Card('Hearts', 'J'),
          Card('Clubs', '5'),
          Card('Clubs', '6')], True, True, True, False)
     dealer.checkWin(player)
     self.assertTrue(
         dealer.roundOver,
         f"dealer.roundOver = {dealer.roundOver} // If both players are 21 - game over should be True"
     )
Example #43
0
    def __init__(self, pot: int, players: [Player], cards: [Card]):
        """This builds a hand with players, a pot value and cards on the board.

        PRE : [int] pot : valeur du pot au début de la main
              [List of Player] players : all players present in the hand
              [List of Card] cards : cards to display on the poker table
        POST : Create a new hand of poker
        """
        self._players = []
        self._pot = pot
        self._board = []
        if len(players) > 0:
            for player in players:
                self._players.append(
                    Player(player['name'], player['stack'], player['position'],
                           player['actions'], player['result'],
                           player['status'], player['hand']))
        if len(cards) > 0:
            for card in cards:
                self._board.append(Card(card['value'], card['color']))
Example #44
0
    def __init__(self, difficulty):
        self.cards = []
        self.frequencies = [3, 2, 2, 2, 1]
        self.excluded_colors = ["Unknown"]

        if difficulty == "Normal":
            self.excluded_colors.append("Rainbow")

        elif difficulty == "Difficult":
            self.frequencies = [1, 1, 1, 1, 1]

        for color in colors.keys():
            if color not in self.excluded_colors:
                for number in numbers:
                    for x in range(self.frequencies[int(number) - 1]):
                        self.cards.append(Card(color, number))

        shuffle(self.cards)

        self.cards_remaining = len(self.cards)
Example #45
0
async def parse_bestbuy_url(s, url, model):
    # Narrow HTML search down using HTML class selectors.
    r = await s.get(url)
    cards = r.html.find('.right-column')

    if len(cards) == 0:
        print(f"No items found for url: {url}")

    for item in cards:      
        card = Card.create_from_bestbuy(item, model)

        if card is not None:
            card_id = card.get_item_id()
            if card_id in card_set.keys():
                if card_set[card_id].get_button_text() != card.get_button_text():
                    original_text = card_set[card_id].get_button_text()
                    if card.is_in_stock():
                        notify_difference(card, original_text)

            card_set[card_id] = card
Example #46
0
	def createCards(self):

		# get the type of cards to use in function of the game number
		myStr = "m " + str(self.gameNumber)
		publisher_tablet.publish(myStr)
		rospy.sleep(1)
		
		value = 0
		nbValue = self.nbCard/2
		vectorIndice = range(0, self.nbCard)

		for i in xrange(self.nbCard):
			self.remainingCard.append(Card(i, -1))


		while len(vectorIndice) > 0:

			# randomly pick an indice in vectorIndice
			indice = random.choice(vectorIndice)
			# remove this indice from the vector
			vectorIndice.remove(indice)
			# create card with this indice and value
			self.remainingCard[indice].setValue(value)

			# randomly pick an indice in vectorIndice
			indice = random.choice(vectorIndice)
			# remove this indice from the vector
			vectorIndice.remove(indice)
			# create card with this indice and value
			self.remainingCard[indice].setValue(value)

			# increase value by +1
			value += 1

		myStr = "i "
		for card in self.remainingCard:
			myStr += str(card.getValue())
			myStr += " "

		# communicate nb value to position to tablet
		publisher_tablet.publish(myStr)
Example #47
0
    def step(self, action):
        # if opened a new account
        if action[0] != '':
            opened_card = action[0]
            # add card to card list
            opened_card_dict = None
            for c in self.card_dict:
                if c['card'] == opened_card:
                    opened_card_dict = c
            self.cards[opened_card] = Card(opened_card_dict,
                                           self.state['month'])
            # add card to state
            self.state[opened_card] = 1

        # assign spend to account
        card_to_spend = action[1]
        reward = self.cards[card_to_spend].apply_transactions(
            {
                'category': self.state['category'],
                'amount': self.cur_trans_amt
            }, self.state['month'])

        # calculate AMFs
        amfs = 0
        for c in self.cards:
            amfs += self.cards[c].calc_amf(self.state['month'])

        # get next observation
        self.trans_idx += 1
        if self.trans_idx >= len(self.trans_info):
            self.cur_trans_cat = None
            self.cur_trans_amt = None
            self.done = True
        else:
            self.cur_trans_cat = self.trans_info.iloc[
                self.trans_idx]['category']
            self.cur_trans_amt = self.trans_info.iloc[self.trans_idx]['amount']
            self.state['month'] = self.trans_info.iloc[self.trans_idx]['month']
        self.state['category'] = self.cur_trans_cat

        return (self.state, reward + amfs, self.done)
Example #48
0
    def __init__(self, nDeck=6, seed=None, presetCards=None):
        self.nDeck = nDeck
        self.top = 0
        self.playcard = []
        if seed is not None:
            random.seed(seed)

        if presetCards is not None:
            self.playcard = []
            for i in presetCards:
                self.playcard.append(i)
            return

        # 六副牌
        # temp = [0, 1, 2, 3, ..., 51, 0, 1, ..., 51]
        temp = [x for x in range(52)] * self.nDeck
        random.shuffle(temp)  # 將temp中的數字隨機排序
        for num in temp:  # 每個數字代表一張牌
            s = num // 13
            r = num % 13 + 1
            self.playcard.append(Card(s, r))
Example #49
0
    def nextGame(self):
        changeDirection = self.winStreak == 0
        self.gamesPlayed += 1
        if self.gamesPlayed % 4 == 0:
            self.direction = self.direction.nextDirection()
        self.turn = Card.special(1)
        self.actionTurn = False
        self.winner = None
        for p in self.players:
            p.nextGame(changeDirection)
        self.discardPile = []
        self.deck = createDeck()
        self.actionsReceived = {}
        self.newGame = True
        self.addKong = False

        # all players draw 13 cards, first player draws 14
        for p in self.players:
            p.setHand([self.deck.pop() for i in range(13)])
        self.playerFromDirection(self.turn).draw(self.deck.pop())
        self.drawPile = len(self.deck)
Example #50
0
def generate_board_states_placement(state, coord, id, old_card, orientations):
    #  Possible states resulting in the placement of a card
    state_list = list()

    for orientation in orientations:
        new_state = copy.deepcopy(state)
        new_card = Card(id, orientation, coord)
        # Make sure the card is in a new position orientation
        if old_card and old_card.orientation == new_card.orientation and old_card.coords1 == new_card.coords1:
            continue

        # If there already exists a card in the cell then skip
        #if state.board[new_card.coords1].card or state.board[new_card.coords2].card:
        #    print('This should never be reached {}'.format(state.top_empty_cell))
        #    break

        BoardHelper.fill_cells(new_card, new_state)
        new_state.last_moved_card = new_card
        state_list.append(new_state)

    return state_list
def last_played():
    payload = {
        'message': None
    }

    res = rq.get(game_server + "last_played")

    res = json.loads(res.text)

    if res['card'] is None:
        payload['message'] = 'No card in game state. You may play any card.'
    else:
        # create default suit - spade (currently not keeping track of suit)
        payload['message'] = \
            "\n".join(Card(Suits.SPADES, str(res['card'])).get_ascii_front())

    print "Last played card:\n"

    io_print(payload, card=True)

    return jsonify(payload)
Example #52
0
    def __init__(self):
        '''
        Constructor
        '''
        self.__levelCount = int(
            raw_input("to define the parking lot's level count:"))
        cards = []
        for i in range(self.__levelCount):
            levelId = i + 1
            self.__spaceCountEachLevel = int(
                raw_input("to define the space count in level " +
                          str(levelId) + " of the parking lot:"))
            spacesOfEachLevel = []
            for j in range(self.__spaceCountEachLevel):
                spaceId = i * self.__spaceCountEachLevel + j + 1
                spacesOfEachLevel.append(Space(spaceId))
                cards.append(Card(spaceId, levelId, spaceId))
            self.__levels.append(Level(spacesOfEachLevel, levelId))
            self.__totalSpaceCount += self.__spaceCountEachLevel

        self.__cardReader = CardReader(cards)
Example #53
0
    def newDeck(self):
        suits = ["Hearts", "Diamonds", "Spades", "Clubs"]
        cFaces = [2, 3, 4, 5, 6, 7, 8, 9, 10, "Jack", "Queen", "King", "Ace"]

        value = 0
        for suit in suits:
            for number in cFaces:
                if (number == "Jack"):
                    value = 10
                elif (number == "Queen"):
                    value = 10
                elif (number == "King"):
                    value = 10
                elif (number == "Ace"):
                    value = 11  ####### should be 1 OR 11
                else:
                    value = number

                newCard = Card(suit, number, value)
                self.thisDeck.append(newCard)
        return self
Example #54
0
    def test_basic_stand_and_hit(self):
        p1 = Player(Hand([Card('HJ'), Card('HQ')]))
        upcard = Card('S2')
        shoe = []
        shoe.append(Card('CJ'))

        self.assertEqual(len(shoe), 1)
        Jack.turn(shoe, p1, 0, upcard)
        self.assertEqual(p1.hands[0].status, 'stand')
        self.assertEqual(len(shoe), 1)

        p2 = Player(Hand([Card('H3'), Card('H4')]))
        Jack.turn(shoe, p2, 0, upcard)

        self.assertEqual(p2.hands[0].status, 'stand')
        self.assertEqual(len(shoe), 0)
Example #55
0
    def __init__(self):
        self.deck = []
        suits = ('Hearts', 'Diamonds', 'Clovers', 'Spades')
        ranks = {
            'Ace': 11,
            '2': 2,
            '3': 3,
            '4': 4,
            '5': 5,
            '6': 6,
            '7': 7,
            '8': 8,
            '9': 9,
            '10': 10,
            'Jack': 10,
            'Queen': 10,
            'King': 10
        }

        for suit in suits:
            for rank, value in ranks.items():
                self.deck.append(Card(suit=suit, rank=rank, value=value))
    def __init__(self, value_start, value_end, number_of_suits, new_suit=None):
        #initializing values required by Deck class
        self.new_deck = []
        self.start = value_start
        self.end = value_end
        self.n = number_of_suits
        # Note that because rank is 0-indexed but when displaying, it should be 1-indexed, it is necessary
        # to add one. Thus, 12 actually represents King (not Queen) and 0 represents Ace.
        # suits are H - Heart , S - Spade, D - Diamond, C - Clubs

        self.suitname = ["H", "S", "D", "C"]
        if self.n <= 4:
            # random.sample takes list and number of items to randomly choose from as agruments
            self.suits = random.sample(self.suitname, self.n)
        else:
            self.suitname.extend(new_suit)
            self.suits = random.sample(self.suitname, self.n)
        #creating Card class instance will help us get the card in rank:suit format
        #Then appending the card to new_deck class to have required number of cards with chosen number of suits
        for j in range(self.start, self.end + 1):
            for symbol in self.suits:
                self.new_deck.append(str(Card(j, symbol)))
Example #57
0
    def initialize_board(self, size):
        import random
        from random import shuffle

        array = list()
        num_of_unique_cards = (self.size**2) // 2
        nums_1 = random.sample(range(1, num_of_unique_cards + 1),
                               num_of_unique_cards)
        nums_2 = random.sample(range(1, num_of_unique_cards + 1),
                               num_of_unique_cards)
        nums_array = nums_1 + nums_2
        shuffle(nums_array)
        count = 0

        for i in range(self.size):
            array.append(list())

            for j in range(self.size):
                array[i].append(Card(nums_array[count]))
                count += 1

        return array
Example #58
0
    def freshdeck(self):
        '''
        Creates a fresh deck of 52 cards
        '''
        cardface = ['2','3','4','5','6','7','8','9','10','J','Q','K','A']
        cardvalues = [2,3,4,5,6,7,8,9,10,10,10,10,1]
        cardsuits = ['S','C','D','H']

        cardfaceandvalues = [(cardface[i],cardvalues[i]) for i in range(len(cardface))]

        self.deck = []

        # insert a Card object for each suit,face,value combination into the deck
        
        for suit in cardsuits: 
            for face, value in cardfaceandvalues:
                self.deck.append(Card(suit,face,value))
            #for face in cardface: 
            #    for value in cardvalues:

        # shuffle the deck
        self.shuffle()
Example #59
0
def CatchGlobalArguments(options):

    global globalArgs

    globalArgs['InputRootFileName'] = options.inFileName  #str(sys.argv[1])
    globalArgs['OutputRootFileName'] = options.outFileName  #str(sys.argv[2])
    globalArgs['CardName'] = options.cardName  #str(sys.argv[3])
    globalArgs['Seed'] = int(options.seedNumber)  #str(sys.argv[4])
    globalArgs['Card'] = Card(globalArgs['CardName'])

    card = globalArgs['Card']
    globalArgs['ResolSS'] = ROOT.TF1('resol_ss', card.Get('ResolSS'), 0,
                                     100000)
    globalArgs['ResolSS'].SetParameters(
        array('d', [float(i) for i in card.Get('ResolPss').split(',')]))
    globalArgs['ResolMS'] = ROOT.TF1('resol_ms', card.Get('ResolMS'), 0,
                                     100000)
    globalArgs['ResolMS'].SetParameters(
        array('d', [float(i) for i in card.Get('ResolPms').split(',')]))
    globalArgs['ResolScale'] = float(card.Get('ResolScale'))

    globalArgs['Random'] = ROOT.TRandom3(int(globalArgs['Seed']))
Example #60
0
    def add_card(self, card: Card):
        """
        Adds the given card to the current hand and recalculates the possible scores
        given this new addition.

        :param card: a Card from a standard deck (e.g. ace)
        """
        self.cards.append(card)  # maintain the card for future reference
        self.possible_scores.clear()  # clear past scores
        leaves = self.hands.get_leaves() # get the most recent scores at play
        has_non_bust = False
        for leaf in leaves:
            for i, val in enumerate(card.get_values()):  # go through each possible value of this card
                possible_score = leaf.val + val
                # each branch of the BinaryTree is a possible value of the current hand
                if i == 0:
                    leaf.left = BinaryTreeNode(possible_score)
                else:
                    leaf.right = BinaryTreeNode(possible_score)
                has_non_bust = has_non_bust or possible_score <= 21  # bust is greater than 21
                self.possible_scores.append(possible_score)
            self.has_non_bust = has_non_bust