def test_hittable_case4(self): self.testDealer.recieve_card(Card(CardFaceType.ACE, SuitType.CLUB)) self.testDealer.recieve_card(Card(CardFaceType.ACE, SuitType.SPADE)) self.testDealer.recieve_card(Card(CardFaceType.SEVEN, SuitType.HEART)) # draw cards, at least 2 aces self.assertFalse(self.testDealer.should_hit(True), "dealer should have stayed")
def test_hittable_case3(self): # draw some cards, face up with a value greater than 17 self.testDealer.recieve_card(Card(CardFaceType.KING, SuitType.CLUB)) self.testDealer.recieve_card(Card(CardFaceType.FIVE, SuitType.CLUB)) self.testDealer.recieve_card(Card(CardFaceType.FIVE, SuitType.HEART)) self.assertFalse(self.testDealer.should_hit(True), "dealer sould have stayed")
def test_card_has_a_value(): king_of_spades = Card('spade', 'K') queen_of_spades = Card('spade', 'Q') assert king_of_spades.value == 'K' assert queen_of_spades.value == 'Q'
def test_hittable_case1(self): # draw some cards , face up, value > 13 < 17 # assert on return of hittable status self.testDealer.recieve_card(Card(CardFaceType.KING, SuitType.CLUB)) self.testDealer.recieve_card(Card(CardFaceType.FIVE, SuitType.DIAMOND)) self.assertTrue(self.testDealer.should_hit(True), "dealer should have hit")
def test_downgrade_ace_on_bust(self): hand = Hand() hand.cards = [Card('Ace', 'Spades'), Card('5', 'Hearts')] hand.hit(Card('Jack', 'Diamonds')) is_hand_busted = hand.check_for_bust() self.assertFalse(is_hand_busted) self.assertEqual(hand.calculate_total(), 16)
def test_one_big_ace_hand(self): """Test generate summary for hand with one ace.""" hand = Hand() hand.cards = [Card('Ace', 'Spades'), Card('7', 'Clubs')] summary = hand.generate_hand_summary() self.assertEqual(summary, '[Ace of Spades, 7 of Clubs] for a total of 18 (8)')
def test_normal_hand(self): """Test generate summary for normal hand.""" hand = Hand() hand.cards = [Card('Queen', 'Spades'), Card('7', 'Clubs')] summary = hand.generate_hand_summary() self.assertEqual(summary, '[Queen of Spades, 7 of Clubs] for a total of 17')
def test_no_ace_alt_score(self): """Test generate summary for hand with one ace.""" hand = Hand() hand.cards = [Card('Ace', 'Spades'), Card('7', 'Clubs')] summary = hand.generate_hand_summary(show_ace_alt_score=False) self.assertEqual(summary, '[Ace of Spades, 7 of Clubs] for a total of 18')
def test_hand_value_all_aces(self): self.testPlayer.recieve_card(Card(CardFaceType.ACE, SuitType.CLUB)) self.testPlayer.recieve_card(Card(CardFaceType.ACE, SuitType.HEART)) self.testPlayer.recieve_card(Card(CardFaceType.ACE, SuitType.SPADE)) self.testPlayer.recieve_card(Card(CardFaceType.ACE, SuitType.CLUB)) self.assertEqual(self.testPlayer.get_hand_value(), 14, "failed case 1")
def test_hittable_case2(self): # draw some cards , face up, one ace, value > 13 < 17 # assert on return of hittable status self.testDealer.recieve_card(Card(CardFaceType.ACE, SuitType.CLUB)) self.testDealer.recieve_card(Card(CardFaceType.THREE, SuitType.HEART)) self.assertTrue(self.testDealer.should_hit(True), "dealer should have hit")
def test_card_has_valid_suite(): with pytest.raises(ValueError): Card('robotricks', 2) c = Card('spade', 2) assert c.suit == 'spade'
def test_two_ace_hand(self): """Test generate summary for hand with one ace.""" hand = Hand() hand.cards = [Card('Ace', 'Spades'), Card('Ace', 'Clubs')] hand.check_for_bust() # to downgrade one Ace to value=1 summary = hand.generate_hand_summary() self.assertEqual( summary, '[Ace of Spades, Ace of Clubs] for a total of 12 (2)')
def test_hand_value_face_and_ace(self): self.testPlayer.recieve_card(Card(CardFaceType.JACK, SuitType.CLUB)) self.testPlayer.recieve_card(Card(CardFaceType.ACE, SuitType.HEART)) self.assertEqual(len(self.testPlayer.get_hand()), 2, "mismatch on the number of cards") self.assertEqual(self.testPlayer.get_hand_value(), 21, "error this should be a winning hand")
def test_iter_deck(): deck = Deck() assert next(deck) == Card('spade', 2) next(deck) next(deck) assert next(deck) == Card('spade', 5)
def test_value( self ): #Tests my calc_val() method in my Player class. It calculates the value sum of the hand of the player player = Player("Mikkel") player.hand.append(Card("Hearts", "Ace", 11)) player.hand.append(Card("Hearts", "King", 10)) self.assertEqual( player.calc_val(), 21, "Total should be 21" ) #In this scenario it tests if the appended cards give a sum of 21 which they should do
def test_false_blackjack(self): """Test check_for_black() returns None for a hand with more than 2 cards.""" self.hand.cards = [ Card('10', 'Hearts'), Card('9', 'Clubs'), Card('2', 'Spades') ] is_blackjack = self.hand.check_for_blackjack() self.assertFalse(is_blackjack) self.assertEqual(self.hand.status, None)
def test_visable_value_case2(self): self.testDealer.recieve_card(Card(CardFaceType.EIGHT, SuitType.SPADE)) self.testDealer.recieve_card( Card(CardFaceType.ACE, SuitType.HEART, CardFaceState.DOWN)) visible_value = self.testDealer.get_visible_hand_value() self.assertEqual(visible_value, 8, "error on visible hand value") self.testDealer.show_card_faces() visible_value = self.testDealer.get_visible_hand_value() self.assertEqual(visible_value, 19, "error in visible hand value after turning cards")
def test_check_for_bust_positive(self): """Test check for bust.""" self.hand.cards = [ Card('10', 'Hearts'), Card('4', 'Clubs'), Card('King', 'Spades') ] is_bust = self.hand.check_for_bust() self.assertTrue(is_bust) self.assertEqual(self.hand.status, 'bust')
def test_calulate_total(self): """Test calculate total.""" self.hand.cards = [ Card('2', 'Hearts'), Card('3', 'Clubs'), Card('6', 'Diamonds'), Card('4', 'Spades'), Card('5', 'Hearts') ] self.assertEqual(self.hand.calculate_total(), 20)
def test_check_for_bust_negative(self): """Test check for bust.""" self.hand.cards = [ Card('10', 'Hearts'), Card('4', 'Clubs'), Card('6', 'Spades') ] is_bust = self.hand.check_for_bust() self.assertFalse(is_bust) self.assertEqual(self.hand.status, None)
def UImain(): used_cards = [] cards_showing = [] deck = [] for decks in range(1): for val in VALS: for suit in SUITS: deck.append(Card(suit, val)) random.shuffle(deck) blank_card = Card('Plastic', 'Blank') rand_index = 8 + random.randint(-4, 4) deck.insert(rand_index, blank_card) player1 = UIPlayer(200.0, deck, used_cards, cards_showing) dealer = Dealer(deck, used_cards, cards_showing) while player1.balence > 0: os.system('cls' if os.name == 'nt' else 'clear') print('Balence:', player1.balence) s = int(input('Place wager amount: ')) player1.set_wager(s) deal_cards([dealer, player1]) # UI player loop while (player1.status != Status.STAND): print_UI(dealer, player1) player1.move() while dealer.status != Status.STAND: print_UI(dealer, player1, dealer_move=True) dealer.move() time.sleep(1) print_UI(dealer, player1, dealer_move=True) dealer_hand_val = dealer.best_hand_val() p_hand_val = player1.best_hand_val() if p_hand_val > 21 or p_hand_val <= 0: print('You lose', player1.wager) player1.lose() elif player1.has_blackjack() and not dealer.has_blackjack(): print('You win', player1.wager) player1.win() elif not player1.has_blackjack() and dealer.has_blackjack(): print('You lose', player1.wager) player1.lose() elif p_hand_val > dealer_hand_val: print('You win', player1.wager) player1.win() elif p_hand_val < dealer_hand_val: print('You lose', player1.wager) player1.lose() input('\nhit any key to continue ') clear_table([dealer, player1])
def test_get_card_str(self): """ Test that get_card_str() returns the appropriate str representation of a card. Also test that it works with hidden cards. """ card = Card('Hearts', 'King', 10) self.assertEqual(card.get_card_str(), 'King of Hearts') card.hidden = True self.assertEqual(card.get_card_str(), '**')
def test_check_draw(self): #Testing if the game ends when there's a draw deck = Deck() player = Player("Mikkel") player.hand.append(Card("Hearts", "Ace", 11)) player.hand.append(Card("Spades", "Jack", 10)) dealer = Player("dealer") dealer.hand.append(Card("Clubs", "Ace", 11)) dealer.hand.append(Card("Diamonds", "Jack", 10)) bj = Blackjack(player, dealer, deck) bj.check_who_won() self.assertFalse(bj.game_running, "Game should be over since the game drawed")
def test_determine_winners(self): """ Test that the dealer hits at the appropriate times and that winning hands are appropriated updated as such. """ # setup deck deck = Deck() deck.create() deck.shuffle() # setup gambler, dealer & hands dealer = Dealer() dealer_hand = Hand() dealer.hands.append(dealer_hand) gambler = Gambler("Test") gambler_hand = Hand() gambler.hands.append(gambler_hand) players = [gambler, dealer] # must hit a soft 17 (A, 6) gambler_hand.final_value = 20 dealer_hand.cards.append(Card('Hearts', 'Ace', 1)) dealer_hand.cards.append(Card('Hearts', 'Six', 6)) bj.determine_winners(players, deck) self.assertTrue(len(dealer_hand.cards) > 2) # must hit on 16 or less (K, 6) self.reset_hand_attrs(dealer_hand) dealer_hand.cards.append(Card('Hearts', 'King', 10)) dealer_hand.cards.append(Card('Hearts', 'Six', 6)) bj.determine_winners(players, deck) self.assertTrue(len(dealer_hand.cards) > 2) # check dealer bust (K, 6, J) dealer_hand.cards.pop() dealer_hand.cards.append(Card('Hearts', 'Jack', 10)) bj.determine_winners(players, deck) self.assertTrue(dealer_hand.busted) self.assertTrue(gambler_hand.win) # check dealer stands on 17 (K, 7) self.reset_hand_attrs(dealer_hand) dealer_hand.cards.append(Card('Hearts', 'King', 10)) dealer_hand.cards.append(Card('Hearts', 'Seven', 7)) bj.determine_winners(players, deck) self.assertTrue(len(dealer_hand.cards) == 2) # gambler wins with 20 to dealer's 17 self.assertTrue(gambler_hand.win) # check dealer stands on soft 18 (Ace, 7) self.reset_hand_attrs(dealer_hand) dealer_hand.cards.append(Card('Hearts', 'Ace', 1)) dealer_hand.cards.append(Card('Hearts', 'Seven', 7)) bj.determine_winners(players, deck) self.assertTrue(len(dealer_hand.cards) == 2)
def test_card_has_a_score(): card = Card(9, "Clubs") assert card.get_score() == 9 card = Card("Q", "Clubs") assert card.get_score() == 10 card = Card("A", "Clubs") assert card.get_score() == 1
def test_check_dealer_win( self): #Testing if the game ends if the dealer wins deck = Deck() player = Player("Mikkel") player.hand.append(Card("Hearts", "Ace", 11)) player.hand.append(Card("Spades", 2, 2)) dealer = Player("dealer") dealer.hand.append(Card("Clubs", "Ace", 11)) dealer.hand.append(Card("Diamonds", 7, 7)) bj = Blackjack(player, dealer, deck) bj.check_who_won() self.assertFalse(bj.game_running, "Game should be over since the dealer won")
def test_ace_values( self ): #Checks if the calc_val() method correctly recalculates the sum of the Players hand if there are multiple aces in the Players hand player = Player("Mikkel") player.hand.append(Card("Hearts", "Ace", 11)) player.hand.append(Card("Diamonds", "Ace", 11)) self.assertEqual( player.calc_val(), 12, "If the player starts with 2 aces the value should be 12 and not 22" ) player.hand.append(Card("Spades", "Ace", 11)) self.assertEqual( player.calc_val(), 13, "Fails if the calc.val() doesn't correctly make the value 13")
def test_winner_dealerBlackJack(self): # dealer has blackjack self.testPlayer.recieve_card( Card(CardFaceType.SEVEN, SuitType.CLUB, CardFaceState.UP)) self.testPlayer.recieve_card( Card(CardFaceType.JACK, SuitType.HEART, CardFaceState.UP)) self.testDealer.recieve_card( Card(CardFaceType.KING, SuitType.DIAMOND, CardFaceState.UP)) self.testDealer.recieve_card( Card(CardFaceType.ACE, SuitType.SPADE, CardFaceState.UP)) self.winner = blackjack.determine_blackjack_winner( self.testPlayer, self.testDealer) self.assertIsInstance(self.winner, Dealer, "Dealer should have won")
def test_winner_player(self): #player has better hand < blackJack self.testPlayer.recieve_card( Card(CardFaceType.NINE, SuitType.CLUB, CardFaceState.UP)) self.testPlayer.recieve_card( Card(CardFaceType.EIGHT, SuitType.HEART, CardFaceState.UP)) self.testDealer.recieve_card( Card(CardFaceType.KING, SuitType.DIAMOND, CardFaceState.UP)) self.testDealer.recieve_card( Card(CardFaceType.THREE, SuitType.SPADE, CardFaceState.UP)) self.winner = blackjack.determine_blackjack_winner( self.testPlayer, self.testDealer) self.assertIsInstance(self.winner, Player, "Player should have won")
def test_Winnner_push(self): # both player and dealer have Ace and Face card self.testPlayer.recieve_card( Card(CardFaceType.ACE, SuitType.CLUB, CardFaceState.UP)) self.testPlayer.recieve_card( Card(CardFaceType.JACK, SuitType.HEART, CardFaceState.UP)) self.testDealer.recieve_card( Card(CardFaceType.KING, SuitType.DIAMOND, CardFaceState.UP)) self.testDealer.recieve_card( Card(CardFaceType.ACE, SuitType.SPADE, CardFaceState.UP)) self.winner = blackjack.determine_blackjack_winner( self.testPlayer, self.testDealer) self.assertTrue((self.winner is None), "there should be no winner here")
class card_getRankTest(unittest.TestCase): def setUp(self): """Call before every test case.""" self.card = Card("C", "A") def testGetSuit(self): assert self.card.get_rank() == "A", 'Card.get_rank() does not provide the right return value'
class card_strTest(unittest.TestCase): def setUp(self): """Call before every test case.""" self.card = Card("C", "A") def testStr(self): assert self.card.__str__() == "CA", 'Card.__str__() does not provide the right return value'
def test_get_value(self): """A test which checks the get_value method of the Card class.""" # Test to make sure that all of the faces and values match up faces = [ "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace", ] values = [ [2,], [3,], [4,], [5,], [6,], [7,], [8,], [9,], [10,], [10,], [10,], [10,], [1, 11,], ] for index in range(len(faces)): face = faces[index] card = Card("Clubs", face) found_value = card.get_value() expected_value = values[index] self.assertEqual(found_value, expected_value, msg="The value for face " + face + \ " was incorrectly returned as " + str(found_value[0]) + " when it should have" + \ " been " + str(expected_value[0]) + ".")
class card_drawTest(unittest.TestCase): def setUp(self): """Call before every test case.""" self.card = Card("C", "A") def tearDown(self): """Call after every test case.""" def testDrawInit(self): testCanvas = Canvas() pos = [1,1] assert self.card.draw(testCanvas, pos) == dummy(self), 'BlackJackGame.draw() does not provide the right return value'
def setUp(self): """Call before every test case.""" self.card = Card("C", "A")
def run(self): server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.bind((socket.gethostname(), SERVER_PORT)) server_socket.listen() server_socket.settimeout(1.5) while len(self.clients) == 0 or len(self.not_ready) > 0: try: client = Client(*server_socket.accept()) self.not_ready[client.uuid] = True self.clients.append(client) client_thread = Thread(target=self.client_thread_wait_for_ready, args=(client,), daemon=True) client_thread.start() # logging -- when a connection happens print("New connection: " + str(len(self.clients))) except socket.timeout: continue # minor cleanup server_socket.close() # play the blackjack game: consecutive_passes = 0 players_at_or_above_max = 0 # send message to all players announcing start self.broadcast("The game is beginning.\n") # main game loop: infinite cycle through clients, until exit conditions are met for player in cycle(self.clients): # ask client for move player.client_socket.send(b"TAKE or PASS") # receive move: if TAKE, give player a card and update players min score data = player.client_socket.recv(128) data = data.decode("utf-8") # move will be broadcast to all players move = "Player " + str(player.uuid) + " has: " if data == "PASS": consecutive_passes += 1 move += " opted to PASS.\n" elif data == "TAKE": card = Card.random() player.cards.append(card) player.client_socket.send( bytes("Your card: " + str(card) + ".\n", "utf-8") ) move += " TAKEN the card " + str(card) + "\n" # check if this player's min sum of card values is at or above 21 if Card.min_value(player.cards) >= 21: players_at_or_above_max += 1 # reset consecutive passes consecutive_passes = 0 else: # invalid request pass # send move broadcast self.broadcast(move, dont_send_to=player) # check for game over conditions if consecutive_passes == len(self.clients) or players_at_or_above_max == len(self.clients): break # decide winner and send to all clients # todo message = "It's over! " if consecutive_passes == len(self.clients): message = "Game is over because each player has passed consecutively.\n" # todo get winner elif players_at_or_above_max == len(self.clients): message = "Game is over because every player is either at or above 21 score.\n" # todo get winners # send final message for player in self.clients: player.client_socket.send(bytes(message, "utf-8")) # cleanup the server for player in self.clients: player.client_socket.close()
def create_card_test(self): c1 = Card("ten", "clubs") self.assertEqual(("ten", "clubs"), c1.__repr__())