def test_double_ace(self): hand = Hand() hand.add_card(Card('Diamonds', 'Ace')) hand.add_card(Card('Hearts', 'Ace')) hand.check_ace() value = hand.value self.assertEqual(value, 12)
class InPlay: def __init__(self): self._constructs = Hand() self._heroes = [] def reset(self): for i in range(self._constructs.get_size()): card = self._constructs.get_card_at_index(i) card.untap() del self._heroes[:] def use_construct(self, index): card = self._constructs.get_card_at_index(index) card.tap() def add_construct(self, card): self._constructs.add_card(card) def remove_construct(self, index): return self._constructs.remove_card(index) def add_hero(self, card): self._heroes.append(card) def is_hero_type_in_play(self, card_type): for i in range(len(self._heroes)): if (self._heroes[i].get_card_type() == card_type): return True return False def print(self): self._constructs.print()
def add_2card_hand_to(player): # deal 2 cards to the player player_hand = Hand() for _ in range(2): card = deck.deal_card() player_hand.add_card(card) player.add_hand(player_hand)
class Deck: def __init__(self, cards): self._deck = cards self._graveyard = Hand() self.shuffle() def draw_card(self): if (self.get_size() == 0): self.shuffle_graveyard_into_deck() if (self.get_size() == 0): return None return self._deck.pop() def peek(self): return self._deck[0] def put_card_on_top(self, card): self._deck.insert(0, card) def add_to_graveyard(self, card): self._graveyard.add_card(card) def shuffle(self): random.shuffle(self._deck) def shuffle_graveyard_into_deck(self): while (self._graveyard.get_size() != 0): self._deck.append(self._graveyard.remove_card(0)) self.shuffle() def get_size(self): return len(self._deck)
class Desk(): def __init__(self): self.dealer_hand = Hand() self.player_hand = Hand() self.account = PlayerAccount() self.bet = 0 self.deck = Deck() def visualize_concealed(self): clear_scrn() print(f"BET: ${self.bet}\n") print("DEALER:") print(self.dealer_hand.cards[0]) print("- CONCEALED -") print("\n", self.account, ": ") self.player_hand.visualize() def visualize(self): clear_scrn() print("DEALER:") self.dealer_hand.visualize() print("\n", self.account, ": ") self.player_hand.visualize() def deal_card(self, whom): if whom == 'player': self.player_hand.add_card(self.deck.cards[self.deck.index_card]) self.deck.index_card += 1 elif whom == 'dealer': self.dealer_hand.add_card(self.deck.cards[self.deck.index_card]) self.deck.index_card += 1
def game(self): player_turn = True print('Welcome to BlackJack!') name = input("What's your name? ") curr_chips = 100 while True: player = Player(name) dealer = Player("Dealer") # setup the game deck = Deck() deck.shuffle() player_hand = Hand() player_hand.add_card(deck.deal()) player_hand.add_card(deck.deal()) dealer_hand = Hand() dealer_hand.add_card(deck.deal()) dealer_hand.add_card(deck.deal()) player_chips = Chips(curr_chips) print(f'You have {player_chips.total} chips.') player_chips.take_bet(player_chips) self.show_cards(player_hand, dealer_hand) while player_turn: if player.hit_or_stand(deck, player_hand) == "h": self.show_cards(player_hand, dealer_hand) else: break if player_hand.value > 21: self.show_all_cards(player_hand, dealer_hand) player.player_busts(player_hand, dealer_hand, player_chips) break if player_hand.value <= 21: while dealer_hand.value < 17: dealer.hit(deck, dealer_hand) self.show_all_cards(player_hand, dealer_hand) if dealer_hand.value > 21: # dealer lose dealer.dealer_busts(player_hand, dealer_hand, player_chips) elif dealer_hand.value > player_hand.value: # dealer win dealer.dealer_wins(player_hand, dealer_hand, player_chips) elif dealer_hand.value < player_hand.value: # player win player.player_wins(player_hand, dealer_hand, player_chips) else: # tied player.tie(player_hand, dealer_hand) print(f'{player.name} has {player_chips.total} chips.') curr_chips = player_chips.total play_again = input("Play Again? y or n: ") if play_again[0].lower() == 'y': player_turn = True else: break continue
def test_add_card(self): hand = Hand() c1 = Card("Spades", "Two") c2 = Card("Hearts", "Jack") hand.add_card(c1) self.assertEqual(hand.value, 2) hand.add_card(c2) self.assertEqual(hand.value, 12)
def test_ace_reduction(self): hand = Hand() hand.add_card(Card('Spades', 'Seven')) hand.add_card(Card('Diamonds', 'Ace')) hand.add_card(Card('Hearts', 'Ten')) hand.check_ace() value = hand.value self.assertEqual(value, 18)
def play(): while True: playing = True print('Welcome to Blackjack') deck = Deck() deck.shuffle() player_hand = Hand() player_hand.add_card(deck.deal()) player_hand.add_card(deck.deal()) dealer_hand = Hand() dealer_hand.add_card(deck.deal()) dealer_hand.add_card(deck.deal()) player_chips = Chips() take_bet(player_chips) show_some(player_hand, dealer_hand) while playing: playing = hit_or_stand(deck, player_hand, playing) show_some(player_hand, dealer_hand) if player_hand.value > 21: player_busts(player_hand, dealer_hand, player_chips) break if player_hand.value <= 21: while dealer_hand.value < 17: hit(deck, dealer_hand) show_all(player_hand, dealer_hand) if dealer_hand.value > 21: dealer_busts(player_hand, dealer_hand, player_chips) elif dealer_hand.value > player_hand.value: dealer_wins(player_hand, dealer_hand, player_chips) elif dealer_hand.value < player_hand.value: player_wins(player_hand, dealer_hand, player_chips) else: push(player_hand, dealer_hand) print('\n Player total chips are at {}'.format(player_chips.total)) new_game = input("Would you like to play another hand? y/n") if new_game[0].lower() == 'y': playing = True continue else: print('Thank you for playing!') break
def split(hand1): hand2 = Hand("HAND 2", hand1.wager, False) hand1.was_split = True hand2.was_split = True hand1.cards.pop() hand1.calc_total() hand2.add_card(hand1.cards[0]) if hand2.cards[0] == "A": hand2.ace_list.append("A") return hand2
def test_ace_adjust(self): hand = Hand() c1 = Card("Spades", "Jack") c2 = Card("Spades", "Queen") hand.add_card(c1) hand.add_card(c2) ace = Card("Spades", "Ace") hand.add_card(ace) self.assertEqual(31, hand.value) hand.ace_adjust() self.assertEqual(21, hand.value)
def new_game(): d = Deck() player_hand = Hand("Player") dealer_hand = Hand("Dealer") player_hand.add_card(d.deal_card()) player_hand.add_card(d.deal_card()) dealer_hand.add_card(d.deal_card()) print(dealer_hand) print("=" * 20) print(player_hand) in_game = True while player_hand.get_value() < 21: ans = input("Hit or stand? (h/s) ") if ans == "h": player_hand.add_card(d.deal_card()) print(player_hand) if player_hand.get_value() > 21: print("You lose") in_game = False else: print("You stand!") break print("=" * 20) if in_game: while dealer_hand.get_value() < 17: dealer_hand.add_card(d.deal_card()) print(dealer_hand) if dealer_hand.get_value() > 21: print("Dealer bust") in_game = False if in_game: if player_hand.get_value() > dealer_hand.get_value(): print("You win") else: print("Dealer win")
def create_hand(self): """ pop 5 cards from self.cards Returns ------- my_hand : Hand instance """ print("card len") print(len(self.cards)) my_hand = Hand() for index in range(5): my_hand.add_card(self.cards.pop()) print("card len") print(len(self.cards)) print("hand len") print(len(my_hand.cards)) return my_hand
def play(): deck = Deck() deck.shuffle() player_hand = Hand() player_hand.add_card(deck.deal()) player_hand.add_card(deck.deal()) player_chip = Chip() take_bet(player_chip) dealer_hand = Hand() dealer_hand.add_card(deck.deal()) dealer_hand.add_card(deck.deal()) show_card(player_hand, dealer_hand) while playing: hit_or_stand(deck, player_hand) show_card(player_hand, dealer_hand) if player_hand.value > 21: player_busted(player_hand, dealer_hand, player_chip) break if player_hand.value <= 21: while dealer_hand.value < 17: hit_hand(deck, dealer_hand) if dealer_hand.value > 21: dealer_busted(player_hand, dealer_hand, player_chip) elif dealer_hand.value > player_hand.value: dealer_won(player_hand, dealer_hand, player_chip) elif dealer_hand.value < player_hand.value: player_won(player_hand, dealer_hand, player_chip) else: push(player_hand, dealer_hand) print('player total chips are at {}'.format(player_chip.total))
class Player(): """Classe do jogador""" #ATTRIBUTES def __init__(self, chips = 0): self.chips = Chips(chips) self.hand = Hand() #METHODS def take_card(self, deck, num_cards = 1): for num in range(0,num_cards): self.hand.add_card(deck.deal()) def make_bid(self): while True: try: print(f"Total de fichas: {self.chips.total}") bid = int(input("Qual a sua aposta? ")) if bid > self.chips.total: raise OverQuantityError() elif bid == 0: raise ZeroBidError() else: self.chips.bet = bid except ValueError: print("\nInsira um número inteiro") continue except OverQuantityError: print("\nQuantidade de fichas indisponível") continue except ZeroBidError: print("\nAposta deve ser maior que 0") continue else: self.chips.bet = bid break def print_hand(self): print("\n=== PLAYER'S HAND ===\n") self.hand.print_hand()
def main(): from Hand import Hand a = [1,2,3,1,2,3,4] print "Length of LIST A is:\t{}".format(len(a)) print "Original list:\t{}\n".format(a) print "Item at position 0:\t{}\n".format(a[0]) # remoove position 0 or the 1st position b = a[0] a.remove(b) print "Updated Length of LIST A is:\t{}".format(len(a)) print "Print the new list:\t{}\n".format(a) #remove the last items b = a[len(a)-1] a.remove(b) print "\n....Remove the last item in the list....\n" print "Updated Length of LIST A is:\t{}".format(len(a)) print "Print the new list:\t{}\n".format(a) card1 = Card("Clubs", "6") card2 = Card("Diamonds", "6") card3 = Card("Hearts", "6") card4 = Card("Spades", "6") card5 = Card("Clubs", "10") hand = Hand() hand.add_card(card1) hand.add_card(card2) hand.add_card(card3) hand.add_card(card4) hand.add_card(card5) print "Number of cards in the Hand LIST:\t{}\n".format(hand.get_number_of_cards()) print "\n...Printing hand via the get_cards() method.....\n" for card in hand.get_cards(): card.print_card() print "\n...Printing hand via the print_hand() method.....\n" hand.print_hand() print "\n.....Next test --> remove card test .....\n" card = hand.remove_card(2) card.print_card() print "\nUpdated Number of cards in the Hand LIST:\t{}\n".format(hand.get_number_of_cards()) print "\n...Printing hand via the print_hand() method.....\n" hand.print_hand() hand.clear() print "\nUpdated Number of cards in the Hand LIST:\t{}\n".format(hand.get_number_of_cards())
def one_round(self): player_to_bets = {} player_to_hands = {} hands_already_done = set() hand_to_double_down = set() insurance_players = dict() busted_hands = set() self.get_bets(player_to_bets) self.print_bets(player_to_bets) current_deck = Deck(self.NUM_DECKS) for player in self.used_player_names: if player not in self.players_with_no_money: # draws the first card for players card_drew = current_deck.draw() new_hand = Hand() new_hand.add_card(card_drew) player_to_hands[player] = [new_hand] dealer_first_card = current_deck.draw( ) # draws the first card for the dealer dealer_hand = Hand() dealer_hand.add_card(dealer_first_card) for player in self.used_player_names: if player not in self.players_with_no_money: # draws the second card for players card_drew = current_deck.draw() player_to_hands[player][0].add_card(card_drew) dealer_second_card = current_deck.draw( ) # draws the second card for dealer dealer_hand.add_card(dealer_second_card) dealer_black_jack = self.get_final_score( dealer_hand) == self.INT_BLACKJACK black_jacks = set() os.system('cls' if os.name == 'nt' else 'clear') self.print_all_hands(player_to_hands) self.print_dealer_hand(dealer_hand, True) if dealer_first_card.get_denomination() == "A": self.ask_for_insurance(insurance_players, player_to_bets) for player in self.used_player_names: if player not in self.players_with_no_money: for hand in player_to_hands[player]: if hand not in hands_already_done: self.make_move(player, hand, current_deck, player_to_hands, black_jacks, None, hand_to_double_down, busted_hands, player_to_bets, hands_already_done, True) dealer_bust = self.dealer_move(dealer_hand, current_deck) os.system('cls' if os.name == 'nt' else 'clear') print( "Final hands (After Dealer has played, so if you busted or blackjacked they still played)" ) self.print_all_hands(player_to_hands) self.print_dealer_hand(dealer_hand, False) self.end_round(player_to_hands, player_to_bets, hand_to_double_down, insurance_players, dealer_black_jack, black_jacks, dealer_bust, dealer_hand, busted_hands)
class Player: def __init__(self, name): self.hand = Hand() self.name = name def take_card(self, card): self.hand.add_card(card) def get_score(self): return self.hand.get_value() def has_busted(self): return self.hand.get_value() > 21 def has_high_aces(self): return self.hand.get_high_aces() > 0 def adjust_for_ace(self): self.hand.adjust_for_ace() def show_some(self): last_card = self.hand.get_cards()[-1] print(f"\n{self.name}'s Card") print('================') print(f'{last_card.rank} of {last_card.suit}') print('================\n') def show_all(self): cards = self.hand.get_cards() print(f"\n{self.name}'s Cards") print('================') for index, card in enumerate(cards, start=1): print(f'Card {index}:') print(f'{card.rank} of {card.suit}') print('================\n') def reset_hand(self): self.hand = Hand()
def new_game(): # создаем колоду d = Deck() # задаем "руки" для игрока и дилера player_hand = Hand("Player") dealer_hand = Hand("Dealer") # сдаем две карты игроку player_hand.add_card(d.deal_card()) player_hand.add_card(d.deal_card()) # сдаем одну карту дилеру dealer_hand.add_card(d.deal_card()) print (dealer_hand) print ("="*20) print (player_hand) # Флаг проверки необходимости продолжать игру in_game = True # набирать карты игроку имеет смысл только если у него на руке меньше 21 очка while player_hand.get_value() < 21: ans = input("Hit or stand? (h/s) ") if ans == "h": player_hand.add_card(d.deal_card()) print(player_hand) # Если у игрока перебор - дилеру нет смысла набирать карты if player_hand.get_value() > 21: print("You lose") in_game = False else: print("You stand!") break print("=" * 20) if in_game: # По правилам дилер обязан набирать карты пока его счет меньше 17 while dealer_hand.get_value() < 17: dealer_hand.add_card(d.deal_card()) print(dealer_hand) # Если у дилера перебор играть дальше нет смысла - игрок выиграл if dealer_hand.get_value() > 21: print("Dealer bust") in_game = False if in_game: # Ни у кого не было перебора - сравниваем количество очков у игрока и дилера. # В нашей версии если у дилера и игрока равное количество очков - выигрывает казино if player_hand.get_value() > dealer_hand.get_value(): print("You win") else: print("Dealer win")
def make_move(self, player, player_hand, curr_deck, player_to_hands, black_jacks, split_denom, hand_to_double_down, busted_hands, player_to_bets, hands_already_done, can_blackjack): hand_is_over = False can_black_jack = can_blackjack while not hand_is_over: # while the hand is still playable (IE the hand has not bust) options = [self.INT_STAND, self.INT_HIT] options_str = [str(self.INT_STAND), str(self.INT_HIT)] can_split = False current_cards_in_hand = player_hand.get_cards() if len( current_cards_in_hand ) == 2: # Determines whether the player can double down and/or split if self.map_player_to_money[player] >= player_to_bets[player]: options.append(self.INT_DOUBLE) options_str.append(str(self.INT_DOUBLE)) if current_cards_in_hand[0].get_denomination( ) == current_cards_in_hand[1].get_denomination(): if split_denom is not None: if split_denom == current_cards_in_hand[0].get_denomination() and \ self.map_player_to_money[player] >= player_to_bets[player]: can_split = True elif self.map_player_to_money[player] >= player_to_bets[ player]: can_split = True if can_split: options.append(self.INT_SPLIT) options_str.append(str(self.INT_SPLIT)) # prints the current hand of the player and score as well asl the choices players can take. ask_for_move_string = player + ", you have several options for your hand of " for card in current_cards_in_hand: ask_for_move_string += card.get_non_graphic_string() if card != current_cards_in_hand[-1]: ask_for_move_string += " and " ask_for_move_string += ". It's current value is " + str(self.get_final_score(player_hand)) + ". You can " \ "either " for i in range(len(options)): number = options[i] ask_for_move_string += self.all_moves[ number] + " (enter " + str(number) + ")" if i != len(options) - 1: ask_for_move_string += ", " choice = input(ask_for_move_string + ": ") while choice not in options_str: # Repeatedly prompts user for choice until they enter a valid choice print( "That is not a valid choice, please enter a valid choice!") choice = input(ask_for_move_string + ": ") choice = int(choice) if choice == self.INT_STAND: # if player stands hand_is_over = True if self.INT_BLACKJACK in player_hand.get_scores( ) and can_black_jack: black_jacks.add(player_hand) hands_already_done.add(player_hand) elif choice == self.INT_HIT: # if player hits next_card = curr_deck.draw() player_hand.add_card(next_card) self.print_single_hand(player_hand) new_score = self.get_final_score(player_hand) if new_score == 0: busted_hands.add(player_hand) hand_is_over = True hands_already_done.add(player_hand) elif choice == self.INT_SPLIT: # if player splits hand_1 = Hand() hand_2 = Hand() hand_1.add_card(current_cards_in_hand[0]) hand_2.add_card(current_cards_in_hand[1]) new_card_1 = curr_deck.draw() new_card_2 = curr_deck.draw() hand_1.add_card(new_card_1) hand_2.add_card(new_card_2) player_to_hands[player].remove(player_hand) player_to_hands[player].append(hand_1) player_to_hands[player].append(hand_2) self.print_all_hands(player_to_hands) self.map_player_to_money[player] -= player_to_bets[player] # Player's hand is split into two hands, then each hand is played out by a recursive call to make_move self.make_move(player, hand_1, curr_deck, player_to_hands, black_jacks, current_cards_in_hand[0].get_denomination(), hand_to_double_down, busted_hands, player_to_bets, hands_already_done, False) self.make_move(player, hand_2, curr_deck, player_to_hands, black_jacks, current_cards_in_hand[0].get_denomination(), hand_to_double_down, busted_hands, player_to_bets, hands_already_done, False) hand_is_over = True else: # choice is to double down next_card = curr_deck.draw() player_hand.add_card(next_card) hand_to_double_down.add(player_hand) new_score = self.get_final_score(player_hand) if new_score == 0: busted_hands.add(player_hand) hand_is_over = True self.map_player_to_money[player] -= player_to_bets[player] hands_already_done.add(player_hand) can_black_jack = False
class Player(object): ''' Player Constructor Set the players name, initializes the players hand, initializes list of hands, initializes players' bank roll and bet amount. @param: name @return: NONE ''' def __init__(self, name): self.__name = name self.__current_hand = Hand() self.__list_of_hands = [] self.__poker_hands = [] self.__bank_roll = 0 self.__bet_amount = 0 self.__current_hand_size = 0 # Poker Hand Utility object which evaluates any 5 card hand self.__poker_hand_utility = PokerHandUtility() ''' Players Destructor clears the list of hands LIST @param: self @return: NONE ''' def __del__(self): del self.__list_of_hands[:] def get_poker_hand_utility(self): return self.__poker_hand_utility def get_poker_hands(self): return self.__poker_hands ''' add_card Add input new card object to the Players' hand @param: new_card - input Card object @return: NONE ''' def add_card(self, new_card): self.__current_hand.add_card(new_card) self.__current_hand_size = self.__current_hand_size + 1 ''' add_funds Adds the specified amount to the player's funds @param: new_funds: The amount to be added to the player's funds @return: NONE ''' def add_funds(self, new_funds): self.__bank_roll = self.__bank_roll + float(new_funds) ''' remove_funds Removes the specified amount from the player's funds @param: amount_of_funds: The amount to be removed from the player's funds @return: NONE ''' def remove_funds(self, amount_of_funds): # probably should check to make sure the player as enough funds in their # bank roll before blindly deduction cash from the account. # we dont want our account to go in the red or become negative self.__bank_roll = self.__bank_roll - float(amount_of_funds) ''' get_funds Retrieves the player's funds @param: self @return: int: The integer amount of funds the player has ''' def get_funds(self): return self.__bank_roll ''' get_bet_amount Retrieves the bet amount @param: self @return: int: The amount of money the player bet ''' def get_bet_amount(self): return self.__bet_amount ''' set_bet_amount Sets the bet amount @param: bet_amount : The amount of money the player is betting @return: NONE ''' def set_bet_amount(self, bet_amount): self.__bet_amount = bet_amount ''' get_name Retrieves the player's name @param: self @return string: The player's name ''' def get_name(self): return self.__name ''' five_card_stud_hand get_hand Retrieves the player's current hand @param: self @return: LIST : The player's hand ''' def get_hand(self): #return self.__current_hand.get_cards() return self.__current_hand def get_current_hand_size(self): return len(self.__current_hand.get_cards()) def show_hand(self): if self.__current_hand.get_cards(): for card in self.__current_hand.get_cards(): card.print_card() else: print "PLAYERS HAND IS EMPTY NO CARDS ARE IN THE HAND\n" def show_hand_by_index(self): ''' The pythonic way to do it is from the PEP 8 style guide: https://stackoverflow.com/questions/53513/how-do-i-check-if-a-list-is-empty ''' if self.__current_hand.get_cards(): index = 0 for card in self.__current_hand.get_cards(): card.print_card_by_index(index) index = index + 1 else: print "PLAYERS HAND IS EMPTY NO CARDS ARE IN THE HAND\n" def show_hand_ver1(self): if self.__current_hand.get_cards(): idx = 0 for card in self.__current_hand.get_cards(): self.__current_hand.get_cards()[idx].print_card() idx = idx + 1 else: print "PLAYERS HAND IS EMPTY NO CARDS ARE IN THE HAND\n" def get_card_at_index(self, position): return self.__current_hand[position] def show_hand_single_card_format(self): if self.__current_hand.get_cards(): for card in self.__current_hand.get_cards(): card.print_single_card() else: print "PLAYERS HAND IS EMPTY NO CARDS ARE IN THE HAND\n" def draw(self, deck): self.__current_hand.add_card(deck.draw_card()) return self ''' reset Resets the player's bet and hand @param: self @return: NONE ''' def reset(self): # reset the bet amount self.__bet_amount = 0 # clear the players' current hand self.__current_hand.clear() ''' get_list_of_players_hands Retrieves the players' history of list of hands @param: self @return: LIST : the list of players previous hands while playing poker ''' def get_list_of_players_hands(self): return self.__list_of_hands ''' add_hand_to_list_of_players_hands Add the latest current hand to the list of players hands This can be used to study the players hands later @param: self @param: list : five_stud_hand @return: NONE ''' def add_hand_to_list_of_players_hands(self, five_stud_hand): self.__list_of_hands.append(five_stud_hand) def get_list_of_players_hands_size(self): return len(self.__list_of_hands) ''' This was done to make the Card class iterable ''' def __eq__(self, other): return self.__dict__ == other.__dict__ ''' toString method @return - String respresentation in a customized card hand order ''' def toString(self): return "Hand: \t\t{} Test\t| {} | {} | {} | {}".format( self.__current_hand.get_cards()[0].print_card(), self.__current_hand.get_cards()[1].print_card(), self.__current_hand.get_cards()[2].print_card(), self.__current_hand.get_cards()[3].print_card(), self.__current_hand.get_cards()[4].print_card())
from Global import globals from CommonFuncs import * from Deck import Deck from Hand import Hand from Chips import Chips while True: print('Welcome to black jack !') deck = Deck() deck.shuffle() player_hand = Hand() player_hand.add_card(deck.deal()) player_hand.add_card(deck.deal()) dealer_hand = Hand() dealer_hand.add_card(deck.deal()) dealer_hand.add_card(deck.deal()) player_chips = Chips() take_bet(player_chips) show_some(player_hand, dealer_hand) while globals.playing: hit_or_stand(deck, player_hand) show_some(player_hand, dealer_hand) if player_hand.value > 21:
class GameBoard: MYSTIC_INDEX = 6 HEAVY_INDEX = 7 CULTIST_INDEX = 8 def __init__(self): self._mystics = DeckFactory.build_mystic_deck() self._heavies = DeckFactory.build_heavy_deck() self._deck = DeckFactory.build_center_deck() self._board = Hand() self._cultist = Cultist() for _ in range(6): self.draw_card() def draw_card(self): card = self._deck.draw_card() if(card == None): return self._board.add_card(card) def get_card(self, index): self.assert_is_valid_index(index) if(index == self.MYSTIC_INDEX): return self._mystics.peek() if(index == self.HEAVY_INDEX): return self._heavies.peek() if(index == self.CULTIST_INDEX): return self._cultist return self._board.get_card_at_index(index) def acquire_card(self, index): self.assert_is_valid_index(index) if(index == self.MYSTIC_INDEX): return self.acquire_mystic() if(index == self.HEAVY_INDEX): return self.acquire_heavy() if(index == self.CULTIST_INDEX): self._cultist.acquire() card = self._board.remove_card(index) try: card.acquire() self.draw_card() return card except Exception as e: self._board.add_card_at_index(card, index) raise e def acquire_heavy(self): card = self._heavies.draw_card() return card def acquire_mystic(self): card = self._mystics.draw_card() return card def defeat_card(self, index): self.assert_is_valid_index(index) if(index == self.CULTIST_INDEX): return self._cultist.defeat() card = self._board.remove_card(index) try: honor = card.defeat() self.draw_card() return honor except Exception as e: self._board.add_card_at_index(card, index) raise e def print(self): for i in range(self._board.get_size()): print(str(i) + ". " + self._board.get_card_at_index(i).get_name() + " - " + str(self._board.get_card_at_index(i).get_cost())) print(str(GameBoard.MYSTIC_INDEX) + ". " + self._mystics.peek().get_name()) print(str(GameBoard.HEAVY_INDEX) + ". " + self._heavies.peek().get_name()) print(str(GameBoard.CULTIST_INDEX) + ". " + self._cultist.get_name()) def assert_is_valid_index(self, index): if(self.is_valid_index(index) == False): raise Exception("Invalid index.") def is_valid_index(self, index): if(index == GameBoard.MYSTIC_INDEX): return True if(index == GameBoard.HEAVY_INDEX): return True if(index == GameBoard.CULTIST_INDEX): return True; if(index < 0): return False if(index >= self._board.get_size()): return False return True
Play = True while Play == True: player = Hand() dealer = Hand() if player_chips.total == 0: print('Sorry, you have lost all your chips. Please come back later.') break bet = take_bet(player_chips.total) playing = True if player_chips.total < bet: print( 'Insufficient chips, please make a lower bet. Your chip balance is {}' .format(player_chips.total)) bet = take_bet() player.add_card(deck.deal(), values) player.add_card(deck.deal(), values) dealer.add_card(deck.deal(), values) dealer.add_card(deck.deal(), values) # show_some(player, dealer) while playing: show_some(player, dealer) playing = hit_or_stand(deck, player, values) if player.aces != 0: while True: try: ace_decision = input( 'Would you like to adjust your ace? (y/n) ') except:
def create_player_hand(): global player_hand player_hand = Hand() player_hand.add_card(deck.deal()) player_hand.add_card(deck.deal())
from Hand import Hand from Deck import Deck print 'Welcome to Casino Royale!' new_deck = Deck() player = Hand() dealer = Hand() player.add_card(new_deck.draw_card()) player.add_card(new_deck.draw_card()) dealer.add_card(new_deck.draw_card()) # Is this even correct for declaring a variable to avoid problems with scope? bet = None # Could just do player.balance here but is it better to use getters and setters in thie case? if player.get_balance() > 0: bet = input('Bet Amount: ') if bet > player.get_balance(): print 'Bet has been adjusted to ' + str(player.get_balance()) + ' due to insufficient funds.' bet = player.get_balance() else: print 'New Balance: ' + str(player.balance - bet) print 'Your Bet: ' + str(bet)
class BlackJack: ''' Creates and manages the game.Check for the condition of the game whether player wins, loss or busted. ''' def __init__(self): self.moves = ["hit","stand","double","split"] self.deck = Deck() self.player = Player() self.player_hand = [] self.player_hand.append(Hand()) self.dealer_hand = Hand() def place_bet(self): if self.player.get_fund() < 1: print("Sorry,not enough fund to play. Start a new game.") input() sys.exit(0) print("You have {0:.2f}".format(self.player.get_fund())+" chips.") while True: try: bet = int(input("Place your bet: ")) if bet < 1: bet = int(input("Bet must be at least 1 chip.Try Again!!! ")) elif self.player.get_fund() < bet: bet = int(input("Not enough chips.Try Again!!! ")) else: break except ValueError: print("Doesn't looks like valid bet.Try Again!!!") self.player.current_bet(bet) def play_hit(self,current_hand, hand_index = 0): new_card = self.deck.deal_card() current_hand.add_card(new_card) print(new_card.get_rank()+" of " + new_card.get_suit()) if current_hand.get_value() > 21: self.player.busted[hand_index] = True def play_double(self): if len(self.player_hand[0].hand) == 2 and not self.player.is_split(): #Allowed only in initial hands try: double_bet = int(input("Enter the double bet amount: ")) except ValueError: double_bet = int(input("Please enter the valid integer positive number: ")) if double_bet <= self.player.current_fund() and double_bet <= self.player.bet[0]: self.player.current_bet(double_bet) new_card = self.deck.deal_card() self.player_hand[0].add_card(new_card) print(new_card.get_rank()+" of " + new_card.get_suit()) if self.player_hand[0].get_value() > 21: self.player.busted[0] = True elif self.player_hand[0].get_value == 21: self.player.blackjack = True else: pass else: print("You should have enough chips and the double cannot be more then 100% of original bet.Try Again!!") else: print("You can only Double Down initially when not playing split.Try other move!!") def play_split(self): hand_cards = self.player_hand[0].get_hand() if len(hand_cards) == 2 and hand_cards[0].get_rank() == hand_cards[1].get_rank(): if self.player.get_bet() <= self.player.current_fund(): self.player.split = True self.player_hand.append(Hand()) # create new hand to store split hand print("Player's split on " + str(hand_cards[0].get_rank())) remove_card = self.player_hand[0].remove_card() self.player.current_bet(self.player.get_bet()) self.player_hand[1].add_card(remove_card) for i in range(0,2): print("Play Hand",i+1) self.player_hand[i].add_card(self.deck.deal_card()) while True: print("Hand: ",end="") self.player_hand[i].print_cards() player_input = input("Player's play:").lower() if player_input not in ["hit","stand"]: print("Only Hit and Stand is valid after splitting.") player_input = input("Enter your play :").lower() elif player_input == "stand": break else: pass self.play_hit(self.player_hand[i],i) if self.player.is_busted(i): break else: print("\nNot enough fund to split.Try other move!!!") else: print("\nSplitting is only allowed on initial hand when cards rank are equal.") def player_move(self): self.player_hand[0].add_card(self.deck.deal_card()) self.dealer_hand.add_card(self.deck.deal_card()) self.player_hand[0].add_card(self.deck.deal_card()) self.dealer_hand.add_card(self.deck.deal_card()) print("\n") print("Player Hand: ",end="") self.player_hand[0].print_cards() print("Dealer Hand: ",end="") self.dealer_hand.print_dealer_initial_hand() if self.player_hand[0].get_value() == 21: self.player.blackjack = True return print("\n\nPlayer's Turn:") while True: print("Hand: ",end="") self.player_hand[0].print_cards() player_input = input("Player's play:").lower() if player_input not in self.moves: print("Enter valid moves: "+",".join(self.moves)) if player_input == 'hit': self.play_hit(self.player_hand[0]) if self.player.is_busted(): break elif player_input == 'double': # Double is not allowed after split self.play_double() break #Just one card be drawn after placing double bet elif player_input == 'split': if not self.player.is_split(): # Split is not allowed in the split hand itself. self.play_split() break else: print("\nSplitting is only allowed on initial hand when cards are equal.!!!") else: break def dealer_move(self): if not self.player.is_busted(): print("\nDealer's Turn:") while True: print("Hand :",end="") self.dealer_hand.print_cards() dealer_value = self.dealer_hand.get_value() if dealer_value < 17: print("\nDealer's Play: Hit") new_card = self.deck.deal_card() print(new_card.get_rank()+" of " + new_card.get_suit()) self.dealer_hand.add_card(new_card) # Dealer Hits on soft 17 elif len(self.dealer_hand.hand) == 2 and dealer_value == 17: print("\nDealer's Play: Hit on Soft 17") new_card = self.deck.deal_card() print(new_card.get_rank()+" of " + new_card.get_suit()) self.dealer_hand.add_card(new_card) elif dealer_value >= 17 and dealer_value <= 21: print("Dealer's Play: Stand") break else: break def result(self): dealer_val = self.dealer_hand.get_value() player_val = [] player_val.append(self.player_hand[0].get_value()) dealer_blackjack = False if len(self.dealer_hand.hand) == 2 and dealer_val == 21: dealer_blackjack = True for i in range(0,2): print("\n") if i == 0 and self.player.is_split(): print("Player's Hand 1: ") elif i == 1 and not self.player.is_split(): break elif i == 1 and self.player.is_split(): print("Player's Hand 2: ") player_val.append(self.player_hand[i].get_value()) else: pass if self.player.is_busted(i): print("Player's Hand: ",end="") self.player_hand[i].print_cards() print("Player Busted -- Dealer Wins!!!") self.player.remaining_fund() elif self.player.is_blackjack() and not dealer_blackjack: print("Player's Hand: ",end="") self.player_hand[i].print_cards() print("!!BLACKJACK!!") print("Dealer's Hand: ",end="") self.dealer_hand.print_cards() if dealer_val > 21: print("Dealer Busted!!") self.player.add_fund() elif dealer_val > 21: print("Dealer Hand: ",end="") self.dealer_hand.print_cards() print("Dealer Busted -- Player Wins!!!") self.player.add_fund() elif player_val[i] > dealer_val: print("Player's Hand: ",end="") self.player_hand[i].print_cards() print("Dealer's Hand: ",end="") self.dealer_hand.print_cards() print("Player Win!!!") self.player.add_fund() elif player_val[i] == dealer_val and not dealer_blackjack : print("Player's Hand: ",end="") self.player_hand[i].print_cards() print("Dealer's Hand: ",end="") self.dealer_hand.print_cards() print("Points Tie.PUSH") else: print("Player's Hand: ",end="") self.player_hand[i].print_cards() print("Dealer's Hand: ",end="") self.dealer_hand.print_cards() print("Dealer Win!!!",end="") if dealer_blackjack: print("Dealer's BLACKJACK") self.player.remaining_fund() print("Player current Status:") print("Player has {0:.2f} chips\n".format(self.player.get_fund()))
print(player) print("\n\n") player.bet_amount(take_bet(player.balance)) print("Giving cards....") time.sleep(1.5) #Start of the game. Card is give to player and dealer #Player first Card player.hand.add_card(deck.give_card()) Utility.display_card(dealer, player) #delay 2 secs time.sleep(2) #Dealer First Card dealer.add_card(deck.give_card()) Utility.display_card(dealer, player) time.sleep(2) #Player Second Card player.hand.add_card(deck.give_card()) Utility.display_card(dealer, player) #time.sleep(3) #Dealer Second Card but will not be shown dealer.add_card(deck.give_card()) Utility.display_card(dealer, player) #Ask the player to hit or stand take_card = False
while True: print("How many chips would you like to bet? (1-100):") # Check if the chips count enetered is an integer valules and enough count to play chip_count = Error().chip_error(total_chips.total) player = Hand() dealer = Hand() card_in_game = Deck(Card().all_card) # Use random function to generate cards for the player and dealers # First card for the dealer random_choice = random.choices(card_in_game.cards) # Pop by index for the card in game card_in_game.Deck_pop(card_in_game.find_idx(random_choice[0])) dealer.add_card(random_choice, card_in_game.cart[random_choice[0][0]]) # second card for the dealer random_choice = random.choices(card_in_game.cards) card_in_game.Deck_pop(card_in_game.find_idx(random_choice[0])) dealer.add_card(random_choice, card_in_game.cart[random_choice[0][0]]) print( "-------------------------------------------------------------------------------------------" ) print("Dealer has cards: <<Card1 Hidden>> ", dealer.Card_in_hand[1][0]) print( "-------------------------------------------------------------------------------------------" ) # Generate 2 cards for player using random function random_choice = random.choices(card_in_game.cards)
def create_dealer_hand(): global dealer_hand dealer_hand = Hand() dealer_hand.add_card(deck.deal()) dealer_hand.add_card(deck.deal())
class Player: """Player.""" def __init__(self): """Constructor.""" self.bank = Bank() self.hand = Hand() self.name = 'Player' def take_bet(self): """Take the player's bet.""" bet = 0 while True: buffer = input('How much do you want to bet? ') try: bet = int(buffer) if bet < 0: print('Negative bets are not allowed. Try again.') elif bet > self.bank.total: print('You do not have enough for that bet. Try again.') else: break except: print('Invalid input. Try again.') return bet def hit_or_stand(self): """Query if the player wants more cards.""" while True: buffer = input('Do you want another card (Y/N)? ') bet = False try: response = buffer[0].upper() if response == 'Y': bet = True break elif response == 'N': bet = False break else: print('Please type Y or N. ') except: print('Invalid input. Try again.') return bet def run_unit_test(self): """Run a unit test.""" max_iters = 5 iters = 0 while iters < max_iters and self.bank.total > 0: iters += 1 self.hand.clear() bet = self.take_bet() if bet < 0: print('Player is out of money. Game over.') break self.bank.bet = bet while True: hit = self.hit_or_stand() if hit: s = random.choice(Card.suits) r = random.choice(Card.ranks) self.hand.add_card(Card(s, r)) print(f'Hand: {self.hand.str_some()}') else: print(f'Player total = {self.hand.value()}') print(f'Final Hand: {self.hand.str_all()}') break won = False if self.hand.value() > 21: won = False else: won = random.choice([False, True]) if won: self.bank.win_bet() print(f'Player won. Bank={self.bank.total}') else: self.bank.lose_bet() print(f'Player lost. Bank={self.bank.total}')
blackjack = False player_bust = False dealer_bust = False # Create & shuffle the deck deck = Deck() deck.shuffle() player = Hand() dealer = Hand() # Prompt the Player for their bet take_bet(player_chips) print() # deal cards player.add_card(deck.deal()) dealer.add_card(deck.deal()) player.add_card(deck.deal()) dealer.add_card(deck.deal()) # check for blackjack if player.value == 21 or dealer.value == 21: playing = False blackjack = True print("Blackjack!") show_all(player, dealer) while playing and player.value < 21: # Show cards (but keep one dealer card hidden) show_some(player, dealer)
class Player(object): """Player will represent the behavior and data of a player""" # These will be the class variables. def __init__(self, money): self.__money = money self.__hand = Hand() self__bet = 0 def get_hand(self): """Return the entire hand""" return self.__hand def get_value_of_hand(self): """Return the value of the hand""" return self.__hand.get_value_of_hand() def get_number_of_cards(self): """Return the number of cards""" return self.__hand.get_number_of_cards() def set_bet(self, bet): """Set the bet for this player""" self.__bet = bet def get_bet(self): """Get the bet for this player""" return self.__bet def get_money(self): """Get the Money for this player""" return self.__money def set_money(self, money): """set the amount of money the player should have""" self.__money = money def recieve_new_card(self, card): """Should take the new Card and add it to the hand""" self.__hand.add_card(card) def want_card(self): """Ask this player if they would like to get another card Also check to see if the player has busted, because if they have they can not recieve any new cards. """ # print self.__hand.get_value_of_hand() if self.__hand.get_value_of_hand() > 21: print "You have busted" choice = False else: choice = raw_input("Would you like another card? (Please Enter True or False\n") if choice == "True": choice = True else: choice = False return bool(choice) def betting(self): self.__bet = input("What is the players bet\n") def ready_for_next_hand(self): """Get the Player ready for the next hand.""" self.__hand = Hand() self.__bet = 0