Ejemplo n.º 1
0
class Game:
    """
  This is the main controller for Black Jack. It handles the creation of the Deck, Dealer, and User.
  As well as managing the main parts of the game flow.
  """
    def __init__(self, print_func=print, input_func=input):
        """
    This is where most of the basic game set up should take place. Namely the creation of the deck as well as the dealer. For now we can also add the player.
    In: None
    Exceptions: None
    Out: None
    """
        # Variables to control both the users starting bank as well as their goal
        self.starting_bank = 100
        self.score_goal = 250
        self.endless = False

        # Override functions so you can create a wrapper around the program
        self._print = print_func
        self._input = input_func

        # Create a new deck of cards
        self.deck = Deck(deck_count=2)

        # Add the players that the game cares about
        self.dealer = Dealer()
        self.user = User(starting_bank=self.starting_bank)
        self.round = 0

    def difficulty_level(self):
        valid_easy_responses = {'e', 'easy'}
        valid_hard_responses = {'h', 'hard'}
        while True:
            level_response = self._input(
                'Which difficulty? \nEasy: start with 100 chips, and goal is 250 chips \nHard: start with 50 chips, and goal is 500 chips \nPress (e) or (h): '
            )

            if level_response.lower() in valid_easy_responses:
                self.user = User(starting_bank=100)
                self.score_goal = 250
                break

            if level_response.lower() in valid_hard_responses:
                self.user = User(starting_bank=50)
                self.score_goal = 500
                break

            self._print('Difficulty must be Easy or Hard')

    def iterate_round(self):
        """
    Increment the round number
    In: None
    Out: None
    """
        self.round += 1

    def shuffle_deck(self):
        """
    Shuffles decks of cards
    In: None
    Out: None
    """
        if self.deck.deck_size() / 4 > self.deck.cards_remaining():
            self.deck.shuffle()

    def place_user_bet(self, value):
        """
    Shows current bank, requests bet, handles edge cases
    In: None
    Out: None
    """
        current_bank = self.user.get_bank()

        if value >= 1 and value <= current_bank:
            self.user.place_bet(value)

    def deal(self):
        """
    Deals 2 cards to the user and dealer
    In: None
    Out: None
    """
        for _ in range(0, 2):
            self.user.hit(self.deck.deal())
            self.dealer.hit(self.deck.deal())
        self.save_game()

    def user_hand(self):
        return self.user.hand

    def dealer_hand(self):
        return self.dealer.hand

    def user_hit(self):
        """
    Handles the users decision to either hit and gain a card, or to stay and keep the cards they have.
    In: None
    Out: None
    """
        self.user.hit(self.deck.deal())
        self.save_game()

    def dealer_turn(self):
        """
    Controls the dealers logic if they need to hit again or keep the cards that they already have
    In: None
    Out: None
    """
        while not self.dealer.bust():
            if self.dealer.get_score() < 17:
                self.dealer.hit(self.deck.deal())
            else:
                break

    def calculate_winner(self):
        """
    ** WIP **
    Used to decide if the player or the dealer is the one to win the round
    In: None
    Out: Changes the value in the Player's bank
    """

        if self.user.bust():
            self.user.beat_dealer(False)
            return False

        else:
            if self.user.blackjack() and not self.dealer.blackjack():
                self.user.beat_dealer(True)
                return True

            if not self.user.blackjack() and self.dealer.blackjack():
                self.user.beat_dealer(False)
                return False

            if self.user.get_score() == self.dealer.get_score(
            ) and not self.dealer.bust():

                return None

            result = self.user.get_score() > self.dealer.get_score(
            ) or self.dealer.bust()
            self.user.beat_dealer(result)

            return result

    def reset_hands(self):
        """
    Resets hands of all players to contain no cards
    In: None
    Out: None
    """
        self.user.reset_hand()
        self.dealer.reset_hand()

    def save_game(self):
        """
    Calls on the player and the deck to save their respective cards to the csv files for the notebook.
    In: None
    Exceptions: No Data To Save
    Out: .csv files
    """
        self.user.to_csv()
        self.deck.to_csv()
Ejemplo n.º 2
0
class Game(object):

    def setup(self):
        self.deck = Deck()
        self.player = Player()
        self.dealer = Dealer()
        for _ in range(2):
            self.player.hit(self.deck.next_card())
            self.dealer.hit(self.deck.next_card())

    def player_turn(self):
        player_choice = input("[H]it, [S]tay, or [Q]uit?").lower()
        os.system('clear')

        if player_choice == 'h':
            self.player.hit(self.deck.next_card())
            self.display_info()
            if self.player.hand_value() > 21:
                pass
            else:
                self.player_turn()
        elif player_choice == 's':
            pass
        elif player_choice == 'q':
            sys.exit()
        else:
            self.player_turn

    def dealer_turn(self):
        while self.dealer.hand_value() <= 16:
            self.display_info(True)
            time.sleep(2)
            self.dealer.hit(self.deck.next_card())
    

    def check_for_outcome(self):
        if self.dealer.hand_value() > 21:
            print("Dealer bust! You Win!")
            self.play_again()
        elif self.player.hand_value() > self.dealer.hand_value():
            print("You win!")
        elif self.player.hand_value() < self.dealer.hand_value():
            print("You lose!")
        elif self.player.hand_value() == self.dealer.hand_value():
            print("Push!")

    def check_for_bust(self):
        if self.player.hand_value() > 21:
            print("You bust! You lose!")
            self.play_again()

    def display_info(self,show = False):
        os.system('clear')
        print("Blackjack")
        print("="*20)
        if show:
            print(self.dealer)
        else:
            print(self.dealer.hidden())
        print(self.player)
        print("="*20)
    
    def play_again(self):
        play_again = input("Do you want to play again? [Y]/[N]?").lower()
        if play_again == 'y':
            Game()
        else:
            sys.exit()

    def __init__(self):
        self.setup()
        
        self.display_info()
        self.player_turn()
        self.check_for_bust()
        self.display_info(True)
        self.dealer_turn()
        self.display_info(True)
        self.check_for_outcome()

        self.play_again()
Ejemplo n.º 3
0
class Round:
	"""start a round of blackjack
	Arguments
	----------
	deck : shared deck of cards between classes
	Parameters
	----------
	user : player class controlled by input
	dealer : player class controlled by hit rules
	mxscore : maximum score without busting
	"""
	def __init__(self, deck):
		self.deck = deck
		self.user = User(deck)
		self.dealer = Dealer(deck)
		self.mxscore = 21
		self.deck.shuffle()

	def play(self):
		def deal(self):
			self.user.get_card()
			self.user.get_card()
			self.dealer.get_card()
			print("\nDealer has {0} ??? for a visible total of {1} points".format(str(self.dealer), self.dealer.first_ace()))
			self.dealer.get_card() # Dealer gets 2nd card after first print to keep 2nd card hidden
			print("You have {0} for a total of {1} points".format(str(self.user), self.user.score()))
			print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
			check_blackjack(self)

		def check_blackjack(self):
			if self.dealer.score() == 21:
				print("Dealer has {0} for a total of {1} points".format(str(self.dealer), self.dealer.score()))
				print("Dealer got a Blackjack! You Lose!")
			elif self.user.score() == 21:
				print("You got a Blackjack! You Win!")
			else:
				user_hit(self)

		def user_hit(self):
			while self.user.score() <= 21 and self.user.hit():
				if self.user.score() > 21:
					print("You have {0} for a total of {1} points. \nYOU BUSTED!".format(str(self.user), self.user.score()))
				if self.user.score() <= 21:
					print("You have {0} for a total of {1} points.".format(str(self.user), self.user.score()))
			if self.user.score() <= 21:
				print("You stay with {0} for a total of {1} points.".format(str(self.user), self.user.score()))
				print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
				dealer_hit(self)
				
		def dealer_hit(self):
			print("Dealer has {0} for a total of {1} points.".format(str(self.dealer), self.dealer.score()))
			if self.dealer.score() >= 17:
				print("Dealer stays at {0}".format(self.dealer.score()))
				print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
				compare_score(self)
			while self.dealer.score() < 17:
				print("Dealer Hits")
				self.dealer.hit()
				print("Dealer has {0} for a total of {1} points.".format(str(self.dealer), self.dealer.score()))
				if 17 <= self.dealer.score() <= 21:
					print("Dealer stays at {0}".format(self.dealer.score()))
					print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
					compare_score(self)
				elif self.dealer.score() > 21:
					print("DEALER BUSTED!".format(str(self.dealer), self.dealer.score()))

		def compare_score(self):
			if self.user.score <= self.dealer.score:
				print("The Dealer's {0} beats your {1}. \nYOU LOSE!").format(self.dealer.score(), self.user.score())
			if self.user.score > self.dealer.score:
				print("Your {0} beats the Dealer's {1}. \nYOU WIN!").format(self.user.score(), self.dealer.score())
				
		deal(self)		
Ejemplo n.º 4
0
        # CARD HANDLING STAGE -------------------------------------------------------
        players = [dealer, player1]
        for p in players[:]:
            print(f"{p.name}'s turn ------------------")
            p_decision = (
                input(f"What would {p.name} like to do (hit, stay or split): ")
                if p.name != "Dealer" else decision_generator(
                    p.hand, dealer_card))

            if p.name == "Dealer":
                print(f"Dealer {p_decision}")

            if p_decision.lower() == "hit":
                while p_decision == "hit":
                    dealer.hit(p)
                    print_hand(p)
                    result = get_hands_result(p.hand)

                    if all(i > 21 for i in result):
                        p_decision = "bust"
                        bust.append(p)
                        break
                    if 21 in result:
                        p_decision = "win"
                        break
                    else:
                        # TODO: alter so basic strategy takes into acount dealer_sum not just dealer card
                        p_decision = (input(
                            f"What would {p.name} like to do (hit, stay or split): "
                        ) if p.name != "Dealer" else decision_generator(