def deal_initial_hands(bljdeck, dealerholecard=False): "Draw hands for the dealer and the player with two cards" initial_cards = bljdeck.draw_cards(ncards=4) dhand = cards.Hand(card_indices=[initial_cards[1], initial_cards[3]], holecard=dealerholecard) phand = cards.Hand(card_indices=[initial_cards[0], initial_cards[2]]) return dhand, phand
def __init__(self): self.board = game_board.Interface() self.win = self.board.getWindow() self.deck = cards.Deck() self.king_deck = cards.KingDeck() self.king_deck.shuffle() self.user_hand = cards.Hand() self.computer_hand = cards.Hand()
def test_init(self): for hand in [cards.Hand('6♡Q♣4♡5♢7♣2♢'), cards.Hand([cards.Card('6♡'), cards.Card('Q♣'), cards.Card('4♡'), cards.Card('5♢'), cards.Card('7♣'), cards.Card('2♢')])]: self.assertEqual(len(hand), 6) self.assertEqual(hand[0], cards.Card('6♡')) self.assertEqual(hand[-1], cards.Card('2♢')) self.assertEqual(repr(hand), '6♡Q♣4♡5♢7♣2♢') self.assertEqual(str(hand), '6♡Q♣4♡5♢7♣2♢') with self.assertRaises(IndexError): hand[6]
def test_setitem(self): hand = cards.Hand('6♡Q♣4♡5♢7♣2♢') hand[0] = cards.Card('K♠') self.assertEqual(repr(hand), 'K♠Q♣4♡5♢7♣2♢') hand[-1] = cards.Card('6♡') self.assertEqual(repr(hand), 'K♠Q♣4♡5♢7♣6♡') cardlist = cards.Hand('T♠J♡8♠A♢')[:] hand[1:3] = cardlist self.assertEqual(repr(hand), 'K♠T♠J♡8♠A♢5♢7♣6♡')
def test_pop(self): hand = cards.Hand('6♡Q♣4♡5♢7♣2♢') self.assertEqual(hand.pop(), cards.Card('6♡')) self.assertEqual(hand.pop(), cards.Card('Q♣')) self.assertEqual(hand.pop(2), cards.Card('7♣')) self.assertEqual(len(hand), 3) hand = cards.Hand('6♡Q♣4♡5♢7♣2♢') self.assertEqual(hand.popn(0), []) self.assertEqual(hand.popn(1), [cards.Card('6♡')]) self.assertEqual(hand.popn(2), [cards.Card('Q♣'), cards.Card('4♡')]) self.assertEqual(len(hand), 3)
def test_copy(self): h1 = cards.Hand('6♡Q♣4♡5♢7♣2♢') h2 = cards.Hand('6♡Q♣4♡5♢7♣2♢') h3 = copy.copy(h1) h4 = copy.deepcopy(h1) self.assertEqual(h1[:], h2[:]) self.assertEqual(h1[:], h3[:]) self.assertEqual(h1[:], h4[:]) h2.append(cards.Card('K♠')) h3.pop() h4.sort(key=cards.RankFirstOrderings.AceHigh) self.assertNotEqual(h1[:], h2[:]) self.assertNotEqual(h1[:], h3[:]) self.assertNotEqual(h1[:], h4[:])
def check_for_splits(deck, dealer_hand, hand_ix): global chip_stack, player_hands while player_hands[hand_ix].cards[0].rank == player_hands[hand_ix].cards[ 1].rank: if input("Player Hand #{}: Do you want to split the hand [y/n]? ". format(hand_ix + 1)).lower() == 'y': # Split the bet chip_stack.split_bet() # Create new hand, add card from current hand player_hands.append(cards.Hand()) player_hands[-1].add_card(player_hands[hand_ix].cards.pop()) player_hands[-1].add_card(deck.deal()) # For current hand, remove dropped card value (accounting for aces), and add new card if player_hands[-1].cards[0].rank == 'A': player_hands[hand_ix].val = 11 player_hands[hand_ix].aces = 1 else: player_hands[hand_ix].val -= cards.Card.vals[ player_hands[-1].cards[0].rank] player_hands[hand_ix].add_card(deck.deal()) jh.sleep_and_clear(1) cards.display_hands(player_hands, dealer_hand, chip_stack.bets, dealer_show=False)
def deal(self, deck=None): self.deck = deck or cards.Deck() self.pot = 0 self.upcards = [] self.winners = None self.dealer_button = self.nextfrom(self.dealer_button) for ps in self.players: ps.hand = cards.Hand() ps.folded = False ps.bet_this_round = 0 ps.played_this_round = False self.total_bet_this_round = 0 self.callback('deal') # deal two cards to each player for i in range(len(self.players) * 2): # start with the dealer button and rotate r = self.nextfrom(self.dealer_button, i + 1) self.players[r].hand.append(self.deck.deal()) # play the blinds self.next_to_act = self.nextfrom(self.dealer_button) self.playing_blinds = True self.putmoneyin(self.small_blind, is_small_blind=True) self.putmoneyin(self.big_blind, is_big_blind=True) self.playing_blinds = False self.callback('next_to_act', self.next_to_act, self.big_blind)
def __init__(self, uid, name, gold=0, stats=dict()): self.uid = uid self.name = name self.gold = gold self.bet = 0 self.hand = cards.Hand() self.in_game = False self.splits = 0 if 'Wins' in stats: self.wins = int(stats['Wins']) else: self.wins = 0 if 'NaturalWins' in stats: self.natural_wins = int(stats['NaturalWins']) else: self.natural_wins = 0 if 'Losses' in stats: self.losses = int(stats['Losses']) else: self.losses = 0 if 'Ties' in stats: self.ties = int(stats['Ties']) else: self.ties = 0 if 'LargestWin' in stats: self.largest_win = int(stats['LargestWin']) else: self.largest_win = 0 if 'LargestLoss' in stats: self.largest_loss = int(stats['LargestLoss']) else: self.largest_loss = 0
def __init__(self, id): ''' id is 1 indexed ''' self.id = id self.role = 'Peasant' self.hand = cards.Hand()
def create_stacked_deck(hands_wanted_strings, upcards_wanted_string): # create an actual deck to pull the cards from; this is so that we don't # duplicate cards, and end up with the correct number of cards in the # deck. unused_cards = cards.Deck(shuffle=False) hands_wanted = [] for s in hands_wanted_strings: h = cards.Hand(s) hands_wanted.append(h) for c in h: unused_cards.popcard(c.rank, c.suit) upcards_wanted = cards.Hand(upcards_wanted_string) for c in upcards_wanted: unused_cards.popcard(c.rank, c.suit) newdeck = cards.Deck(deckcount=0) def addcard(c=None): if c: newdeck.append(c) else: # deal something out of unused_cards c = unused_cards.pop() newdeck.append(c) for hand in hands_wanted: addcard(hand[0]) for hand in hands_wanted: addcard(hand[1]) # burn, flop, burn, turn, burn, river. addcard() for i in range(3): addcard(upcards_wanted.pop()) addcard() addcard(upcards_wanted.pop()) addcard() addcard(upcards_wanted.pop()) # add the remaining cards from the deck while len(unused_cards): addcard(unused_cards.deal()) return newdeck
def __init__(self): self.deck = cards.Deck() self.deck.populate() self.deck.shuffle() self.deck.stack() #for grading self.players = [] self.dealer_hand = cards.Hand() self.start()
def player_savvy(num_hands, totals): fitness = 0 while num_hands > 0: #set deck deck = cards.Deck() deck.shuffle() #deal cards player_hand = cards.Hand() deck.move_cards(player_hand, 2) dealer_hand = cards.Hand() deck.move_cards(dealer_hand, 2) #player logic while (savvy_decide(player_hand, dealer_hand) > 0): deck.move_cards(player_hand, 1) fitness += check_winner(dealer_hand, player_hand) num_hands -= 1 totals.put(("savvy", fitness))
def __init__(self, uid, name): self.uid = uid self.name = name self.gold = 0 self.bet = 0 self.hand = cards.Hand() self.in_game = False self.wins = 0 self.losses = 0
def __init__(self, name, deck, is_sim=False): self.name = name self.deck = deck self.hand = cards.Hand() self.board = Board(is_sim=is_sim) self.life_points = 4000 self.is_sim = is_sim self.memory = [] self.performance_memory = [] self.decisionmanager = decisionmanager.DecisionManager()
def player_rock(num_hands, totals): fitness = 0 for i in range(num_hands): #set deck deck = cards.Deck() deck.shuffle() #deal cards player_hand = cards.Hand() deck.move_cards(player_hand, 2) dealer_hand = cards.Hand() deck.move_cards(dealer_hand, 2) #player logic while add_cards(player_hand) <= 13: deck.move_cards(player_hand, 1) #dealer logic while add_cards(dealer_hand) <= 17: deck.move_cards(dealer_hand, 1) #evaluate fitness fitness += check_winner(dealer_hand, player_hand) totals.put(("rock", fitness))
def get_7_card_ranking(hand): # TODO: there's a much more efficient way to do this than checking every # possible combination, particularly if there are more than 7 cards. but # this works well enough, I might never change it. best_so_far = None for _5cards in itertools.combinations(hand[:], 5): _5card_hand = cards.Hand(_5cards) ranking = get_5_card_ranking(_5card_hand) if best_so_far is None or (ranking > best_so_far): best_so_far = ranking return best_so_far
def player_fish(num_hands, totals): fitness = 0 while num_hands > 0: #set deck deck = cards.Deck() deck.shuffle() #deal cards player_hand = cards.Hand() deck.move_cards(player_hand, 2) dealer_hand = cards.Hand() deck.move_cards(dealer_hand, 2) #player logic while add_cards(player_hand) <= 16: deck.move_cards(player_hand, 1) #dealer logic while add_cards(dealer_hand) <= 17: deck.move_cards(dealer_hand, 1) #evaluate fitness fitness += check_winner(dealer_hand, player_hand) num_hands -= 1 totals.put(("fish", fitness))
def __init__(self, wallet_amt, player_id, player_name): ''' Creates a new Player class. wallet_amt: int - the "buy in" amount that a player starts with player_id: int - the id for this player, provided by the server player_name: str - this player's name ''' self.wallet = wallet_amt self.hand = cards.Hand(cards.NUM_CARDS_IN_HAND) self.name = player_name self.id = player_id self.prompt = '> '
def __init__(self, player, fake_id): """ Takes in an originating player as the first argument and the card to start with as the second """ #start off with the original bet self.bet = player.bet self.hand = cards.Hand() #split the hand between self and parent self.hand.add_card(player.hand.remove_card(1)) self.fake_id = fake_id self.in_game = True self.parent = player
def test_sort_shuffle(self): hands = [cards.Hand('6♡Q♣4♡5♢7♣2♢') for i in range(5)] hands[1].sort(key=cards.RankFirstOrderings.AceHigh) hands[2].sort(key=cards.SuitFirstOrderings.AceLow) hands[3].shuffle() hands[4].shuffle() for hand in hands: self.assertEqual(len(hand), 6) cardsets = [set(hand[:]) for hand in hands] for i in range(4): self.assertEqual(cardsets[i], cardsets[i+1])
def deal(self, opponents): ''' Deals hole cards to the player and to X opponents and 4 cards to the board. Figures out if the player is ahead or behin: 1) if the player is ahead, finds the outs the player has to lose 2) if the player is behind, finds the outs the player has to win @param opponents number of opponent hands to deal ''' # we can't deal twice if False != self._dealt: return # shuffle it up! self._dealt = True self._deck.shuffle() # deal out the player hand self._hand_player = cards.Hand(self._deck.deal(), self._deck.deal()) # now for each opponent self._hand_opponents = [] for i in range(0, opponents): hand = cards.Hand(self._deck.deal(), self._deck.deal()) self._hand_opponents.append(hand) # now the four cards on the board self._board = [] for i in range(0, 4): self._board.append(self._deck.deal()) # figure out if the player is ahead or not after the turn self._ahead = self._calc_ahead() # calculate the number of outs the player or opponents have self._calc_outs()
def store_hand(self, player_id, card_list): ''' Takes the players hand and stores it to be evaluated. player_id: int - The ID of the player. cards: Card - The cards in the player's hand ''' # Cards not in Hand because it will be easier for server to pass to the # class; not sent as a hand, but individual cards. Creates the hand here. num_cards = len(card_list) hand = cards.Hand(num_cards) for card in card_list: hand.add_card(card) self.final_hands[player_id] = hand
def player_genetic(entities, num_hands, totals, training=True): for entity in entities: if not training: fitness = 0 entity.rawFitness = 0 deck = cards.Deck() for i in range(num_hands): #set deck deck.shuffle() #deal cards player_hand = cards.Hand() deck.move_cards(player_hand, 2) dealer_hand = cards.Hand() deck.move_cards(dealer_hand, 2) #player logic nn = entity.getNN() #Get the player's Neural Network while add_cards(player_hand) < 21 and nn.update([ add_cards(player_hand) / 31, low_add_cards(player_hand) / 31, min(dealer_hand.cards[0].rank / 10, 1), 1 ])[0] >= 0.5: deck.move_cards(player_hand, 1) #dealer logic while add_cards(dealer_hand) <= 17: deck.move_cards(dealer_hand, 1) #evaluate fitness if not training: fitness += check_winner(dealer_hand, player_hand) entity.rawFitness += check_winner(dealer_hand, player_hand) #return all cards to the deck player_hand.move_cards(deck, len(player_hand.cards)) dealer_hand.move_cards(deck, len(dealer_hand.cards)) if training: totals.put(entity) else: totals.put(("genetic", fitness)) totals.close() totals.join_thread()
def random_sample_hands(): # generate two of each type lists = { k: [] for k in range(poker.Ranking.high_card, poker.Ranking.straight_flush + 1) } while True: deck = cards.Deck() hand = cards.Hand(deck.dealn(7)) ranking = poker.get_7_card_ranking(hand) if len(lists[ranking.ranking]) < 2: print('{} {}'.format(hand.pretty(), ranking)) lists[ranking.ranking].append(hand) if all(len(l) == 2 for l in lists.values()): break return sum(lists.values(), [])
def clone_and_shuffle(self, hand): newhand = cards.Hand() # rotate suits for card in hand: newsuit = cards.SUITS[(cards.SUITS.index(card.suit) + 1) % 4] newhand.append(cards.Card(card.rank, newsuit)) newhand.shuffle() # ranks should be the same s1 = ''.join( card.rank for card in sorted(hand[:], key=cards.RankFirstOrderings.AceLow)) s2 = ''.join(card.rank for card in sorted(newhand[:], key=cards.RankFirstOrderings.AceLow)) self.assertEqual(s1, s2) return newhand
def test_popcard(self): hand = cards.Hand('6♡Q♣4♡5♢7♣2♢Q♢Q♡') card = hand.popcard(rank='5') self.assertEqual(repr(card), '5♢') self.assertEqual(len(hand), 7) self.assertEqual(repr(hand), '6♡Q♣4♡7♣2♢Q♢Q♡') card = hand.popcard(suit='♣') self.assertEqual(repr(card), 'Q♣') self.assertEqual(len(hand), 6) self.assertEqual(repr(hand), '6♡4♡7♣2♢Q♢Q♡') card = hand.popcard(rank='Q', suit='♡') self.assertEqual(repr(card), 'Q♡') self.assertEqual(len(hand), 5) self.assertEqual(repr(hand), '6♡4♡7♣2♢Q♢') with self.assertRaises(cards.CardNotFoundError): hand.popcard(rank='Q', suit='♡')
def __init__(self, img_path=os.path.join(SHIPS_PATH, 'Ship3/Ship3.png'), ctype='fighter', health=40, power=3, hand=5): super().__init__(img_path=img_path, max_health=health, explosion_path='Ship3') self.max_handsize = hand self.max_power = power self.power = 0 # all cards in the players current deck self.all_cards = [] # player class self.ctype = ctype # battle hands self.hand = cards.Hand() self.graveyard = [] self.deck = [] self.in_play = []
import cards as c my_deck = c.Deck() my_deck.shuffle() player = c.Hand() dealer = c.Hand() player.draw(my_deck.deal_card()) # dealer.draw(my_deck.deal_card()) player.draw(my_deck.deal_card()) # dealer.draw(my_deck.deal_card()) # player_bank = c.Chips(100) # player_bank.bet = 40 ################ # test for dealing cards to a hand # c.disp_hand(player) # print(f"aces = {player.aces}") ################ # test bust switch # c.disp_hand(player) # c.hit(player, my_deck) # c.disp_hand(player) # print(f"{player.bust}") # c.hit(player, my_deck)
async def cards_blackjack(ctx, *args: discord.Member): """You can play blackjack against the dealer and other members. Just give all the people you want to play with as arguments.""" channel = ctx.message.channel players = [] for arg in args: if arg.bot: await bot.send_message(channel, "No challenging bots, m8.") return players.append(arg) s = "Place your bets " for player in players: s += player.mention s += " " await bot.send_message(channel, s) bets = {} temp_players = players[:] for player in temp_players: await bot.send_message(channel, "{}'s turn. If you don't want to play, simply respond 'no'.".format( player.mention)) while True: bet = await bot.wait_for_message(timeout=60, author=player) if bet is None: await bot.send_message(channel, "You didn't bet in time, too bad.") players.remove(player) break if "no" in bet.content: await bot.send_message(channel, "{} has quit.".format(player.name)) players.remove(player) break try: bet = int(bet.content) if bet <= 0 or bet > ggs.get_ggs(player.id): await bot.send_message(channel, "Not enough ggs. Or you tried betting 0, what do I know.") continue bets[player.id] = bet break except ValueError: await bot.send_message(channel, "Not a number, try again, or just say no.") if len(players) == 0: await bot.send_message(channel, "EVERYBODY QUIT GG WP NO RE.") return await bot.send_message(channel, "Participants and their bets.") s = "" for player in players: s += player.name s += ": " s += str(bets[player.id]) s += "\n" await bot.send_message(channel, s) bj = cards.BlackJack() hands = {} for player in players: hands[player.name] = cards.Hand(player.name) dealer_hand = cards.Hand("Dealer") for hand in hands: result = bj.deck.deal([hands[hand]], 1) await bot.send_message(channel, "First card dealt to every player.") bj.deck.deal([dealer_hand], 1) await bot.send_message(channel, "Card dealt to dealer.") await bot.send_message(channel, str(dealer_hand)) temp_players = players[:] for player in temp_players: result = bj.deck.deal([hands[player.name]], 1) if result == 1: await bot.say(str(hands[player.name])) await bot.say("{}, WOW, NATURAL BLACKJACK. YOU WIN TWICE YOUR BET" .format(player.name)) ggs.add(player.id, (bets[player.id] * 2)) players.remove(player) await bot.send_message(channel, "Second card dealt to every player.") hand_messages = {} for player in players: hand_messages[player.id] = await bot.send_message(player, str(hands[player.name])) bj.deck.deal([dealer_hand], 1) await bot.send_message(channel, "Second card dealt to dealer.") await bot.send_message(channel, "THE GAME BEGINS FOR REAL.") temp_players_2 = players[:] for player in temp_players_2: while True: await bot.send_message(channel, "Your turn, {}. Take a card (type hit) or not (type stand)." .format(player.mention)) msg = await bot.wait_for_message(author=player, channel=channel) msg = msg.content if "stop" in msg.lower() or "stand" in msg.lower(): break if "hit" in msg.lower() or "take" in msg.lower(): dl = bj.deck.deal([hands[player.name]], 1) await bot.edit_message(hand_messages[player.id], str(hands[player.name])) if dl == 1: await bot.send_message(channel, str(hands[player.name])) await bot.send_message(channel, "{}, WOW, BLACKJACK.".format(player.name)) ggs.add(player.id, bets[player.id]) players.remove(player) break if dl == -1: await bot.send_message(channel, str(hands[player.name])) await bot.send_message(channel, "{}, YOU LOSE.".format(player.name)) ggs.sub(player.id, bets[player.id]) players.remove(player) break continue await bot.send_message(channel, "I don't get you m8, try again.") if len(players) == 0: await bot.send_message(channel, "Everybody lost, GG WP.") return dl_turn_result = None await bot.send_message(channel, str(dealer_hand)) await bot.send_message(channel, "Dealer's turn.") while dealer_hand.total_value() < 17: dl_turn_result = bj.deck.deal([dealer_hand], 1) await bot.send_message(channel, "Dealer's hand after his turn.") await bot.send_message(channel, str(dealer_hand)) if dl_turn_result == -1: await bot.send_message(channel, "The dealer loses. Every player gets paid their bet.") for player in players: ggs.add(player.id, bets[player.id]) return if dl_turn_result == 1: await bot.send_message(channel, "The dealer has a blackjack, every player who doesn't have it loses.") for player in players: ggs.sub(player.id, bets[player.id]) return for player in players: if hands[player.name].total_value() > dealer_hand.total_value(): await bot.send_message(channel, "{0} wins {1} ggs. {0}'s hand:\n {2}".format(player.name, bets[player.id], str(hands[player.name]))) ggs.add(player.id, bets[player.id]) elif hands[player.name].total_value() == dealer_hand.total_value(): await bot.send_message( channel, "{0} ties with the dealer, so they don't win nor lose anything. {0}'s hand:\n {1}".format( player.name, str(hands[player.name]))) else: await bot.send_message(channel, "{0} loses {1} ggs. {0}'s hand:\n {2}".format(player.name, bets[player.id], str(hands[player.name]))) ggs.sub(player.id, bets[player.id]) await bot.say("THE END")