def main(): print('---Blackjack 0.5---\n') table = Table(doubleOn=[9, 10, 11]) dealer = Dealer('Dealer', 1000000) dealer.sit(table) # # Deck Stacking: # dealer._shoe.append(Card('ace', 'spades')) dealer._shoe.append(Card('ace', 'hearts')) # # # numberOfPlayers = get_integer_between(1, 7, 'How many players?') for number in range(1, numberOfPlayers + 1): name = get_string(f"What is player {number}'s name?") player = HumanPlayer(name, 100) player.sit(table) dealer.take_bets() while table.has_players(): dealer.deal() dealer.offer_insurance() dealer.play_hands() dealer.play_own_hand() dealer.payout_hands() dealer.take_bets() print('\n---There are no more players. Game Over.---')
class TestPot(unittest.TestCase): """Do we have a fully functional pot object?""" def setUp(self): self.p0 = Player('p0', 100) self.p1 = Player('p1', 100) self.p2 = Player('p2', 100) self.p3 = Player('p3', 100) self.p4 = Player('p4', 100) self.p5 = Player('p5', 100) self.s0 = Seat('s0') self.s1 = Seat('s1') self.s2 = Seat('s2') self.s3 = Seat('s3') self.s4 = Seat('s4') self.s5 = Seat('s5') players = [self.p0, self.p1, self.p2, self.p3, self.p4, self.p5] seats = [self.s0, self.s1, self.s2, self.s3, self.s4, self.s5] self.table = Table(seats, 5, 10, 0) self.dealer = Dealer(self.table) self.table.dealer = self.dealer player = 0 for seat in seats: seat.player = players[player] seat.player.seat = seat seat.active = True seat.player.table = self.table player += 1 self.table.init_hand() def test_who_is_first_pre_flop(self): """Do we make the proper player act first pre-flop??""" self.dealer.deal_hole() self.assertTrue(self.table.seats[self.table.under_the_gun].player.action) def test_who_is_first_post_flop(self): """Do we make the proper player act first post-flop""" self.dealer.deal_hole() self.table.seats[self.table.under_the_gun].player.action = False self.dealer.deal() self.assertTrue(self.table.seats[self.table.first].player.action) def test_bet(self): """Can each player bet 50?""" self.dealer.deal_hole() i = 0 while i < 6: i += 1 for seat in self.table.pots[-1].seats: print(seat.player.name, seat.player.equity, seat.player.action) if seat.player.action: seat.player.bet(50) self.table.pots[-1].betting_round() break print(seat.player.name, seat.player.equity, seat.player.action) print(self.table.pots[-1].pot)
class Blackjack: def play(self): self.dealer = Dealer() self.player = Player() while True: self.play_round() def __str__(self): return str(self.dealer) + os.linesep + str(self.player) def play_round(self): self.dealer.deal(self.player) while True: print(self) if not self.act(): print(self) break self.dealer.collect(self.player.dispose()) input() def act(self): action = input("action: ") if action == constant.HIT: self.dealer.hit(self.player) elif action == constant.STAND: return False
def test_deals_to_self(self): dealer = Dealer('test', 100) dealer.add_hand = MagicMock() dealer.deal() # Expect add_hand to have been called with a hand # that has two cards hand = dealer.add_hand.call_args[0][0] self.assertEqual(len(hand), 2)
def test_doesnt_deal_when_0_bet(self): dealer = Dealer('test', 100) player = self.deal_in_player(dealer) player.bet_or_leave = MagicMock(return_value=0) dealer.take_bets() player.add_hand = MagicMock() dealer.deal() player.add_hand.assert_not_called()
def test_deal(self): """test the deal method""" player = Player('Foo') card = Card(Rank(0, 'x'), Suit('y')) dealer = Dealer([card], [player], 1) self.assertEqual(0, len(player.cards)) dealer.deal() self.assertEqual(1, len(player.cards)) self.assertEqual(card, player.cards[0])
def main(): dealer = Dealer('Dealer', 1000) for number in range(2): player = HumanPlayer(f'Player {number}', 100) dealer.deal_in(player) dealer.take_bets() while dealer.has_players(): dealer.deal() #dealer.offer_insurance() #dealer.offer_surrender() dealer.resolve_hands() dealer.payout() dealer.take_bets()
def test_deals_when_nonzero_bet(self): dealer = Dealer('test', 100) player = self.deal_in_player(dealer) player.bet_or_leave = MagicMock(return_value=50) dealer.take_bets() player.rake_out = MagicMock() player.add_hand = MagicMock() dealer.deal() player.rake_out.assert_called() player.add_hand.assert_called_once() # Expect add_hand to have been called with a hand # that has two cards hand = player.add_hand.call_args[0][0] self.assertEqual(len(hand), 2)
class TestDealer(unittest.TestCase): def setUp(self): self.dealer = Dealer() self.player = Player() def test_initial_deck_size(self): self.assertEqual(self.dealer.deck.size, 104) def test_cut_number(self): self.assertTrue(self.dealer.cut_num >= 12 and self.dealer.cut_num <= 42) def test_get_deck(self): self.assertEqual(self.dealer.get_deck(), self.dealer.deck) def test_get_hand(self): card_1 = Card('Ace', 'Spades') card_2 = Card('2', 'Diamonds') temp_hand = [card_1, card_2] test_hand = Stack(cards=temp_hand) self.dealer.hand = test_hand self.assertEqual(self.dealer.get_hand(), test_hand) def test_initial_deal(self): self.dealer.initial_deal(self.player) self.assertEqual(self.dealer.deck.size, 100) self.assertEqual(self.dealer.hand.size, 2) self.assertEqual(self.player.hand.size, 2) def test_deal(self): # dealt cards are actually passed as a Stack card = self.dealer.deal() self.assertTrue(type(card) is Stack) self.assertEqual(card.size, 1) self.assertEqual(self.dealer.deck.size, 103) def test_deal_dealer(self): self.dealer.deal_dealer() self.assertEqual(self.dealer.hand.size, 1) self.assertEqual(self.dealer.deck.size, 103) self.dealer.deal_dealer() self.assertEqual(self.dealer.hand.size, 2) self.assertEqual(self.dealer.deck.size, 102) self.dealer.deal_dealer() self.assertEqual(self.dealer.hand.size, 3) self.assertEqual(self.dealer.deck.size, 101) def test_reshuffle(self): self.dealer.deal_dealer() self.dealer.deal_dealer() self.dealer.deal_dealer() self.dealer.deal_dealer() self.dealer.deal_dealer() self.assertEqual(self.dealer.deck.size, 99) self.dealer.reshuffle() self.assertEqual(self.dealer.deck.size, 104)
def main(argv): try: opts, args = getopt.getopt(argv, "ha:d:g:", ["attacker=", "defender=", "game="]) except getopt.GetoptError: print('big2.py -a <attacker> -d <defender> -g <game>') sys.exit(2) Tom = Jack = game = None for opt, arg in opts: if opt == '-h': print('big2.py -a <attacker> -d <defender> -g <game>') sys.exit() elif opt in ("-a", "--attacker"): Tom = choosePlayer(arg) elif opt in ("-d", "--defender"): Jack = choosePlayer(arg) elif opt in ("-g", "--game"): game = int(arg) if not Tom or not Jack or not game: print('big2.py -a <attacker> -d <defender> -g <game>') sys.exit(3) Annie = Dealer("Version1") cards = Annie.deal(game) Tom.newGame(copy.copy(cards[0]), copy.copy(cards[1]), Jack.teamName()) Jack.newGame(copy.copy(cards[1]), copy.copy(cards[0]), Tom.teamName()) print("{:<80}".format(Tom.teamName())) print("{:<80}".format(str(cards[0]))) print("{:>80}".format(Jack.teamName())) print("{:>80}".format(str(cards[1]))) print("-" * 80) #Tom.play(['A', 'J', '2', '3', '3', '5', '10'], [7, 7, 8], [8])) t, player, score = [], None, None while not score: # Tom 先手,然后轮流出牌 player = Tom if not player or player is Jack else Jack t = player.play(t) score, t = Annie.check(t) output = "{:<80}" if player is Tom else "{:>80}" print(output.format(str(t) if t else "pass")) player.ack(t) # player获知Annie的裁定 else: print("{} is the winner! score={}".format(player.teamName(), score))
class TestAnalyzer(unittest.TestCase): def setUp(self): self.p0 = Player('p0', 100) self.p1 = Player('p1', 100) self.p2 = Player('p2', 100) self.p3 = Player('p3', 100) self.p4 = Player('p4', 100) self.p5 = Player('p5', 100) self.s0 = Seat('s0') self.s1 = Seat('s1') self.s2 = Seat('s2') self.s3 = Seat('s3') self.s4 = Seat('s4') self.s5 = Seat('s5') players = [self.p0, self.p1, self.p2, self.p3, self.p4, self.p5] seats = [self.s0, self.s1, self.s2, self.s3, self.s4, self.s5] self.table = Table(seats, 5, 10, 0) self.dealer = Dealer(self.table) self.table.dealer = self.dealer player = 0 for seat in seats: seat.player = players[player] seat.player.seat = seat seat.active = True seat.player.table = self.table player += 1 self.table.init_hand() self.dealer.deal() self.dealer.deal() self.dealer.deal() self.analyzer = Analyzer(self.table) def test_award(self): """can we award a single winner the entire pot?""" players = [self.p2] self.table.pots[0].pot = 100 self.p2.stack = 90 self.analyzer._award(players) self.assertEqual(self.p2.stack, 190) def test_award_multiple(self): """Can we pay out evenly to multiple winners?""" players = [self.p2, self.p3] self.table.pots[0].pot = 100 self.p2.stack = 50 self.p3.stack = 50 self.analyzer._award(players) self.assertEqual(self.p2.stack, 100) self.assertEqual(self.p3.stack, 100) def test_award_indivisible(self): """Can we properly pay pots that don't divide evenly?""" players = [self.p2, self.p3] self.table.first = 1 self.table.pots[0].pot = 105 self.p2.stack = 50 self.p3.stack = 50 self.analyzer._award(players) self.assertEqual(self.p2.stack, 105) self.assertEqual(self.p3.stack, 100) def test_compare(self): """can we determine the winning hand""" players = self.analyzer._setup() self.p0.hand = [0, 14, 12, 11, 10, 8] self.p1.hand = [1, 14, 12, 11, 8] self.p2.hand = [7, 8, 14] self.p3.hand = [7, 10, 2] self.p4.hand = [0] self.p5.hand = [0] result = self.analyzer._compare(players) expected = [self.p3] self.assertEqual(expected, result) def test_compare_multiple(self): """if there are multiple winners do we return all of them?""" players = self.analyzer._setup() self.p0.hand = [0, 14, 12, 11, 10, 8] self.p1.hand = [1, 14, 12, 11, 8] self.p2.hand = [7, 10, 2] self.p3.hand = [7, 10, 2] self.p4.hand = [0] self.p5.hand = [0] result = self.analyzer._compare(players) expected = [self.p2, self.p3] self.assertEqual(expected, result) def test_hi_card(self): """can we identify a hi card hand?""" players = self.analyzer._setup() self.p4.hole[0].value = 12 self.p4.hole[1].value = 11 self.p4.hole[2].value = 9 self.p4.hole[3].value = 14 self.p4.hole[4].value = 13 self.p4.hole[5].value = 3 self.p4.hole[6].value = 2 players = self.analyzer._order(players) self.analyzer._matching(players) expected = [0, 14, 13, 12, 11, 9] self.assertEqual(self.p4.hand, expected) def test_matching_hands(self): """can we find matching number hands eg. pairs through quads??""" players = self.analyzer._setup() # quads self.p0.hole[0].value = 14 self.p0.hole[1].value = 14 # boat self.p1.hole[0].value = 14 self.p1.hole[1].value = 13 # trips self.p2.hole[0].value = 14 self.p2.hole[1].value = 12 # two pair self.p3.hole[0].value = 12 self.p3.hole[1].value = 12 # pair self.p4.hole[0].value = 12 self.p4.hole[1].value = 11 self.p4.hole[2].value = 14 self.p4.hole[3].value = 14 self.p4.hole[4].value = 13 self.p4.hole[5].value = 3 self.p4.hole[6].value = 2 players = self.analyzer._order(players) self.analyzer._matching(players) # Do we have 4 A's with a K kicker? self.assertEqual(self.p0.hand, [7, 14, 13]) # Do we have a boat A's full of K's? self.assertEqual(self.p1.hand, [6, 14, 13]) # Do we have trip A's with K & Q kickers? self.assertEqual(self.p2.hand, [3, 14, 13, 12]) # Do we have 2 pair A's & Q's with a K kicker? self.assertEqual(self.p3.hand, [2, 14, 12, 13]) # Do we have a pair of A's with K, Q, J kickers? self.assertEqual(self.p4.hand, [1, 14, 13, 12, 11]) def test_straight(self ): """can we find the highest straight in a hand""" players = self.analyzer._setup() #p0 has a 6 high straight self.p0.hole[0].value = 8 self.p0.hole[1].value = 6 self.p0.hole[2].value = 5 self.p0.hole[3].value = 4 self.p0.hole[4].value = 3 self.p0.hole[5].value = 13 self.p0.hole[6].value = 2 #poor p1 hit the wheel self.p1.hole[0].value = 14 self.p1.hole[1].value = 11 self.analyzer._order(players) self.analyzer._straight(self.p0) self.analyzer._straight(self.p1) expected_0 = [4, 6] expected_1 = [4, 5] self.assertEqual(self.p0.hand, expected_0) self.assertEqual(self.p1.hand, expected_1) def test_flush(self): """Can we find a flush in the players' hands""" players = self.analyzer._setup() # a flush self.p0.hole[0].suit = "d" self.p0.hole[0].value = 2 self.p0.hole[1].suit = "d" self.p0.hole[1].value = 2 self.p0.hole[2].suit = "d" self.p0.hole[3].suit = "d" self.p0.hole[4].suit = "d" self.p0.hole[5].suit = "d" self.p0.hole[5].value = 5 self.p0.hole[6].suit = "d" self.p0.hole[6].value = 4 self.p1.hole[0].suit = "d" self.p1.hole[1].suit = "d" self.p1.hole[0].value = 14 self.p1.hole[1].value = 13 self.p1.hole[2].value = 12 self.p1.hole[3].value = 11 self.p1.hole[4].value = 10 players = self.analyzer._order(players) self.analyzer._flush(players) self.assertTrue(self.p0.hand) self.assertEqual(self.p0.hand[0], 5) self.assertEqual(len(self.p0.hand), 6) # p1 should be a straight flush expected = [8, 14] self.assertEqual(self.p1.hand, expected) def test_order(self): """Can we order the hands in a proper order, left to right""" players = self.analyzer._setup() players = self.analyzer._order(players) for player in players: for i in range(6): v1 = player.hole[i].value v2 = player.hole[i + 1].value self.assertTrue(v2 <= v1) def test_seven_cards(self): """Can we get a list of players in the hand with 7 cards in the hand""" players = self.analyzer._setup() for player in players: self.assertTrue(len(player.hole) == 7)
class GameManager(object): STARTING_CHIPS = 100 def __init__(self): self.dealer = Dealer() self.quit = False self.user = Player() def setup(self): print("\n") print("WELCOME TO BLACKJACK!\n") print("You will start with 100 chips") print("Blackjack pays out 3:2.") print("Double Down and Split bets can be less than or equal " +\ "to original bet.") print("Only one card will be dealt to Double Down and Split hands.") print("No insurance will be offered.") print("Have Fun!\n\n\n") def ask_to_quit(self): """Check if the user wants to quit the game""" if self.user.get_chips() == 0: print("Game Over, you have 0 chips remaining.") self.quit = True return True user_input = input("Enter 'C' to continue or 'Q' to quit.\n") while user_input != 'C' and user_input != 'Q': user_input = input("Invalid input, enter 'C' to coninue " +\ "or 'Q' to quit.\n") if user_input == 'Q': self.quit = True return True return False def get_bet(self): """Get a bet from the user through the command line""" user_input = input("Enter integer ammount to bet.\n") while True: try: bet = int(user_input) assert (bet > 0 and bet <= self.user.get_chips()) return bet except ValueError: print("Bet must be an Integer.") except AssertionError: print("Valid bets are greater than 0 and less than {} chips."\ .format(self.user.get_chips())) user_input = input("Enter integer ammount to bet.\n") def play_hand(self, bet): """Logic for playing a hand of Blackjack is contained in this mehod""" # Deal two cards to the user and the dealer self.dealer.initial_deal(self.user) self.display_table(self.user.get_hand(), bet, self.user.get_chips()) # Check if either hand is a blackjack and payout accordingly dealer_bj = check_for_blackjack(self.dealer.get_hand()) user_bj = check_for_blackjack(self.user.get_hand()) if dealer_bj and user_bj: print("Push") print("Current chip total is {}.".format(self.user.get_chips())) return elif dealer_bj: self.user.take_chips(bet) self.display_table(self.user.get_hand(), bet, self.user.get_chips(), hide_dealer=False) print("Dealer has Blackjack. You lose.") print("Current chip total is {}.".format(self.user.get_chips())) return elif user_bj: payout = bet * 1.5 self.user.add_chips(math.ceil(payout)) print("Black Jack!") print("Current chip total is {}.".format(self.user.get_chips())) return # Ask the user to Hit, Stand, Double Down, or Split choice = self.user_choice(bet) if choice == 'H': while choice != 'S': self.user.add_cards(self.dealer.deal()) self.display_table(self.user.get_hand(), bet, self.user.get_chips()) if check_for_bust(self.user.get_hand()): self.user.take_chips(bet) print("BUST") print("Current chip total is {}."\ .format(self.user.get_chips())) return choice = input("'H' to hit, 'S' to stand.\n") while choice != 'H' and choice != 'S': choice = input("Invalid input, please select 'H' to hit, "\ "'S' to stand.\n") elif choice == 'D': double_down = self.get_bet() while double_down > bet or double_down > \ self.user.get_chips() - bet: if double_down > self.user.get_chips() - bet: print("Double down bet can't be greater than " +\ "your remiaining chips.") else: print("Double down bet must be less than or equal " +\ "to original bet.") double_down = self.get_bet() bet += double_down self.user.add_cards(self.dealer.deal()) if check_for_bust(self.user.get_hand()): self.display_table(self.user.get_hand(), bet, self.user.get_chips(), hide_dealer=False) self.user.take_chips(bet) print("BUST") print("Current chip total is {}.".format( self.user.get_chips())) return elif choice == 'P': split_bet = self.get_bet() while split_bet > bet or split_bet > self.user.get_chips() - bet: if split_bet > self.user.get_chips() - bet: print("Split bet can't be greater than your " +\ "remiaining chips.") else: print("Split bet must be less than or equal to " +\ "original bet.") split_bet = self.get_bet() bet_total = bet + split_bet hand_1 = Stack() hand_2 = Stack() hand_1 += self.user.get_hand().deal(1) hand_1 += self.dealer.deal() hand_2 += self.user.get_hand().deal(1) hand_2 += self.dealer.deal() if get_hand_total(self.dealer.get_hand()) < 17: self.display_table(hand_1, bet_total, self.user.get_chips()) self.display_table(hand_2, bet_total, self.user.get_chips()) else: self.display_table(hand_1, bet_total, self.user.get_chips(), hide_dealer=False) self.display_table(hand_2, bet_total, self.user.get_chips(), hide_dealer=False) while get_hand_total(self.dealer.get_hand()) < 17: self.dealer.deal_dealer() self.display_table(hand_1, bet_total, self.user.get_chips(), hide_dealer=False) self.display_table(hand_2, bet_total, self.user.get_chips(), hide_dealer=False) if check_for_bust(self.dealer.get_hand()): self.user.add_chips(bet) self.user.add_chips(split_bet) print("DEALER BUSTS, YOU WIN!") print("Current chip total is {}.".format( self.user.get_chips())) return self.compare_hands(bet, hand_1) self.compare_hands(split_bet, hand_2) return if choice != 'P': self.display_table(self.user.get_hand(), bet, self.user.get_chips(), hide_dealer=False) while get_hand_total(self.dealer.get_hand()) < 17: self.dealer.deal_dealer() self.display_table(self.user.get_hand(), bet, self.user.get_chips(), hide_dealer=False) if check_for_bust(self.dealer.get_hand()): self.user.add_chips(bet) print("DEALER BUSTS, YOU WIN!") print("Current chip total is {}.".format(self.user.get_chips())) return # If neither hand has busted, check which hand is higher and settle bet self.compare_hands(bet, self.user.get_hand()) def clean_up_hand(self): """Clean up after hand is over""" self.dealer.empty_hand() self.user.empty_hand() if len(self.dealer.deck) < self.dealer.cut_num: self.dealer.reshuffle() def compare_hands(self, bet, user_hand): """Compare hands to see which hand wins. An assumption this method makes is that both hands are under 21.""" dealer_total = get_hand_total(self.dealer.get_hand()) user_total = get_hand_total(user_hand) if dealer_total == user_total: print("Push") print("Current chip total is {}.".format(self.user.get_chips())) elif dealer_total > user_total: self.user.take_chips(bet) print("House wins") print("Current chip total is {}.".format(self.user.get_chips())) else: self.user.add_chips(bet) print("Winner!") print("Current chip total is {}.".format(self.user.get_chips())) def display_table(self, hand, bet, chips_left, hide_dealer=True): """Display the current state of the table""" dealer_cards = [] user_cards = [] print("#################################") print(" POT: {:<3} | CHIPS LEFT: {:<3}".format( bet, chips_left - bet)) print("---------------------------------") print(" DEALER HAND | PLAYER HAND ") for card in self.dealer.get_hand(): dealer_cards.append(self.card_to_print(card, hide_dealer)) hide_dealer = False for card in hand: user_cards.append(self.card_to_print(card)) difference = self.dealer.get_hand().size - hand.size if difference < 0: for i in range(difference * -1): dealer_cards.append(self.card_to_print(place_holder=True)) elif difference > 0: for i in range(difference): user_cards.append(self.card_to_print(place_holder=True)) for i in range(max(len(dealer_cards), len(user_cards))): for j in range(7): print("{} | {}".format(dealer_cards[i][j], user_cards[i][j])) def card_to_print(self, card=None, hide_dealer=False, place_holder=False): """Returs a printable representation of a playing card.""" lines = [] if place_holder: lines.append(' ') lines.append(' ') lines.append(' ') lines.append(' ') lines.append(' ') lines.append(' ') lines.append(' ') return lines suit = SUITS[card.suit] if card.value in VALUES: value = VALUES[card.value] else: value = card.value if hide_dealer: lines.append(' ┌───────┐ ') lines.append(' |*******| ') lines.append(' |*******| ') lines.append(' |*******| ') lines.append(' |*******| ') lines.append(' |*******| ') lines.append(' └───────┘ ') return lines else: suit = SUITS[card.suit] if card.value in VALUES: value = VALUES[card.value] else: value = card.value lines.append(' ┌───────┐ ') lines.append(' | {:<2} | '.format(value)) lines.append(' | | ') lines.append(' | {} | '.format(suit)) lines.append(' | | ') lines.append(' | {:>2} | '.format(value)) lines.append(' └───────┘ ') return lines def user_choice(self, bet): """Collect a choice from the user through the command line""" choice = '' while choice != 'H' and choice != 'S' and choice != 'D' \ and choice != 'P': choice = input("Please select 'H' to hit, 'S' to stand, 'D' " + \ "to double-down, or 'P' to split.\n") if choice == 'D' and self.user.get_chips() - bet == 0: choice = '' print("Invalid choice, you have no additional chips to bet.") if choice == 'P' and self.user.get_chips() - bet == 0: choice = '' print("Invalid choice, you have no additional chips to bet.") elif choice == 'P': user_hand = self.user.get_hand() card_list = [] for card in user_hand: card_list.append(card) if BJ_RANKS[card_list[0].value] != BJ_RANKS[ card_list[1].value]: print("Invalid choice, you must have a pair to split.") choice = '' return choice def run(self): """Run loop for the game manager""" self.setup() while not self.quit: if not self.ask_to_quit(): bet = self.get_bet() self.play_hand(bet) self.clean_up_hand() self.teardown() def teardown(self): """Preform necessary teardown at the end of the game.""" if self.user.chips >= 100: print("Congratulations you won {} dollars!".format( self.user.get_chips() - 100)) else: print("Better luck next time.")
def test_shuffles_if_necessary(self): dealer = Dealer('test', 100) dealer.shoe.should_shuffle = MagicMock(return_value=True) dealer.shoe.shuffle = MagicMock() dealer.deal() dealer.shoe.shuffle.assert_called()
dealer.deck.shuffle() deal_num = 0 # Initialize two players for the game player1 = Player() player2 = Player() if game_type == 'battle': player1_wins = 0 player2_wins = 0 while (dealer.deck.number_of_cards > 1): # Receive a new card from the dealer player1.receive_card(dealer.deal()) player2.receive_card(dealer.deal()) deal_num += 1 # Show their hands after one card each player1_total, player2_total = print_state(deal_num) # Receive a new card from the dealer new_card = dealer.deal() player1.receive_card(new_card) new_card = dealer.deal() player2.receive_card(new_card) deal_num += 1 # Show their hands after two cards each player1_total, player2_total = print_state(deal_num)
def main(argv): try: opts, args = getopt.getopt(argv, "ha:d:g:", ["attacker=", "defender=", "game="]) except getopt.GetoptError: print('big2.py -a <attacker> -d <defender> -g <game>') sys.exit(2) Tom = Jack = game = None for opt, arg in opts: if opt == '-h': print('big2.py -a <attacker> -d <defender> -g <game>') sys.exit() elif opt in ("-a", "--attacker"): Tom = choosePlayer(arg) elif opt in ("-d", "--defender"): Jack = choosePlayer(arg) elif opt in ("-g", "--game"): game = int(arg) if not Tom or not Jack or not game: print('big2.py -a <attacker> -d <defender> -g <game>') sys.exit(3) Annie = Dealer("Version1") cards = Annie.deal(game) Tom.newGame(copy.copy(cards[0]), copy.copy(cards[1]), Jack.teamName()) Jack.newGame(copy.copy(cards[1]), copy.copy(cards[0]), Tom.teamName()) print("{:<80}".format(Tom.teamName())) print("{:<80}".format(str(cards[0]))) print("{:>80}".format(Jack.teamName())) print("{:>80}".format(str(cards[1]))) print("-" * 80) #Tom.play(['A', 'J', '2', '3', '3', '5', '10'], [7, 7, 8], [8])) t, player, score = [], None, None while not score: # Tom 先手,然后轮流出牌 player = Tom if not player or player is Jack else Jack try: # t = player.play(t.copy()) time_out = RunWithTimeout(player.play, t.copy()) t = time_out.run(33) if len(t) == 1 and (t[0] == 'timeout' or t[0] == 'error'): print(t[0]) t = [] score, t = Annie.check(t) except: print('error2') score, t = Annie.check([]) output = "{:<80}" if player is Tom else "{:>80}" print(output.format(str(t) if t else "pass")) try: player.ack(t.copy()) # player获知Annie的裁定 except: pass else: print("{} is the winner! score={}".format(player.teamName(), score)) with open('result/%s.txt' % game, 'a+') as f: f.write(Tom.teamName()) if player.teamName() == Tom.teamName(): f.write(' win ') else: f.write(' loss ') score = -score f.write(Jack.teamName()) f.write(' ') f.write(str(score)) f.write('\n') print('write')
class Blackjack: use_color = True playing = True continue_game = True def __init__(self): self.cards = Cards() self.player = Player() self.dealer = Dealer() def _continueGame(self): if self.player.hasBlackjack() or self.dealer.hasBlackjack(): return False else: return True def isBust(self): if self.player.isBust() or self.dealer.isBust(): return True else: return False def new(self): time.sleep(2) self.cards = Cards() self.player = Player() self.dealer = Dealer() self.dealer.shuffle(self.cards) card1, card2 = self.player.receiveCards(self.dealer.deal(self.cards)) card3, card4 = Dealer.receiveCards() global screen cards_render = pygame.sprite.RenderPlain((card1,card2,card3,card4)) cards_render.update() cards_render.draw(screen) pygame.display.flip() return self._continueGame() def showCards(self): global screen card1 = Dealer.revealFirstCard() cards_render = pygame.sprite.RenderPlain((card1)) cards_render.update() cards_render.draw(screen) pygame.display.flip() time.sleep(2) ds = self.dealer.showCards() time.sleep(2) ps = self.player.showCards() time.sleep(2) _print('---------------------------------------', 'magenta') if ps == ds or (ps > 21 and ds > 21): _print('Push. Neither dealer nor player won.', 'magenta') elif ps <= 21 and ps > ds: _print('Player wins with {0}.'.format(ps), 'magenta') elif ds <= 21 and ds > ps: _print('Dealer wins with {0}.'.format(ds), 'magenta') elif ps > 21 and ds <= 21: _print('Dealer wins with {0}. Player bust.'.format(ds), 'magenta') elif ds > 21 and ps <= 21: _print('Player wins with {0}. Dealer bust.'.format(ps), 'magenta') _print('---------------------------------------', 'magenta') def hit(self): self.player.hit(self.cards) def stand(self): self.player.stand() response, dealer_cards = self.dealer.respond(self.cards) if len(dealer_cards) > 0: global screen card1 = dealer_cards[0] card2 = None cards_render = pygame.sprite.RenderPlain((card1)) cards_render.update() cards_render.draw(screen) pygame.display.flip() def cls(self): os.system('cls' if os.name == 'nt' else 'clear')
def main(args=None): assert version_info.major == 3 and version_info.minor == 8, "Ensure python version (= 3.8)" """ SETUP """ if args is None: args = parse_args() global loglevel loglevel = LogLevel[args.log] l, k, t = args.l, args.k, args.t log(f"Participating players: {l}, Number of collaborating players (Quorom size): {k}, Maximum number of corrupt players: {t}") assert l >= t + \ k, ("total number of participating players has to be larger than number of collaborating players and corrupt players combined") assert k >= t + \ 1, ("the minimum requried number of collaborating parties has to be at least one larger than the maximum number of corrupt parties") primegen_method = args.primegen log(f"Prime generation method: {primegen_method}") """ THE DEALER Generates safe primes for the public key modulus. Deals secret key shares and verification key shares. """ bitlength = args.bitlength log(f"Bitlength of primes: {bitlength}") # the fourth Fermat number - basically just a large number known to be prime e = pow(2, pow(2, 4)) + 1 assert e > l, "e has to be a prime larger than number of players" players = [Player() for _ in range(l)] dealer = Dealer(bitlength, e, primegen_method) # Shared values n, e = dealer.public_key v, u, m = dealer.v, dealer.u, dealer.m log(f"Bitlength of modulus: {n.bit_length()}") message = args.message log(f"message: {message}", LogLevel.VERBOSE) delta = factorial(l) protocol = None if k == t + 1: log("Protocol 1") protocol = Protocol1(message=message, n=n, delta=delta, m=m) else: # k > t + 1: log("Protocol 2") protocol = Protocol2(message=message, n=n, delta=delta, m=m, u=u, e=e) vks = dealer.deal(players, k, protocol) # Dealer is no longer used del dealer # Hashed message x = protocol.get_hashed_message() log(f"hashed message: {x}", LogLevel.VERBOSE) """ COMBINING SHARES Combines signature shares to get a signature. We simulate that we receive generated signature shares from k players. """ from random import sample S = sample(range(1, l + 1), k) log(f"Combining shares of players {S}", LogLevel.VERBOSE) w = 1 for i in S: x_i, poc_i = players[i-1].generate_signature_share(delta, protocol) # verify proof of correctness verify_poc(protocol, x, vks, i, poc_i, v, x_i, n) # combine signature share lambda_S_0i = lambda_(delta, 0, i, S) temp = powmod(x_i, 2 * lambda_S_0i, n) w = (w * temp) % n log(f"w: {w}", LogLevel.VERBOSE) e_prime = protocol.calculate_e_prime() gcd, a, b = xgcd(e_prime, e) assert gcd == 1, "gcd(e', e) != 1" xe_prime = powmod(x, e_prime, n) we = powmod(w, e, n) assert we == xe_prime, "w^e != x^e'" assert e_prime * a + e * b == 1, "e'a + eb != 1" wa = powmod(w, a, n) xb = powmod(x, b, n) y = protocol.calculate_y(wa, xb) ye = powmod(y, e, n) log(f"y^e: {ye}", LogLevel.VERBOSE) assert ye == H(message, n), "Invalid message signature" log("Message signature was valid!", LogLevel.DEFAULT)
def test_deal(self): dealer = Dealer() self.assertEqual(len(dealer.cards), 52) dealer.deal() self.assertEqual(len(dealer.cards), 51)
class Blackjack: use_ai = False settings = { 'use_color': True, 'code-page': '850' } playing = True continue_game = True @staticmethod def loadConfiguration(config='blackjack.xml'): tree = ET.parse(config) root = tree.getroot() for child in root.findall('terminal'): Blackjack.settings['use_color'] = str2bool(child.find('use-color').text) Blackjack.settings['code-page'] = child.find('code-page').get('default') def __init__(self): self.cards = Cards(Blackjack.settings['use_color']) self.player = Player(Blackjack.settings['use_color']) self.dealer = Dealer(Blackjack.settings['use_color']) def _continueGame(self): if self.player.hasBlackjack() or self.dealer.hasBlackjack(): return False else: return True def isBust(self): if self.player.isBust() or self.dealer.isBust(): return True else: return False def new(self): time.sleep(2) self.cards = Cards(Blackjack.settings['use_color']) if Blackjack.use_ai: self.player = AI(Blackjack.settings['use_color']) else: self.player = Player(Blackjack.settings['use_color']) self.dealer = Dealer(Blackjack.settings['use_color']) self.dealer.shuffle(self.cards) self.player.receiveCards(self.dealer.deal(self.cards)) return self._continueGame() def showCards(self): time.sleep(2) ds = self.dealer.showCards() time.sleep(2) ps = self.player.showCards() time.sleep(2) _print('-------------------------------------------------------', 'magenta') if ps == ds or (ps > 21 and ds > 21): _print('Push. Neither dealer nor player won.', 'magenta') elif ps <= 21 and ps > ds: _print('Player wins with {0}.'.format(ps), 'magenta') elif ds <= 21 and ds > ps: _print('Dealer wins with {0}.'.format(ds), 'magenta') elif ps > 21 and ds <= 21: _print('Dealer wins with {0}. Player bust.'.format(ds), 'magenta') elif ds > 21 and ps <= 21: _print('Player wins with {0}. Dealer bust.'.format(ps), 'magenta') _print('-------------------------------------------------------', 'magenta') def hit(self): self.player.hit(self.cards) def stand(self): self.player.stand() self.dealer.respond(self.cards) def aiRespond(self): response = self.player.respond(self.cards) if response == 'stand': response = self.dealer.respond(self.cards) if response == 'stand': Blackjack.continue_game = False def cls(self): os.system('cls' if os.name == 'nt' else 'clear')