def test_hand_can_cast_itself_to_new_ranked(self): hand = Hand() hand.add_card(Card("C", "A")) hand.add_card(Card("D", "A")) new_hand = hand.to_ranked("C") for card in new_hand: assert isinstance(card, RankedCard)
def play(): """ :return: """ bj_settings = Settings() pygame.display.set_caption("Blackjack") # create play button rect play_button = pygame.image.load('images/play.png') play_rect = play_button.get_rect() play_rect.topleft = (475, 100) # draw screen and add objects bj_settings.game_screen.fill(bj_settings.GREEN) bj_settings.game_screen.blit(play_button, (475, 50)) pygame.display.update() # get events while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == MOUSEBUTTONDOWN: if play_rect.collidepoint(event.pos): player = Hand() dealer = Hand() deck = Deck() tb.take_bet(10, player, dealer, deck)
def play(): """ play button screen :return: """ bj_settings = Settings() pygame.display.set_caption("Blackjack") # create play button rect play_button = pygame.image.load('images/play.png') play_rect = play_button.get_rect() play_rect.topleft = (475, 100) # TODO FIX pygame.display.set_icon(pygame.image.load('images/poker.png')) bj_settings.screen.fill(bj_settings.bg_color) bj_settings.screen.blit(play_button, (475, 50)) pygame.display.update() while True: # main game loop for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() if event.type == pygame.MOUSEBUTTONDOWN: if play_rect.collidepoint(event.pos): player = Hand() dealer = Hand() deck = Deck() tb.take_bet(1000, player, dealer, deck)
def __init__(self, id=''): """Initialize player object""" self.hand = Hand() self.id = id self.turnsLeft = 0 self.hasToBeat = False
class Player: def __init__(self, is_dealer=False): self.type = 'dealer' if is_dealer else 'player' self.hand = Hand() def hit(self, card): self.hand.add_card(card) def hand_total(self): return self.hand.get_total() def show_hand(self, hole_card=False): total = self.hand.get_total() for n in range(len(self.hand.cards)): if self.type == 'dealer' and n == 0 and hole_card: print('{num}) {val}'.format(num=n, val='–')) continue val = self.hand.cards[n].value print('{num}) {val}'.format(num=n, val=val)) if self.type == 'player' or not hole_card: print('Total: {total}'.format(total=total)) def __str__(self): return 'Player Type: ' + self.type + '\n'
def test_hard_17(self): hand = Hand([ Card(rank='A', suit='spade'), Card(rank='K', suit='spade'), Card(rank='6', suit='spade'), ]) self.assertEqual(hand.score(), 17)
class Dealer(User): """Define the dealer.""" def __init__(self, deck, players): User.__init__(self, deck) self.hand = Hand() self.players = players def deal(self): """The dealer deals two cards to the player. Dealer's first card is face down.""" for _ in range(2): for player in self.players: player.hit() self.hit() self.hand.cards[0].face_down() def hit_long(self): """The dealer hits until 17. In pyBlackJack dealer stands on soft 17.""" while self.hand.get_value() < 17: self.hit() def unveil_cards(self): """Unveil dealer's cards.""" self.hand.cards[0].face_up() def clear(self): """Remove dealer's hand.""" self.hand.clear()
def deck_deal_cards_test(): d = Deck() h = Hand() d.deal_cards(h, 10) if d.card_count() == 42 and h.card_count() == 10: return True else: return False
def __init__(self, user): self.name = str(user) self.display_name = user.display_name self.inv = Inventory() self.decks = [] self.hand = Hand()
def hit(deck: cards.Deck, hand: cards.Hand): assert type(deck) is cards.Deck assert type(hand) is cards.Hand hand.add_card(deck.deal()) hand.adjust_for_aces() return hand
def test_hand(): hand = Hand() for i in range(2): for j in range(4): hand.cards.append( Card(Card.values[randint(0, 12)], Card.suits[randint(0, 3)])) hand.sort_hand() return hand
def hand_card_count_test(): d = Deck() h = Hand() d.deal_cards(h, 8) if h.card_count() == 8: return True else: return False
def test_bust(self): hand = Hand([ Card(rank='K', suit='spade'), Card(rank='Q', suit='spade'), Card(rank='J', suit='spade'), Card(rank='A', suit='spade'), ]) hand.is_bust()
def test_really_hard_14(self): hand = Hand([ Card(rank='A', suit='spade'), Card(rank='A', suit='club'), Card(rank='A', suit='heart'), Card(rank='A', suit='diamond'), Card(rank='K', suit='spade') ]) self.assertEqual(hand.score(), 14)
def hit(deck, hand): card = Deck.deal(deck) Hand.add_cards(hand, card) if hand.value > 21: if hand.aces > 0: hand.adjust_for_ace() else: print('bust') print(hand)
def split(self, hand, bet): new_hand = Hand("Split") new_hand.add_card(hand.cards[1]) hand.remove_card(hand.cards[1]) self.deck.move_cards(hand, 1) self.deck.move_cards(new_hand, 1) self.player_hands.append(new_hand) self.player_chips = self.player_chips - bet self.bets.append(bet) self.in_play.append(True)
def hand_add_card_test(): c = Card('A', 'd') h = Hand() h.add_card(c) if h.card_count() == 1: if h.cards[0].rank == 'A' and h.cards[0].suit == 'd': return True else: return False else: return False
class Player: def __init__(self, user): self.name = str(user) self.display_name = user.display_name self.inv = Inventory() self.decks = [] self.hand = Hand() def draw(self, card): self.hand.append(card)
def main(): d = Deck() print 'hands:' c1 = raw_input('card1?') c2 = raw_input('card2?') c3 = raw_input('card3?') c4 = raw_input('card4?') card1 = Card(c1[0], c1[1]) card2 = Card(c2[0], c2[1]) card3 = Card(c3[0], c3[1]) card4 = Card(c4[0], c4[1]) ps = list() ps.append(Hand(card1, card2)) ps.append(Hand(card3, card4)) # ps = d.deal_players(N_PLAYERS) ps_str = '' for p in ps: ps_str += str(p) + ', ' print ps_str wins = [0] * N_PLAYERS for loop in range(0, N_LOOP): d.reset() for p in ps: d.draw_card(p.card1) d.draw_card(p.card2) # print "community:" com = d.deal_community() com_str = '' for c in com: com_str += str(c) + ', ' # print com_str ss = [] for i in range(0, N_PLAYERS): ss.append(Holdem.showdown_hand_score(ps[i], com)) # print ps[i], ss[i] # # if ss[i][0] == '9': # # exit() # print 'best:' max_index, max_value = max(enumerate(ss), key=operator.itemgetter(1)) # print max_index, max_value if ss[0] == ss[1]: wins[0] += 0.5 wins[1] += 0.5 else: wins[max_index] += 1 # OCOC what about ties? for i_wins in wins: print round(float(i_wins) / N_LOOP * 1000) / 10.0
def _parse_players(line: str, trump: TrumpType) -> List[Player]: """ Helper for parse_file. Example: line is such - [Deal "E:AK872.KQJT.K.Q94 QT95.85.AQJ2.AK7 4.A962.96.J86532 J63.743.T87543.T"] And the result is list of Player object. First is Player(PositionEnum.E, Hand) such that Hand is list contain A, K, 8, 7, 2 faces of suit ♠, ect. :param line: line from PBN file, which starts with "[Deal " :return: list of 4 Player objects, sorted by (N, E, S, W) """ player_str, all_hands_str = line.split(':') next_position = POSITIONS[PLAYERS_DICT[player_str]] players = [None, None, None, None] players_str = all_hands_str.split( ' ') # spaces separate every two players for p in players_str: curr_position = next_position cards_str = p.split('.') # dots separate every two suits cards = [] for i, suit in enumerate(cards_str): for face in suit: cards.append( Card(face=face, suit=SuitType(SUITS[i]).name, trump=trump)) next_position = PLAYERS_CYCLE[curr_position] players[curr_position.value - 1] = Player(curr_position, Hand(cards)) return players
def split(self): """Split a hand containing a pair. Create two separate hands that have the same first card.""" # Create a new hand new_hand = Hand() # Add current hand's first card to the new hand new_hand.deal(self.hand.cards[0]) # Remove the first card from the splitted hand self.hand.cards.pop(0) # Complete both hands with a card new_hand.deal(self.deck.pop()) self.hand.deal(self.deck.pop()) # Add the new hand to self.hands array self.hands.append(new_hand)
def parse_cards(self): if hasattr(self, 'me') and self.me: key = ('hand', self.me) if key in self.sharedData: cards = self.sharedData.pop(key) self.hand = Hand(cards[0], cards[1]) if 'table' in self.sharedData: self.table_cards = self.sharedData.pop('table')
def hand_print_output(): print('------: Creating Hand') d = Deck() d.shuffle_deck() h = Hand() d.deal_cards(h, 8) print(Fore.CYAN + 'OUTPUT: ', end='') print(Style.RESET_ALL, end='') hand_iter(h)
def hand_is_empty_test(): c = Card("A", 'd') h = Hand() if h.is_empty(): h.add_card(c) h.remove_card1() if h.is_empty(): return True else: return False else: return False
def __init__(self, id=''): """Initialize CPU object""" super().__init__(id) # self.id = "CPU" + str(id) self.hand = Hand() self.seed = random.seed() # 1 is no error, 0 is never slap self.errorSlapRate = 0.5 # random.uniform(0, 1) # TODO: not uniform
def hand_remove_card1_test(): c = Card('A', 'd') h = Hand() h.add_card(c) if h.card_count() == 1: h.remove_card1() if h.card_count() == 0: return True else: return False else: return False
def __init__(self, player_type: PlayerType, deck: Deck): self.life = Life() self.aura = Aura() self.flare = Flare() self.type = player_type self.vigor = Vigor(player_type) self.hand = Hand() self.trumps = Trumps(deck.trump_cards) self.stock = Cards(deck.normal_cards) self.downed = Cards() self.discarded = Cards() self.grants = Grants() self.extra_cards = Cards(deck.extra_cards) # 個別のメガミ関連 self.umbrella = None self.gauge = None self.stratagem = None self.machine = None self.stock.shuffle()
def __init__(self, name, credits=100, hand=None, deck=None): self.name = name self.credits = credits if deck is None: self.deck = Deck() else: self.deck = deck if hand is None: self.hand = Hand(deck=self.deck) else: self.hand = hand
def deck_deal_to_hand_test(): ''' Testing card dealing by dealing 7 cards to 2 separate Hands and checking the count of both the cards and hands are correct ''' d = Deck() h1 = Hand() h2 = Hand() for i in range(7): d.deal_to_hand(h1) d.deal_to_hand(h2) if d.card_count() == 38: if h1.card_count() == 7 and h2.card_count() == 7: return True
def __init__(self, deck, players): User.__init__(self, deck) self.hand = Hand() self.players = players
def test_simple(self): hand = Hand([Card(rank='5', suit='spade')]) self.assertEqual(hand.score(), 5)
def run(self, input_socket): # Get a file-object for reading packets from the socket. # Using this ensures that you get exactly one packet per read. f_in = input_socket.makefile() debug = True hand = Hand() strength = 0 board = Hand() pip = 0 num_raises = 0 pcklin = open('../../starting_hands/hand_strengths.pickle', 'r') hand_strengths = pickle.loads(pcklin.read()) pcklin.close() opp_profile = PlayerProfile() while True: # Block until the engine sends us a packet. data = f_in.readline().strip() # If data is None, connection has closed. if not data: print "Gameover, engine disconnected." break if debug: print data words = data.split() if words[0] == "NEWGAME": my_name = words[1] opp_name = words[2] stack_size = int(words[3]) bb = int(words[4]) num_hands = int(words[5]) time_bank = float(words[6]) elif words[0] == "NEWHAND": hand_id = int(words[1]) button = (words[2].lower() == 'true') hand = make_hand(' '.join(words[3:7])) board = Hand() my_bank = int(words[7]) opp_bank = int(words[8]) time_bank = float(words[9]) pip = 0 hand_strength_data = hand_strengths[hand.unique_id()] strength = float(hand_strength_data[0]) / hand_strength_data[1] num_raises = 0 street = 0 my_last_action = "CHECK" if (debug): opp_profile.reset() elif words[0] == "HANDOVER": opp_profile.pretty_print() print elif words[0] == "GETACTION": pot_size = int(words[1]) board_size = int(words[2]) for i in range(len(board.cards), board_size): board = board.add(make_card(words[3 + i])) curr_token = 3 + board_size num_last_actions = int(words[curr_token]) last_actions_raw = words[curr_token + 1:curr_token + num_last_actions + 1] print("Last actions: {}".format(last_actions_raw)) curr_token += num_last_actions + 1 num_legal_actions = int(words[curr_token]) legal_actions_raw = words[curr_token + 1:curr_token + num_legal_actions + 1] print("Legal actions: {}".format(legal_actions_raw)) curr_token += num_legal_actions + 1 timeBank = float(words[curr_token]) can_check = False can_bet = False min_bet = 0 max_bet = 0 can_raise = False min_raise = 0 max_raise = 0 can_call = False to_call = 0 for action in last_actions_raw: print("processing action {}".format(action)) print("street: {}".format(street)) split_action = action.split(':') if split_action[0] == 'DEAL': # New card has been dealt, pip resets. pip = 0 street += 1 elif split_action[-1] != my_name: if split_action[0] == 'CHECK': opp_profile.check_obs[street] += 1 elif split_action[0] == 'CALL': opp_profile.call_obs[street] += 1 opp_profile.calls[street] += 1 elif split_action[0] == 'BET': to_call = int(split_action[1]) opp_profile.check_obs[street] += 1 opp_profile.bets[street] += 1 elif split_action[0] == 'RAISE': to_call = int(split_action[1]) opp_profile.call_obs[street] += 1 opp_profile.raises[street] += 1 elif split_action[0] == 'FOLD': if my_last_action == 'CHECK': opp_profile.check_obs[street] += 1 else: opp_profile.call_obs[street] += 1 elif split_action[0] == 'POST': to_call = 2 else: my_last_action = split_action[0] if split_action[0] == 'POST': pip = int(split_action[1]) for action in legal_actions_raw: split_action = action.split(':') if split_action[0] == 'CHECK': can_check = True elif split_action[0] == 'BET': can_bet = True min_bet = int(split_action[1]) max_bet = int(split_action[2]) elif split_action[0] == 'CALL': can_call = True elif split_action[0] == 'RAISE': can_raise = True min_raise = int(split_action[1]) max_raise = int(split_action[2]) output = None if board_size == 0: # Pre-flop strategy # print("My hand strength is {}".format(strength)) if can_check: if strength > 0.6: # Premium hand # if max_bet > 0: output = "BET:{}".format(max_bet) elif max_raise > 0: output = "RAISE:{}".format(max_raise) else: output = "CHECK" elif strength > 0.53: # Good hand # if max_bet > 0: output = "BET:{}".format( (min_bet + max_bet) / 2) elif max_raise > 0: output = "RAISE:{}".format( (min_raise + max_raise) / 2) else: output = "CHECK" else: output = "CHECK" else: if strength > 0.7 and max_raise > 0: output = "RAISE:{}".format(max_raise) elif strength > 0.65 and max_raise > 0 and num_raises < 3: output = "RAISE:{}".format(max_raise) elif strength > 0.58 and max_raise > 0 and num_raises < 2: output = "RAISE:{}".format(max_raise) elif strength > 0.55: output = "CALL" else: output = "FOLD" else: # Post-flop strategy # strength = relative_strength(hand, board) print("My relative strength is {}".format(strength)) if can_check: if max_bet == 0: output = "CHECK" else: if strength > 0.9: # Uber hand # output = "BET:{}".format(max_bet) elif strength > 0.75: # Strong hand# output = "BET:{}".format( (max_bet + min_bet) / 2) else: output = "CHECK" elif num_raises == 0: if strength > 0.95: if max_raise > 0: output = "RAISE:{}".format(max_raise) else: output = "CALL" elif strength > 0.8: raise_amount = int(pot_size * strength / 1.5) if max_raise > 0 and raise_amount >= min_raise: output = "RAISE:{}".format( min(max_raise, raise_amount)) else: call_amount = int(pot_size * strength) if to_call < call_amount: output = "CALL" else: output = "FOLD" elif strength > 0.65: call_amount = int(pot_size * strength / 1.5) if to_call < call_amount: output = "CALL" else: output = "FOLD" else: output = "FOLD" else: if strength > 0.96 + 0.01 * num_raises: if max_raise > 0: output = "RAISE:{}".format(max_raise) else: output = "CALL" elif strength > 0.85: output = "CALL" else: output = "FOLD" if (debug): print("My hand: {}".format(hand)) print("The board: {}".format(board)) print("my name: {}".format(my_name)) if can_check: print("I can CHECK.") if can_call: print("I can CALL {}".format(to_call)) if can_bet: print("I can BET {} to {}".format(min_bet, max_bet)) if can_raise: print("I can RAISE {} to {}".format( min_raise, max_raise)) if pip > 0: print("I have {} in the pot".format(pip)) print("I choose to {}".format(output.strip())) # Calculate pip (how much money I have in the pot) split_output = output.split(':') if split_output[0] == 'RAISE' or split_output[0] == 'BET': pip = int(split_output[1]) # Add newline to output for the engine if (output[-1] != '\n'): s.send("{}\n".format(output)) else: s.send(output) if (debug): print elif words[0] == "REQUESTKEYVALUES": # At the end, the engine will allow your bot save key/value pairs. # Send FINISH to indicate you're done. s.send("FINISH\n") # Clean up the socket. s.close()
class Player: """ A Player class Attributes ---------- num_cards : int The number of cards the player has id : str A player's id Methods ------- __init__(self, id='') Initialize player object __repr__(self) Representational string __str__(self) Stringify spit(self, deck) The player moves top card from hand to top of main deck burn(self, deck) The player "burns" top card from hand to bottom of main deck slap(self, deck) The player slaps the main deck """ def __init__(self, id=''): """Initialize player object""" self.hand = Hand() self.id = id self.turnsLeft = 0 self.hasToBeat = False # self.prevPlayer <- implement like linked list? # self.nextPlayer <- implement like linked list? def __repr__(self): """Representational string representation""" return "%s(%s)" % (self.__class__.__name__, repr(self.hand)) def __str__(self): """Stringify""" return "%s" % (str(self.hand)) # return "%s %s has %s cards" % (self.__class__.__name__, self.id, self.hand.size) def spit(self, deck): """The player moves top card from hand to top of main deck Parameters ---------- deck : Deck The main deck to move card to """ temp = self.hand.peek() self.hand.to_deck(deck, 1, toTop=True) print_player("+ %s" % (temp), self, replace=True) def burn(self, deck): """The player "burns" top card from hand to bottom of main deck Parameters ---------- deck : Deck The main deck to move card to """ # print_player("- %s" % (self.hand.peek()), self) self.hand.to_deck(deck, 1, toTop=False) def slap(self, deck): """ The player slaps the main deck. If the slap is good, the entire deck is transferred to the players hand. If not, the player must burn one card. Parameters ---------- deck : Deck The main deck that the player slapped """ print_player("slapped the deck", self) slapRule = self._check_slap(deck) if (slapRule is not False): # Good slap -> move all deck cards to hand whoWon = "You" if self.id == 0 else "Player %d" % (self.id) print_player( "+ %d cards. %s won the deck with the %s!" % (deck.size, whoWon, slapRule), self) deck.to_hand(self, deck.size, toTop=False) return True else: # Bad slap -> burn one card to front of deck temp = self.hand.peek() self.burn(deck) print_player("- %s Bad slap!" % (temp), self) return False @staticmethod def _check_slap(deck): """Check if deck is slappable Rules found here: (https://www.bicyclecards.com/how-to-play/egyptian-rat-screw/) * Double – When two cards of equivalent value are laid down consecutively. Ex: 5, 5 * Sandwich – When two cards of equivalent value are laid down consecutively, but with one card of different value between them. Ex: 5, 7, 5 * Top Bottom – When the same card as the first card of the set is laid down. * Tens – When two cards played consecutively (or with a letter card in between) add up to 10. For this rule, an ace counts as one. Ex: 3, 7 or A, K, 9 * Jokers – When jokers are used in the game, which should be determined before gameplay begins. Anytime someone lays down a joker, the pile can be slapped. * Four in a row – When four cards with values in consistent ascending or descending order is placed. Ex: 5, 6, 7, 8 or Q, K, A, 2 * Marriage – When a queen is placed over or under a king. Ex: Q, K or K,Q Parameters ---------- deck : Deck The Deck that you want to check Returns ------- boolean True if deck was slappable, False if not """ slapIsGood = False slapRule = None slapLogFormat = "{} Rule" def deck1(_deck): # """If deck is 1 card # * Jokers # """ # if _deck.stack[-1].rank == 11: # _slapRule = slapLogFormat.format("Jokers") # return True # return False return [] # don't implement Joker card def deck2(_deck): """If deck is 2 cards * Double * Top Bottom * Tens - 2 cards * Marriage """ if _deck.stack[-1].rank == _deck.stack[-2].rank: return [slapLogFormat.format("Double")] if _deck.stack[-1].rank == _deck.stack[0].rank: return [slapLogFormat.format("Top Bottom")] if _deck.stack[-1].rank + _deck.stack[-2].rank == 10: return [slapLogFormat.format("Tens - 2 cards")] if (_deck.stack[-1].rank == 12 and _deck.stack[-2].rank == 13) or \ (_deck.stack[-1].rank == 13 and _deck.stack[-2].rank == 12): return [slapLogFormat.format("Marriage")] return [] def deck3(_deck): """If deck is 3 cards * Sandwich * Tens - 3 cards """ if _deck.stack[-1].rank == _deck.stack[-3].rank: return [slapLogFormat.format("Sandwich")] if 11 <= _deck.stack[-2].rank <= 13 and sum( [e.rank for e in _deck.stack[-3:]]) == 10: return [slapLogFormat.format("Tens - 3 cards")] return [] def deck4(_deck): """If deck is 4 cards * Four in a row """ if all(diff == 1 for diff in [ y.rank - x.rank for x, y in zip(_deck.stack[-4:-1], _deck.stack[-3:]) ]): return [slapLogFormat.format("Four in a row")] return [] if deck.size == 1: slapRule = deck1(deck) elif deck.size == 2: slapRule = deck1(deck) + deck2(deck) elif deck.size == 3: slapRule = deck1(deck) + deck2(deck) + deck3(deck) elif deck.size >= 4: slapRule = deck1(deck) + deck2(deck) + deck3(deck) + deck4(deck) else: slapRule = [] if len(slapRule) == 0: return False else: return slapRule[0]
def play_round(deck): playerHand = Hand() dealerHand = Hand() playerHand.add_card(deck.deal()) playerHand.add_card(deck.deal()) dealerHand.add_card(deck.deal()) dealerHand.add_card(deck.deal()) print("The dealer has: ") dealerHand.show(partial=True) print("You have: ") playerHand.show() while True: action = input("Do you want to \n" + "1. [H]it \n" + "2. [S]tand \n") if action in ["1", "h", "H"]: playerHand.add_card(deck.deal()) print("You have: ") playerHand.show() if playerHand.cur_value == GOAL_CONSTANT: win_statement("You", playerHand.cur_value) return playerHand, dealerHand, deck if playerHand.cur_value > GOAL_CONSTANT: lose_statement("You", playerHand.cur_value) return playerHand, dealerHand, deck if action in ['2', 'S', 's']: while dealerHand.cur_value < DEALER_CONSTANT: dealerHand.add_card(deck.deal()) dealerHand.show(partial=True) if dealerHand.cur_value > GOAL_CONSTANT: print("The dealer has: ") dealerHand.show() lose_statement("Dealer", dealerHand.cur_value) return playerHand, dealerHand, deck else: print("Please make a selection using 1 or 2")