コード例 #1
0
class Game:
    def __init__(self, players=[]):
        self.players = players
        self.deck = Deck()
        self.deck.shuffle()

    def add_player(self, player):
        if not isinstance(player, Player):
            raise Exception("You have to be a player in order to join a game")

        self.players.append(player)
        return f"{player.name} has joined the game"

    def deal_players(self, num):
        for player in self.players:
            player.hand = self.deck.deal_hand(num)

    def clear_hand(self):
        for player in self.players:
            player.hand.clear()

        self.deck = Deck()
        self.deck.shuffle()

    def __repr__(self):
        return '\n'.join(f"Name: {player.name}" for player in self.players)
コード例 #2
0
 def __init__(self):
     self.top = None
     self.available = []
     self.deck = Deck()
     self.deck.shuffle()
     self.shuffle_count = 3
     self.discards = PyramidNode()
コード例 #3
0
class DeckTests(unittest.TestCase):
    def setUp(self):
        self.test_deck = Deck()

    def test_init(self):
        """new deck should have 52 cards"""
        self.assertEqual(len(self.test_deck.cards), 52)

    def test_repr(self):
        """deck should be printed as 'Deck of 52 cards'"""
        self.assertEqual(repr(self.test_deck), "Deck of 52 cards")

    def test_count(self):
        """count method should return len of cards attribute"""
        self.assertEqual(self.test_deck.count(), len(self.test_deck.cards))

    def test_deal_card(self):
        """deal 1 card from the deck. Deck has 51 cards now"""
        self.test_deck.deal_card()
        self.assertTrue(len(self.test_deck.cards) == 51)

    def test_deal_hand(self):
        """deal 5 cards from the deck. Deck has 47 cards now"""
        self.test_deck.deal_hand(5)
        self.assertTrue(len(self.test_deck.cards) == 47)
コード例 #4
0
    def deal_hand(self):
        deck = Deck()

        hand = ["J of spades", "Q of spades", "K of spades"]

        hand_delt = [str(card) for card in deck.deal_hand(3)]

        self.assertEqual(hand_delt, hand)
コード例 #5
0
    def test_shuffle(self):
        ordered_deck = Deck()
        deck = Deck()

        deck.shuffle()

        self.assertTrue(ordered_deck.cards[0] != deck.cards[0] or ordered_deck.cards[1] != deck.cards[1] 
            or ordered_deck.cards[2] != deck.cards[2])
コード例 #6
0
    def test_deal_card(self):
        deck = Deck()
        card = Card("spades", "K")
        
        self.assertEqual(str(deck.deal_card()), str(card))

        card.value = "Q"

        self.assertEqual(str(deck.deal_card()), str(card))
コード例 #7
0
ファイル: tests.py プロジェクト: sderuiter77/deck-of-cards
class DeckTest(unittest.TestCase):
    def setUp(self):
        self.deck1 = Deck()

    def test_deck_creation(self):
        self.assertEqual(len(self.deck1.cards), 52)

    def test_repr_deck(self):
        self.assertEqual(str(self.deck1), "Deck of 52 cards")

    def test_count(self):
        self.assertEqual(self.deck1.count(), len(self.deck1.cards))

    def test_shuffle_keeps_cards(self):
        self.deck1.shuffle()
        self.assertEqual(len(self.deck1.cards), 52)

    def test_shuffle_error(self):
        self.deck1.cards.pop()
        with self.assertRaises(ValueError):
            self.deck1.shuffle()

    def test_deal_card(self):
        self.deck1.deal_card()
        self.assertEqual(len(self.deck1.cards), 51)

    def test_deal_hand(self):
        self.deck1.deal_hand(4)
        self.assertEqual(len(self.deck1.cards), 48)
コード例 #8
0
class DeckTests(unittest.TestCase):
    def setUp(self):
        self.deck = Deck()

    def test_init(self):
        """deck init should match 52"""
        self.assertTrue(isinstance(self.deck.cards, list))
        self.assertEqual(len(self.deck.cards), 52)

    def test_repr(self):
        """deck repr should match"""
        self.assertEqual(repr(self.deck), "Deck of 52 cards")

    def test_count(self):
        """deck count should work"""
        self.assertEqual(self.deck.count(), 52)
        self.deck.cards.pop()
        self.assertEqual(self.deck.count(), 51)
コード例 #9
0
    def test_shuffle_exception(self):
        deck = Deck()

        deck.deal_hand(3)

        with self.assertRaises(ValueError):
            deck.shuffle()
コード例 #10
0
    def test_count(self):
        deck = Deck()
        self.assertEqual(deck.count(), 52)

        deck.deal_card()

        self.assertEqual(deck.count(), 51)
コード例 #11
0
class DeckTests(unittest.TestCase):
    def setUp(self):
        self.deck = Deck()

    def test_number_of_card(self):
        self.assertEqual(self.deck.count(), 52)

    def test_values(self):
        suits = ["Hearts", "Diamonds", "Clubs", "Spades"]
        values = [
            "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"
        ]
        for card in self.deck.cards:
            self.assertIn(card.suit, suits)
            self.assertIn(card.value, values)

    def test_shuffle(self):
        self.assertNotEqual(self.deck.cards[0], self.deck.shuffle()[0])

    def test_deal_cards(self):
        self.assertEqual(len(self.deck.deal_hand(5)), 5)
        self.assertNotIn(self.deck.deal_hand(5), self.deck.cards)
コード例 #12
0
class TestDeck:
    @pytest.fixture
    def set_up_test_deck(self):
        self.deck = Deck()

    def test_init(self, set_up_test_deck):
        assert len(self.deck.cards) == 52
        assert isinstance(self.deck.cards, list)

    def test_repr(self, set_up_test_deck):
        assert repr(self.deck) == "Deck of 52 cards."

    def test_count(self, set_up_test_deck):
        assert self.deck.count() == 52
コード例 #13
0
ファイル: test_cards.py プロジェクト: SosoP93/Deck-of-Cards
class DeckTests(unittest.TestCase):
	def setUp(self):
		self.my_deck = Deck()

	def test_count(self):
		""" Should return number of cards in the deck"""
		self.assertEqual(self.my_deck.count(), 
			52)

	def test_shuffle(self):
		""" Cards in deck should be mixed up after shuffle"""
		temp = self.my_deck.cards[:]
		self.my_deck.shuffle()	
		self.assertNotEqual(self.my_deck.cards, temp)

	def test_deal_hand(self):
		""" Number of cards in deck should reflect number of cards dealt"""
		self.my_deck.deal_hand(5)
		self.assertEqual(self.my_deck.count(), 47)

	def test_deal_card(self):
		""" Deck count should only decrease by one"""
		self.my_deck.deal_card()
		self.assertEqual(self.my_deck.count(), 51)
コード例 #14
0
def main():
    deck = Deck(1).shuffle()

    dealer = Dealer('Dealer')
    bob = Player('Bob', 10000, 3)

    # test person class
    ace_of_hearts = Card('A', 'h', (1, 11))
    ace_of_diamonds = Card('A', 'd', (1, 11))
    king_of_hearts = Card('K', 'h', 10)
    bob.bet(500)
    bob.showMoney()
    bob.hit(dealer, deck)
    bob.hit(dealer, deck)
    bob.showMoney()
    bob.showHands()
    bob.split()
    bob.showHands()
    bob.showMoney()
    bob.dubbleDown(dealer, deck, 0)
    bob.hit(dealer, deck, 1)
    bob.showHands()
    bob.showMoney()
コード例 #15
0
class DeckTests(unittest.TestCase):
    def setUp(self):
        self.deck = Deck()

    def test_init(self):
        """decks should have a cards attribute that is an instance of a list and a count of 52"""
        self.assertTrue(isinstance(self.deck.cards, list))
        self.assertEqual(len(self.deck.cards), 52)

    def test_repr(self):
        """Deck should display 'Deck of 52' cards"""
        self.assertEqual(repr(self.deck), "Deck of 52 cards.")

    def test_count(self):
        """Should return a length of 52"""
        self.assertEqual(self.deck.count(), 52)
        self.deck.cards.pop()
        self.assertEqual(self.deck.count(), 51)

    def test_deal_sufficient_cards(self):
        """Test that deal deals the proper number of cards and the number of leftover cards is accurate"""
        cards = self.deck._deal(10)
        self.assertEqual(len(cards), 10)
        self.assertEqual(self.deck.count(), 42)

    def test_deal_insufficient_cards(self):
        """Test that deal cannot deal more cards than available and the number of leftover cards is 0"""
        cards = self.deck._deal(100)
        self.assertEqual(len(cards), 52)
        self.assertEqual(self.deck.count(), 0)

    def test_insufficient_shuffle(self):
        """Anything less than a full deck should return a ValueError"""
        self.deck._deal(1)
        with self.assertRaises(ValueError):
            self.deck.shuffle()

    def test_sufficient_shuffle(self):
        """Should shuffle the deck and """
        cards = self.deck.cards[:]
        self.deck.shuffle()
        self.assertNotEqual(cards, self.deck.cards)
        self.assertEqual(self.deck.count(), 52)
コード例 #16
0
class DeckTests(unittest.TestCase):
    def setUp(self):
        self.deck = Deck()

    def test_init(self):
        """decks should have a cards attribute, which is a list"""
        self.assertTrue(isinstance(self.deck.cards, list))
        self.assertEqual(len(self.deck.cards), 52)

    def test_repr(self):
        """repr should return a string of the form 'Deck of cars'"""
        self.assertEqual(repr(self.deck), "Deck of 52 cards.")

    def test_count(self):
        """count should return a count of the number of cards"""
        self.assertEqual(self.deck.count(), 52)
        self.deck.cards.pop()
        self.assertEqual(self.deck.count(), 51)

    def test_deal_sufficient_cards(self):
        """_deal should deal the number of cards specified"""
        cards = self.deck._deal(10)
        self.assertEqual(len(cards), 10)
        self.assertEqual(self.deck.count(), 42)

    def test_deal_insufficient_cards(self):
        """_deal should deal the number of cards left in the deck"""
        cards = self.deck._deal(100)
        self.assertEqual(len(cards), 52)
        self.assertEqual(self.deck.count(), 0)

    def test_deal_no_cards(self):
        """_deal should throw a ValueError if the deck has no cards"""
        self.deck._deal(self.deck.count())
        with self.assertRaises(ValueError):
            self.deck._deal(1)

    def test_deal_card(self):
        """deal_card should deal a single card from the deck"""
        card = self.deck.cards[-1]
        dealt_card = self.deck.deal_card()
        self.assertEqual(card, dealt_card)
        self.assertEqual(self.deck.count(), 51)

    def test_deal_hand(self):
        """deal_hand should deal the number of cards passed into it"""
        cards = self.deck.deal_hand(20)
        self.assertEqual(len(cards), 20)
        self.assertEqual(self.deck.count(), 32)

    def test_shuffle_full_deck(self):
        """shuffle should shuffle the deck if the deck is full"""
        cards = self.deck.cards[:]  # copy, that is pointing to different memory space
        self.deck.shuffle()
        self.assertNotEqual(cards, self.deck.cards)
        self.assertEqual(self.deck.count(), 52)

    def test_shuffle_not_full_deck(self):
        """shuffle should throw a VAlueError of the deck isinstance()"""
        self.deck._deal(1)
        with self.assertRaises(ValueError):
            self.deck.shuffle()
コード例 #17
0
ファイル: war.py プロジェクト: CBroaders12/Card-Games
        # print("%s takes the hand" % (player2.name))
        # print("-----------------")
        player2.hand.extend(cards_played)

    #Use a tie breaker if card values are the same
    else:
        tie_breaker(player1, player2, cards_played)


#Initialize the deck and the players

number_rounds = []
winners = []

for i in range(1000):
    deck = Deck()
    player1 = Player("Ann")
    player2 = Player("Conor")

    rounds, winner = war(player1, player2, deck)
    if winner:  #Exclude games that timed out
        number_rounds.append(rounds)
        winners.append(winner)

# for i in range(len(number_rounds)):
#     print("Game {0}: {1} in {2} rounds".format(i+1, winners[i], number_rounds[i]))
player1_wins = winners.count(player1.name)
player2_wins = winners.count(player2.name)

average_number_games = int(mean(number_rounds))
print("The average number of rounds for {0} games is {1}".format(
コード例 #18
0
class Pyramid:
    def __init__(self):
        self.top = None
        self.available = []
        self.deck = Deck()
        self.deck.shuffle()
        self.shuffle_count = 3
        self.discards = PyramidNode()

    def deal(self):
        return self.deck.deal()
    
    def draw(self):
        if self.deck.need_reshuffle():
            self.shuffle_count -= 1
        self.discards.card = self.deck.draw()

    def deal_board(self):
        self.top = PyramidNode(self.deck.deal())
        Q = Queue()
        Q.push(self.top)
        for _ in range(21):
            current = Q.pop()
            # adding to the left edge of pyramid
            if current.top_left == None:
                current.low_left = PyramidNode(self.deck.deal(), top_right=current)
                Q.push(current.low_left)
            # connecting to the left
            else:
                current.low_left = current.top_left.low_left.low_right
                current.low_left.top_right = current
            # adding to the right
            current.low_right = PyramidNode(self.deck.deal(), top_left=current)
            Q.push(current.low_right)
        # bottom row
        while Q.is_empty() == False:
            current = Q.pop()
            current.card.turn_face_up()
            self.available.append(current)
    
    def remove_card(self, node):
        if node == self.discards:
            self.deck.remove_discard()
            self.discards = PyramidNode(self.deck.get_discard())
        else:
            node.remove_card()
            self.available.remove(node)
            # check if card at top_left is free
            if node.top_left != None and node.top_left.low_left.card == "empty":
                self.available.append(node.top_left)
                node.top_left.card.turn_face_up()
            # check if card at top_right is free
            if node.top_right != None and node.top_right.low_right.card == "empty":
                self.available.append(node.top_right)
                node.top_right.card.turn_face_up()

    def __str__(self):
        if self.game_won():
            return "YOU'VE WON!"
        if self.game_lost():
            return "GAME OVER!"
        return_str = " " * 12
        Q = Queue()
        Q.push(self.top)  
        indent = 10
        while Q.is_empty() == False:
            current = Q.pop()
            if current.low_left != None:
                # adding child cards to queue
                if current.top_left == None:
                    Q.push(current.low_left)
                Q.push(current.low_right)
            return_str += str(current)
            # end of row
            if current.top_right == None:
                return_str += "\n" + (" " * indent)
                indent -= 2
        return return_str

    def search_board(self, in_val):
        for node in self.available:
            if in_val.upper() == str(node).strip():
                return node
    
    def get_discard(self):
        return str(self.discards).strip()
    
    def game_over(self):
        if self.game_lost() or self.game_won():
            return True
        return False

    def game_won(self):
        if self.top.card == "empty":
            return True
        return False

    # set game over conditions
    def game_lost(self):
        if self.shuffle_count == 0:
            return True
        return False
コード例 #19
0
def main():
    display.welcome()  #welcome note
    display.intro()  #intro about black jack

    Black_jack.get_players_number()  #input number of palyers

    players = []  #to store list of players
    print(
        '\nAll players should open their wallet accounts in casino to play this game'
    )
    for i in range(Black_jack.n):
        players.append(Black_jack())  #appending n objects to the players list
        players[i].status = "PLAY"  #assigning status as play
        print('\nPlayer', i + 1, ':')
        print('-' * 10)
        Wallet.open_account(players[i])  #to open account
    for i in range(Black_jack.n):
        Wallet.display(players[i])

    print('\nPlayers should enter your bet amount before playing:\n')
    for i in range(Black_jack.n):
        print('\n', players[i].name, ':')
        print('-' * 10)
        players[i].get_bet_amount()  #get bet amount for all players
        Wallet.withdraw(players[i], players[i].bet)  #withdraw bet amount

    print("\nPlayers' Wallet Details:")  #print wallet details
    print('-' * 25, end='')
    for i in range(Black_jack.n):
        Wallet.display(players[i])

#first two cards
    Black_jack.assign_dealer_cards()  #assign dealer cards
    for i in range(Black_jack.n):
        players[i].cards = list()  #creating list for players' cards
        for j in range(2):
            players[i].hit()  #assign cards for players

    print('Dealer is distributing the cards.....')
    display.pause()  #pause
    Black_jack.display_cards(players)

    for i in range(Black_jack.n):
        players[i].black_jackpot()  #check players who has natural
        if players[i].status == 'NATURAL':
            Black_jack.natural_indexes.append(
                i)  #store index of players who has natural

#check if insurance is possible(i.e,if there is a possibility for a natural for dealer
    Black_jack.check_for_insurance()
    if Black_jack.insure == True:  #if dealer has possibility for a natural
        for i in range(Black_jack.n):
            if i in Black_jack.natural_indexes:  #players with natural
                print(
                    players[i].name,
                    ',Congrajulations!!!You have a natural.Wait for the dealer to turn up his card'
                )
                players[i].status = 'END'  #change status to END
            else:  #players with no natural
                players[i].ask_for_insurance(
                )  #ask if players wish to insure themselves
                if players[i].status == 'INSURE':
                    Black_jack.insure_indexes.append(
                        i)  #store index of players who insured

#check if dealer has natural
    Black_jack.dealer_black_jackpot()
    #dealer with natural
    if Black_jack.natural == True:  #if dealer has natural
        Black_jack.dealer_cards[1] = Black_jack.card_2  #unhiding the card
        Black_jack.display_cards(
            players
        )  #display cards after unhiding dealer's card cuz game end once dealer has a natural
        for i in range(Black_jack.n):
            #players with natural
            if i in Black_jack.natural_indexes:  #players with natural ties with dealer since dealer also has natural
                print(
                    players[i].name,
                    ',since the dealer too has natural, you ties up with dealer'
                )
                print('Bet amount will be refunded')
                Wallet.deposit(players[i], players[i].bet)
        #players without natural
            else:  #players without natural
                if i in Black_jack.insure_indexes:  #non natural players with insurance will get insured bet
                    print(
                        players[i].name,
                        ",since the dealer has natural and you don't, you lost your bet amount"
                    )
                    print(
                        'But since you have insured yourself, you won your insured bet.The insured bet amount will be refunded soon!'
                    )
                    Wallet.deposit(players[i], players[i].bet / 2)
                else:  #non natural players without insurance
                    print(
                        players[i].name,
                        ",since the dealer has natural and you don't, you lost your bet amount"
                    )
                    print('You should have insured yourself!!!')
            display.pause()
        return None  #game ends

#dealer without natural but insure possible
    elif Black_jack.insure == True and Black_jack.natural == False:  #if dealer has no natural
        for i in range(Black_jack.n):
            if i in Black_jack.natural_indexes:  #natural players win 1.5 of the bet and ends the game
                print(players[i].name,
                      ",since the dealer don't have natural,you win the bet!")
                print(
                    'One and a half of your bet amount will be credited to your wallet account now'
                )
                Wallet.deposit(players[i], players[i].bet * 1.5)
            else:  #non natural players
                if i in Black_jack.insure_indexes:  #non natural insured players lose their insured bet
                    print(
                        players[i].name,
                        ",since the dealer don't have natural,you can continue your game"
                    )
                    print(
                        "Also since you have insured,you lose your insured bet"
                    )
                else:  #non natural non insured players continue their game
                    print(
                        players[i].name,
                        ",since the dealer don't have natural,you can continue your game"
                    )
            display.pause()

    if Black_jack.natural == False:  #if dealer has no insurance(no natural obviously)
        for i in range(Black_jack.n):
            if players[
                    i].status != 'END' and i in Black_jack.natural_indexes:  #natural players win naturally
                print(players[i].name,
                      ",since the dealer don't have natural,you win the bet!")
                print(
                    'One and a half of your bet amount will be credited to your wallet account now'
                )
                Wallet.deposit(players[i], players[i].bet * 1.5)
            else:  #non natural players should choose to double down or split or hit
                if players[i].check_double_down() == True:
                    players[i].ask_double_down(
                    )  #ask players who satisfy doubling conditions
                    if players[i].status == 'DD':
                        Black_jack.double_indexes.append(
                            i
                        )  #store index in a list of players who doubles their bet
                        players[i].double_down(
                        )  #process to do for double down
                        Black_jack.display_cards(players)
                elif players[i].check_split() == True:
                    players[i].ask_split(
                    )  #ask players who satisfy splitting conditions
                    if players[i].status == 'SPLIT':
                        Black_jack.split_indexes.append(
                            i)  #store index in a list of players who splits
                        players[i].split(players)  #process to do for split
#rest of the players(non splitted and non doubled players (satisfy condition but chose not to split or double), and regular players)
                if players[i].status != 'END' and players[i].status != 'STAY':
                    Black_jack.display_cards(players)
                    players[i].hit_till_stay(players)
                else:
                    continue
            display.pause()

#all players' turns ends
#now dealer's turn

    Black_jack.dealer_cards[1] = Black_jack.card_2  #unhiding
    print('Dealer Turns up his face-down card')
    display.pause()
    Black_jack.dealer_cards[1] = Black_jack.card_2
    Black_jack.display_cards(players)  #displays cards

    Black_jack.dealer_sum()  #to calc dealer's total
    while Black_jack.add < 17:  #dealer should hit until his total is atleast 17
        print("Dealer's total is less than 17...,")
        input('So now the dealer is forced to Hit,Press Enter to continue\n')
        Black_jack.dealer_cards.append(Deck.draw_card_random())  #dealer hits
        Black_jack.dealer_sum()
        Black_jack.display_cards(players)

    if Black_jack.add > 21:
        print('Dealer is busted')
        for i in range(Black_jack.n):
            if i in Black_jack.double_indexes and players[i].status == 'STAY':
                print(players[i].name,
                      'since you doubled your bet,you win twice of your bet!')
                print(
                    'Amount you won and your bet amounts will be credited to your wallet'
                )
                Wallet.deposit(players[i], 4 * players[i].bet)
            elif i in Black_jack.split_indexes:
                flag = 0
                if players[i].status == 'STAY':
                    flag += 1
                if players[i].status_split == 'STAY':
                    flag += 1
                if flag != 0:
                    print(players[i].name, ", you won", flag, 'hand(s)')
                    print('Amount you won will be credited to your wallet')
                    Wallet.deposit(players[i], 2 * flag * players[i].bet)
            elif players[i].status == 'STAY':
                print(players[i].name, ", you win")
                print(
                    'Your bet amounts and the amount you won will be credited to your wallet'
                )
                Wallet.deposit(players[i], players[i].bet * 2)
            display.pause()
        return None


#now check with dealer
    Black_jack.dealer_sum()  #calc total of dealer
    Black_jack.check_with_dealer(players)
コード例 #20
0
 def setup(self):
     self.deck = Deck()
コード例 #21
0
ファイル: black_jack.py プロジェクト: avinash-218/Black-Jack
 def hit(self):			#hit once
  self.cards.append(Deck.draw_card_random())
コード例 #22
0
class DeckTests(unittest.TestCase):

    # Always makes a new deck before the test cases are run
    def setUp(self):
        self.deck = Deck()

    # Checks to see that the Deck object is a list with 52 elements
    def test_init(self):
        """Decks should have a 'Cards' attribute, which is a list of values"""
        self.assertTrue(isinstance(self.deck.cards, list))
        self.assertTrue(len(self.deck.cards), 52)

    # Checks the representation of the Deck object
    def test_repr(self):
        """repr should return a string of the form 'Deck of COUNT cards.'"""
        self.assertEqual(repr(self.deck), "Deck of 52 cards")

    # Checks to make sure the count function returns the amount of cards in the deck
    def test_count(self):
        """Count should return a count of the number of cards in the deck"""
        self.assertEqual(self.deck.count(), 52)
        self.deck.cards.pop()
        self.assertEqual(self.deck.count(), 51)

    # Checks to make sure a specific amount of cards can be dealt
    def test_deal_sufficient_cards(self):
        """_deal should deal the number of cards specified"""
        cards = self.deck._deal(5)
        self.assertEqual(len(cards), 5)
        self.assertEqual(self.deck.count(), 47)

    # Checks to see that the maximum number of cards can be dealt
    def test_deal_insufficient_cards(self):
        """_deal should deal the number of cards left in the deck when there aren't enough to deal"""
        cards = self.deck._deal(65)
        self.assertEqual(len(cards), 52)
        self.assertEqual(self.deck.count(), 0)

    # Checks to see that no cards are dealt when specified
    def test_deal_no_cards(self):
        """_deal should throw a value error when the deck is empty"""
        self.deck._deal(self.deck.count())
        # The "with" statement checks for errors
        with self.assertRaises(ValueError):
            self.deck._deal(1)

    # Checks to see if a single card can be dealt from the deck
    def test_deal_card(self):
        """deal_card should deal a single card from the deck"""
        card = self.deck.cards[-1]
        dealt_card = self.deck.deal_cards()
        self.assertEqual(card, dealt_card)
        self.assertEqual(self.deck.count(), 51)

    # Checks to see if a hand can be dealt
    def test_deal_hand(self):
        """deal_hand should deal the number of cards passed in"""
        cards = self.deck.deal_hand(5)
        self.assertEqual(len(cards), 5)
        self.assertEqual(self.deck.count(), 47)

    # Checks to see if the deck can be shuffled
    def test_shuffle_deck(self):
        """shuffle should shuffle the deck if the deck is full"""
        cards = self.deck.cards[:]  # The [:] is a slice that makes a copy of the deck
        self.deck.shuffle()
        self.assertNotEqual(cards, self.deck.cards)
        self.assertEqual(self.deck.count(), 52)

    # Checks to make sure that a less-than-full deck cannot be shuffled
    def test_shuffle_not_full_deck(self):
        """shuffle should throw a ValueError if the deck isn't full"""
        self.deck._deal(1)
        with self.assertRaises(ValueError):
            self.deck.shuffle()
コード例 #23
0
 def test_deck_repr(self):
     self.assertEqual(str(Deck()), "Deck of 52 cards")
コード例 #24
0
 def setUp(self):
     self.test_deck = Deck()
コード例 #25
0
class DeckTests(unittest.TestCase):
    def setUp(self):
        self.deck = Deck()

    def test_unit(self):
        """decks should have a cards attribute, which is a list with 52 items"""
        self.assertTrue(isinstance(self.deck.cards, list))
        self.assertEqual(self.deck.cards, 52)

    def test_repr(self):
        """repr should return a string of the form 'Deck of 52 cards'"""
        self.assertEqual(self.deck, "Deck of 52 cards")

    def test_count(self):
        """count should a count of the number of cards in the deck"""
        self.assertEqual(self.deck.count(), 52)
        self.deck.cards.pop()
        self.assertEqual(self.deck.count(), 51)

    def test_deal_sufficient_cards(self):
        """_deal should deal the number of cards specified, if less cards return remaining cards"""
        cards = self.deck._deal(10)
        self.assertEqual(len(cards), 10)
        self.assertEqual(self.deck.count(), 42)

    def test_deal_insufficient_cards(self):
        """_deal should deal the remaining cards in the deck"""
        cards = self.deck._deal(100)
        self.assertEqual(len(cards), 52)
        self.assertEqual(self.deck.count(), 0)

    def test_deal_no_cards(self):
        """_deal should throw a ValueError if no cards in the deck"""
        self.deck._deal(self.deck.count())
        with self.assertRaises(ValueError):
            self.deck._deal(1)

    def test_deal_card(self):
        """deal_card should deal a single card from the deck"""
        card = self.deck.cards[-1]
        dealt_card = self.deck.deal_card()
        self.assertEqual(card, dealt_card)
        self.assertEqual(self.deck.count(), 51)

    def test_deal_hand(self):
        """deal_hand should deal the number of cards passed to fn"""
        cards = self.deck.deal_hand(20)
        self.assertEqual(len(cards), 20)
        self.assertEqual(self.deck.count(), 32)

    def test_shuffle_full_deck(self):
        """shuffle should only shuffle if the deck is full"""
        cards = self.deck.cards[:]
        self.deck.shuffle()
        self.assertNotEqual(cards, self.deck.cards)
        self.assertEqual(self.deck.count(), 52)

    def test_shuffle_not_full_deck(self):
        """shuffle should raise a ValueError if the deck is not full"""
        self.deck._deal(1)
        with self.assertRaises(ValueError):
            self.deck.shuffle()
コード例 #26
0
ファイル: black_jack.py プロジェクト: avinash-218/Black-Jack
 def assign_dealer_cards():                                             #assign cards for dealer
  Black_jack.dealer_cards.extend([Deck.draw_card_random(),'???'])       #one card hidden
  Black_jack.card_2=Deck.draw_card_random()                             #to assign the hidden card of dealer to card_2 attribute
コード例 #27
0
 def setUp(self):
     self.deck = Deck()
コード例 #28
0
from deck_of_cards import Deck
import pandas as pd

print("Let's play a game.")
print(
    "I have a standard deck of cards. You can draw as many cards as you like and I will add up all the numbers."
)
print(
    "After you draw your cards, I will draw the same number of cards and add up all my numbers."
)
print("Whoever has the highest total sum, wins!")
print("Type 'q' at any time to quit the game.\n")

while True:
    starting_deck = Deck.copy()
    number_of_cards = int(input('How many cards would you like to draw?'))

    if number_of_cards == 'q':
        break
    user_cards = starting_deck.sample(number_of_cards, replace=True)
    print("You drew:\n")

    for card in range(0, number_of_cards):
        print("The " + str(user_cards['Face'].values[card]) + " of " +
              str(user_cards['Suits'].values[card]))
    user_sum = user_cards['Rank'].sum()
    print('Your cards sum up to a total of ' + str(user_sum) + '.\n')
    print('My turn to draw.')
    remaining_cards = pd.merge(starting_deck, user_cards, how='outer')
    dealer_cards = remaining_cards.sample(number_of_cards, replace=True)
    print('I drew:')
コード例 #29
0
 def set_up_test_deck(self):
     self.deck = Deck()
コード例 #30
0
from deck_of_cards import Deck, Card, Player, Game

d1 = Deck()
d1.build_deck()
d1.shuffle()

p1 = Player("Hao")
p2 = Player("Hayoung")
p3 = Player("KG")

players = [p1, p2, p3]

game1 = Game(players, d1.deck)
game1.start_game()

while (game1.done == False):
    print(" i am in the while*****************")
    game1.play_turn()