Exemple #1
0
class Player(object):
    def __init__(self, chips=100):
        self.chips = chips
        self.hand = Hand()

    def _subtract_chips(self, amt):
        if self.chips >= amt:
            self.chips -= amt
        else:
            raise StandardError("Not enough chips")

    def clear_hand(self):
        self.hand.clear()

    def bet(self, amt):
        self._subtract_chips(amt)

    def add_card(self, card):
        self.hand.add_card(card)
Exemple #2
0
class Game:
    def __init__(self):
        self.deck = Deck()
        self.dealer_hand = Hand()
        self.player_hand = Hand()
        self.deck.shuffle()

    def reset(self):
        self.deck.reset()
        self.dealer_hand.clear()
        self.player_hand.clear()
        self.deck.shuffle()

    def ask_user(self, prompt, valid_inputs):
        """
        Prompt the user with a question, and repeat until they give a valid answer
        For example, `self.ask_user('Choose:', ['hit', 'stay'])` will display:
          Choose: (hit/stay)
        and loop until the user types either hit or stay

        :param prompt: The question to display
        :param valid_inputs: the valid answers
        :return: one of the valid answers given
        """
        joined_inputs = '/'.join(valid_inputs)
        prompt_string = f'{prompt} ({joined_inputs})  '
        result = input(prompt_string)
        while result not in valid_inputs:
            print('Invalid input, please try again')
            result = input(prompt_string)
        return result

    def play_hand(self):
        # First, make sure everything is cleared out to play the hand
        self.reset()

        # Setup and deal two cards to each player
        self.player_hand.add_card(self.deck.draw())
        self.dealer_hand.add_card(self.deck.draw())
        self.player_hand.add_card(self.deck.draw())
        self.dealer_hand.add_card(self.deck.draw())

        # Print the game state out to the user
        self.display_game()

        # Checks for natural 21
        if self.player_hand.score() == 21:
            print('You Win!')
            return

        # Start by asking the user if they want to hit or stay
        user_input = self.ask_user('Choose:', ['hit', 'stay'])

        # Loop so long as the user is not busted and they have not entered "stay"
        while user_input != 'stay' and not self.player_hand.is_bust():
            # Deal the player another card
            self.player_hand.add_card(self.deck.draw())

            # Print out the game state again
            self.display_game()

            # Check if the user is busted and if so, return because the hand is done
            if self.player_hand.is_bust():
                print('Bust! You Lose!')
                return
            # Ask the user again if they'd like to hit, which determines if the loop will run again
            user_input = self.ask_user('Choose:', ['hit', 'stay'])

        # If the player hasn't busted, dealer plays
        # From here on out we don't mask the dealer's cards beyond the first
        self.display_game(dealer_hidden=False)
        # Dealers hit on 16 and stay on 17, so that's the condition for our loop
        while self.dealer_hand.score() < 17:
            print('Dealer hits')
            # Dealer draws a card
            self.dealer_hand.add_card(self.deck.draw())
            # Print out the game state again
            self.display_game(dealer_hidden=False)

            # Check if the dealer has busted and if so, return out of this function
            if self.dealer_hand.is_bust():
                print('Dealer busted! You Win!')
                return

        # Neither player has busted, who wins?

        if self.player_hand.score() > self.dealer_hand.score():
            print('You Win!')
        else:
            # Dealer wins in case of a tie
            print('You Lose!')

    def display_game(self, dealer_hidden=True):
        """
        Print out the game state to the console
        :param dealer_hidden: If cards in the dealers hand beyond the first should be "face down"
        :return: None
        """
        print('Your hand:')
        print(self.player_hand.display())
        print(f'Score: {self.player_hand.score()}')
        print('Dealer\'s hand:')
        print(self.dealer_hand.display(dealer_hidden))
        print()

    def run(self):
        """
        Main entry point to the game. Plays hands in a loop until the user chooses to exit
        :return: None
        """
        play_again = None
        while play_again != 'n':
            self.play_hand()
            play_again = self.ask_user('Play again?', ['y', 'n'])
Exemple #3
0
class BlackJack:
    def __init__(self, shoe_size=6):
        self.deck = Deck(shoe_size)
        self.players = self.setup_players()
        self.dealer = Hand('Dealer')

    def setup_players(self):
        plrs = []
        while True:
            try:
                q = int(input('How many players are going to play?: '))
                break
            except ValueError:
                print('Please enter a base 10 number.')
        for i in range(q):
            player_name = input('What is the name of player {}?: '.format(i + 1))
            plrs.append(Hand(player_name))
        return plrs

    def deal_round(self):
        for i in range(2):
            for p in self.players:
                p.take(self.deck.deal_card())
            self.dealer.take(self.deck.deal_card())

    def play_round(self):
        self.deal_round()
        for p in self.players:
            while p.score() <= 21:
                p.display_hand()
                q = input('Would you like to (H)it or (S)tay?: ').lower()
                if q == 'h':
                    p.take(self.deck.deal_card())
                elif q == 's':
                    break
            else:
                if p.score() > 21:
                    p.display_hand()
        else:
            self.dealer.display_hand()
            d_score = self.dealer.score()
            while d_score < 17:
                self.dealer.take(self.deck.deal_card())
                self.dealer.display_hand()
                d_score = self.dealer.score()
                time.sleep(1)

    def clear_hands(self):
        for p in self.players:
            p.clear()
        self.dealer.clear()

    def score_game(self):
        winner = self.dealer
        score = self.dealer.score() if self.dealer.score() <= 21 else 0
        for p in self.players:
            if 22 > p.score() > score:
                score = p.score()
                winner = p
        return winner

    def game(self):
        while True:
            self.play_round()
            print('{} wins!'.format(self.score_game().name))
            self.clear_hands()
            q = input("Would you like to play again?: ").lower()
            if 'n' in q:
                quit()
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from hand import Hand

testHand = Hand()

## Royal Flush
testHand.add_card(14,0)
testHand.add_card(10,0)
testHand.add_card(12,0)
testHand.add_card(11,0)
testHand.add_card(13,0)
testHand.clear()

## Straight Flush
testHand.add_card(9,3)
testHand.add_card(10,3)
testHand.add_card(12,3)
testHand.add_card(11,3)
testHand.add_card(13,3)
testHand.clear()

## Straight 
testHand.add_card(9,1)
testHand.add_card(10,2)
testHand.add_card(12,0)
testHand.add_card(11,3)
testHand.add_card(13,2)
testHand.clear()
class GameController:

    CONST_ISLAND_MASK = 0b10000
    CONST_FOREST_MASK = 0b01000
    CONST_PLAIN_MASK = 0b00100
    CONST_MOUNTAIN_MASK = 0b00010
    CONST_SWAMP_MASK = 0b00001

    def __init__(self, deck_wanted_size, hand_init_size, enable_mulligan=True):
        assert deck_wanted_size >= hand_init_size
        assert deck_wanted_size >= self.get_land_quantity()
        self.deck = Deck()
        self.hand = Hand()
        self.board = Board()
        self.deck_wanted_size = deck_wanted_size
        self.hand_init_size = hand_init_size
        self.enable_mulligan = enable_mulligan

        self.decision_tree = {}
        self.compute_tree = []

    def init(self):
        self.deck.clear()
        self.hand.clear()
        self.board.clear()

    def insert_lands_in_deck(self):
        for land, quantity in binary_lands.items():
            card = Card(
                'terrain',
                land & self.CONST_ISLAND_MASK,
                land & self.CONST_FOREST_MASK,
                land & self.CONST_PLAIN_MASK,
                land & self.CONST_MOUNTAIN_MASK,
                land & self.CONST_SWAMP_MASK,
            )
            self.deck.add_card(card)

    def fill_deck(self):
        for i in range(self.deck_wanted_size - self.get_land_quantity()):
            self.deck.add_card(Card('useless'))

    def game_set_up(self):
        self.insert_lands_in_deck()
        self.fill_deck()
        self.deck.shuffle()

    # If we enable mulligans
    def mulligan_phase(self, hand_size):
        cards_drawn = self.deck.draw(hand_size)
        self.hand.clear()
        self.hand.add_cards(cards_drawn)
        if not self.enable_mulligan or \
           self.deck.get_size() == 0 or \
           hand_size == 0 or \
           not self.hand.is_improvable(self.get_land_quantity(), self.deck.get_size()):
            return
        # Put card back into the deck and redraw
        self.deck.add_cards(self.hand.get_cards())
        self.deck.shuffle()
        self.hand.clear()
        self.mulligan_phase(hand_size - 1)

    def run(self):
        self.init()
        self.game_set_up()
        self.mulligan_phase(self.hand_init_size)
        print(self.hand)
        ret = self.game()
        # game_result(ret)

    def check_succeed(self, binary_hand_matrix, chain=0b00000):
        for binary_card in binary_hand_matrix:
            binary_substract = [
                x for x in binary_hand_matrix if x != binary_card
            ]
            chain = 0b00000
            for elem in binary_card:
                chain = chain | elem
                print(chain)
            if chain == 0b11111:
                print("Returning True")
                return True
        print("Returning False")
        return False

    # def place_element_tree(self, tree, elem):
    #     if not tree:
    #         if type(elem) != tuple:
    #             elem = tuple(elem)
    #         for e in elem:
    #             tree[e] = {}
    #         return
    #     for key, val in tree.items():
    #         self.place_element_tree(val, elem)
    #
    # def construct_decision_tree(self):
    #     for card in self.board.get_cards():
    #         if card.name == 'cavern':
    #             continue
    #         self.place_element_tree(self.decision_tree, card)
    #
    # def do_compute_tree(self, next_elem, path=''):
    #     if not next_elem:
    #         return self.compute_tree.append(path)
    #     for key, val in next_elem.items():
    #         if key in path:
    #             self.do_compute_tree(val, path)
    #         else:
    #             self.do_compute_tree(val, path + key)
    #
    # def check_succeed(self):
    #     if self.board.get_size() > 5 and self.board.has_cavern():
    #         return True
    #     self.construct_decision_tree()
    #     # print(json.dumps(decision_tree, indent=1))
    #     self.do_compute_tree(self.decision_tree)
    #     # print(json.dumps(compute_tree, indent=1))
    #
    #     for elem in self.compute_tree:
    #         if len(elem) == 5:#nb_diff_land_to_collect:
    #             return True
    #     return False

    def place_land_board(self):
        weight_matrix = {}
        for key, card in enumerate(self.hand.get_cards()):
            if card.name == 'useless':
                continue
            if card.name == 'cavern':
                if len(self.board.get_size()) == 5:
                    weight_matrix[key] = 100
                else:
                    weight_matrix[key] = 0.5
            if card in self.board.get_cards():
                weight_matrix[key] = 1
            weight_matrix[key] = len(card.get_mana_colors())

        if not weight_matrix:
            return
        key = max(weight_matrix, key=weight_matrix.get)

        card_to_add = self.hand.remove(key)
        self.board.add_card(card_to_add)
        # print('%s added to the board...' % (card_to_add))
        # print(self.board)

    def game(self):
        while self.deck.get_size() > 0:

            self.decision_tree = {}
            self.compute_tree = []

            card_drawn = self.deck.draw(1)
            # print("Draw %s" % (card_drawn,))
            self.hand.add_cards(card_drawn)
            self.place_land_board()
            print(self.board)
            if self.check_succeed(self.board.get_cards_binary_color_matrix()):
                return 1
        return 0

    @staticmethod
    def get_land_quantity():
        return len(binary_lands)
Exemple #6
0
card7 = Card(rank="7", suit="c")
card8 = Card(rank="8", suit="c")
card9 = Card(rank="9", suit="c")
card10 = Card(rank="10", suit="c")
card11 = Card(rank="11", suit="c")
card12 = Card(rank="12", suit="c")
card13 = Card(rank="13", suit="c")

print(card1)  # Ac
print(card2)  # 2c
print(card3)  # 3c
print(card4)  # 4c
print(card5)  # 5c

my_hand = Hand()
print(my_hand)  # <empty>
my_hand.add(card1)
my_hand.add(card2)
my_hand.add(card3)
my_hand.add(card4)
my_hand.add(card5)
print(my_hand)  # Ac 2c 3c 4c 5c

your_hand = Hand()
my_hand.give(card1, your_hand)
my_hand.give(card2, your_hand)
print(your_hand)  # Ac 2c
print(my_hand)  # 3c 4c 5c
my_hand.clear()
print(my_hand)  # <empty>
Exemple #7
0
            dealer_bust = True

        for i in range(len(player)):
            if (player[i].value > dealer.value and not player_bust[i]) or (dealer_bust and not player_bust[i]):
                if len(player) > 1:
                    print('You win on hand ' + str(i + 1) + '!')
                else:
                    print('You win!')
            elif player[i].value == dealer.value and not player_bust[i]:
                if len(player) > 1:
                    print('You tie the dealer on hand ' + str(i + 1) + '.')
                else:
                    print('You tie the dealer.')
            else:
                if len(player) > 1:
                    print('You lose on hand ' + str(i + 1) + '!')
                else:
                    print('You lose!')

        play_again = True if input('\nPlay again? (y/n) ').lower() == 'y' else False

        if play_again:
            player = []
            player_bust = []

            player.append(Hand())
            player_bust.append(False)
            dealer.clear()

    print('\n\nThanks for playing Blackjack!\n\n')
Exemple #8
0
class Game:
    def __init__(self):
        self.players = [Human('Player'), CPU('CPU')]
        self.dealToCrib = False
        if (len(self.players) == 2):
            self.dealCardNumber = 6
        elif (len(self.players) == 3 or len(self.players) == 4):
            self.dealCardNumber = 5
            self.dealToCrib = True
        else:
            raise ValueError('Number of players not supported')
        self.gameWinningScore = 121
        self.cutCard = None
        self.currentDealer = None
        self.deck = Deck()
        self.crib = Hand()

    def determineDealer(self):
        randomIndex = random.randrange(len(self.players))
        self.currentDealer = self.players[randomIndex]

    def switchDealer(self):
        dealerIndex = self.players.index(self.currentDealer)
        if (dealerIndex < 0 or dealerIndex >= len(self.players)):
            self.determineDealer()
        elif ((dealerIndex + 1) % len(self.players) == 0):
            self.currentDealer = self.players[0]
        else:
            self.currentDealer = self.players[dealerIndex + 1]

    def dealCards(self):
        self.deck.shuffle()
        for i in range(self.dealCardNumber):
            for player in self.players:
                player.hand.append(self.deck.deal())
        if (self.dealToCrib):
            self.crib.append(self.deck.deal())
        self.cutCard = self.deck.cut()

    def discard(self):
        # Player discard
        # First
        for player in self.players:
            self.crib.append(player.discard())
            self.crib.append(player.discard())

    def playRound(self):
        currentPlay = Play()
        currentPlayerIndex = self.players.index(self.currentDealer)
        currentPlayer = self.players[currentPlayerIndex]
        for player in self.players:
            player.createPlayHand()
        lastPlayerToPlay = None
        while True:
            # Determine is anyone has cards left
            someoneHasCards = False
            for player in self.players:
                if (len(player.playHand) > 0):
                    someoneHasCards = True
            if (not someoneHasCards):
                break

            # Get the next player
            if ((currentPlayerIndex + 1) % len(self.players) == 0):
                currentPlayerIndex = 0
                currentPlayer = self.players[0]
            else:
                currentPlayerIndex += 1
            currentPlayer = self.players[currentPlayerIndex]

            # If player can play, play
            if (currentPlayer.canPlay(currentPlay.pointLimit)):
                cardPlayed = currentPlayer.play(currentPlay.pointLimit)
                currentPlay.append(cardPlayed)
                print('{0} plays {1}'.format(currentPlayer.name, cardPlayed))
                currentPlayer.score += currentPlay.calculateExtraPoints()
                lastPlayerToPlay = currentPlayer
                print(currentPlay.points)
            else:
                if (currentPlayer == lastPlayerToPlay):
                    currentPlayer.score += 1
                    print('{0}: One for last'.format(currentPlayer.name))
                    currentPlay.reset()
                else:
                    print('{0} GO'.format(currentPlayer.name))
        currentPlayer.score += 1
        print('{0}: One for last'.format(currentPlayer.name))
        currentPlay.reset()

    def show(self):
        print('Cut Card: {0}'.format(self.cutCard))
        for player in self.players:
            print(player.name, player.hand)
            player.show(self.cutCard)
        print('The Crib: {0}'.format(self.crib))
        self.currentDealer.score += self.crib.getPoints(self.cutCard)

    def endRound(self):
        self.crib.clear()
        self.cutCard = None
        for player in self.players:
            player.hand.clear()

    def isComplete(self):
        for player in self.players:
            if (player.score >= self.gameWinningScore):
                return True
        return False

    def getScoreBoardString(self):
        scoreBoardString = ''
        for player in self.players:
            scoreBoardString += '{0:16s}: {1:3d}\n'.format(
                player.name, player.score)
        return scoreBoardString
Exemple #9
0
class Player(object):
    HUMAN = 1
    COMPUTER = 0
    
    def __init__(self,name,tyyppi):
        self.__name=name
        self.__cottages=0
        self.__points=0
        self.__hand = Hand()
        self.__type = tyyppi
        self.__stack = Hand()
        
    '''
    name methods
    '''
    def getName(self):
        return self.__name
        
    '''
    point methods
    '''
    def updatePoints(self,amount):
        self.__points += amount
        
    def setPoints(self,amount):
        self.__points = amount
        
    def getPoints(self):
        return self.__points
        
    '''
    cottage methods
    '''
    def getCottages(self):
        return self.__cottages  
        
    def raiseCottages(self,amount):
        self.__cottages+=amount
        
    def setCottages(self,amount):
        self.__cottages=amount
        
    def clearCottages(self):
        self.__cottages=0
        
    '''
    hand methods
    '''
    def getHand(self):
        return self.__hand
    
    def addCardsToHand(self,cards):
        self.__hand.addCards(cards)
            
    def addCardToHand(self,card):
        self.__hand.append(cards)
    
    def setHand(self,cards):
        self.__hand.clear()
        self.__hand.addCards(cards)
    
    def hasCards(self):
        return len(self.__hand.getCards())>0
    
    '''
    stack methods
    '''
    def getStack(self):
        return self.__stack
    
    def clearStack(self):
        self.__stack=Hand()
    
    def addCardsToStack(self,cards):
        for card in cards:
            self.addCardToStack(card)
            
    def addCardToStack(self,card):
        self.__stack.addCard(card)
    
    def setStack(self,cards):
        self.__stack.clear()
        self.__stack.addCards(cards)
    
    '''
    type methods
    '''
    def getType(self):
        return self.__type
            
    '''
    other methods
    '''
    def getScoreFromStack(self):
        points = self.__cottages
        points += self.__stack.getSureValue()
        return points
    
    def __str__(self):
        return self.__name+"-"+str(self.__points)