Пример #1
0
def prob_two_pairs(N=100000):
    M = 0  # no. of successes
    for exp in xrange(N):
        deck = Deck()
        hand = deck.hand(n=5)
        M += (same_rank(hand, 2) == 2)
    return float(M) / N
Пример #2
0
def prob_fourofakind(N=100000):
    M = 0  # no. of successes
    for exp in xrange(N):
        deck = Deck()
        hand = deck.hand(n=5)
        M += (same_rank(hand, 4) == 1)
    return float(M) / N
Пример #3
0
 def __init__(self, *args, **kwargs):
     platform = pyglet.window.get_platform()
     display = platform.get_default_display()
     screen = display.get_default_screen()
     template = pyglet.gl.Config(double_buffer=True)
     config = screen.get_best_config(template)
     context = config.create_context(None)
     window.Window.__init__(self, resizable=True, width=WINWIDTH, height=WINHEIGHT, caption="REZD:" + str(VERSION), context=context)
     self.baseDeck = Deck() # used to lookup cards basically a reference instead of using a database. Basically don't remove / add cards
     self.baseDeck.populate('assets/cardlist.xml')
     self.newdeck = Deck()
     self.selectedCard = None
     self.runnerbaselist = []
     self.corpbaselist = []
 
     for card in self.baseDeck.deck:
         if card.playertype == "Runner":
             self.runnerbaselist.append(card.name)
         else:
             self.corpbaselist.append(card.name)
     
     self.runnerbaselist.sort()
     self.corpbaselist.sort()
     # kytten stuff
     self.theme = kytten.Theme(os.path.join(os.getcwd(), 'theme'), override={
                                                                        "gui_color": [64, 128, 255, 255],
                                                                        "font_size": 14
                                                                        })
     
     self.theme2 = kytten.Theme(self.theme, override={
                                                 "gui_color": [61, 111, 255, 255],
                                                 "font_size": 12
                                                 })
Пример #4
0
def battle():
    print('\n#<====== Playing a Game of War ======>#\n')
    ## Creating p1Score, p2Score, ties variables.
    p1Score = 0
    p2Score = 0
    ties = 0
    ## Creating two hands to hold cards (that are dealt for each player)
    h1 = []
    h2 = []
    ## Creating a new deck for the cards
    d = Deck()
    ## Shuffling the new deck
    d.shuffle()
    ## Using a loop to deal cards to the two players.
    for i in range(len(d.cards)):
        if i % 2 == 0:
            h1.append(d.deal())
        elif i % 2 == 1:
            h2.append(d.deal())
        i += 1
    ## printing each player's hands
    print('\n#<====== Player 1\'s Hand: ======>#\n')
    for card in h1:
        print(card)
    print('\n#<====== Player 2\'s Hand: ======>#\n')
    for card in h2:
        print(card)
    print('\n#<====== Now its time for WAR!!! ======>#\n')
Пример #5
0
 def playGame(self):
     while self.newGame != False:
         self.newGame = False
         print("Welcome to Bender's Totally Legit and Not Rigged at All Blackjack Table.")
         print("You're not a cop, are you?  You have to tell me if you're a cop...")
         self.getPlayers()
         print("Welcome",self.player.name)
         self.player.startingCash()
         print(self.player.name, "has $",self.player.cash,"available")
         deck = Deck()
         dealer = Dealer()
         while self.replayGame != False:
             if len(deck.currentDeck) <= 10:
                 house = deck.newDeck()
             round = Round(self)
             results = Results(self)
             score = Scoreboard(self)
             wager = score.placeBet(self.player.cash)
             if self.newGame == True:
                 break
             round.startingHands(self.player, dealer, deck, house)
             round.takeAction(self.player, dealer, deck, house)
             if self.player.score <= 21 and self.player.score > 0:
                 round.checkDealerHand(self.player, dealer, deck, house)
             results.determineWinner(self.player, dealer)
             self.player.cash = score.updateCash(self.player.cash, wager)
             print(self.player.name, "has $", self.player.cash, "available")
             replay = KeepPlaying()
             replay.replayGame(self.player, dealer)
             self.replayGame = replay.playAgain
         if self.newGame == False:
             print("I don't need you.  I'll build my own casino.  With Blackjack... and hookers... Awww, forget it.")
         elif self.newGame == True:
             print("Oops, you're broke! ¯\_(ツ)_/¯")
             print("Come back when you have some money to lose. (\/)(;,,;)(\/)")
def test():
    """ Simple test program for card dragging. """

    from Deck import Deck

    pygame.init()
    screen = pygame.display.set_mode((640, 480))

    deck = Deck()
    handler = CardDraggingEventHandler(deck)

    while True:
        pygame.time.wait(30)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    sys.exit()
            else:
                handler.handle_card_dragging(event)

        screen.fill((0x00, 0xb0, 0x00))

        deck.draw(screen)

        pygame.display.flip()
Пример #7
0
class DeckTest(unittest.TestCase):

    def setUp(self):
        self.deck = Deck()

    def test_createDeck(self):
        self.assertEqual(52, self.deck.getNumOfCards())

    def test_shuffle(self):
        testDeck = self.deck.getAllCards()
        compareDeck = []
        for card in testDeck:
            compareDeck.append(card)
        numOfSameCards = 0
        for x in range(0, 52):
            if compareDeck[x] == testDeck[x]:
                numOfSameCards += 1
        self.assertEqual(52, numOfSameCards)
        self.deck.shuffle()
        numOfSameCards = 0
        for x in range(0, 52):
            if compareDeck[x] == testDeck[x]:
                numOfSameCards += 1
        self.assertNotEqual(52, numOfSameCards)

    def test_getNextCard(self):
        newDeck = Deck()
        for x in range(0, 52):
            newDeck.getNextCard()
        with self.assertRaises((NameError)):
            newDeck.getNextCard()
Пример #8
0
def prob_same_suit(N=100000):
    M = 0  # no. of successes
    for exp in xrange(N):
        deck = Deck()
        hand = deck.hand(n=5)
        for suit in same_suit(hand):
            M += (same_suit(hand)[suit] in [4, 5])
    return float(M) / N
Пример #9
0
 def playBJ(self):
     
     deck = Deck(self.game_deck_num)
     deck.shuffleDeck()
     in_hand = True
     #print deck.printDeck(self.game_deck_num * 52)
     
     player_card1 = deck.dealCard(in_hand)
     dealer_card1 = deck.dealCard(in_hand)
     player_card2 = deck.dealCard(in_hand)
     dealer_card2 = deck.dealCard(in_hand)
Пример #10
0
    def updateRatingsAI(self, table, setFound, the_time):
        '''AI was faster, so all sets involved are actually harder
        than we thought, ie increase their rating
        Please call whenever an AI finds a set
        '''

        allSets = Deck.allSets(table)
        for the_set in allSets:
            try:
                self.ratingList[Deck.idOfSet(the_set)] += 50
            except:
                self.ratingList[Deck.idOfSet(the_set)] = 1550
        self.dumpData()
Пример #11
0
    def __initializeDeck(self):
        # Initialize discard columns
        self.__discardPiles = [
            Deck(),
            Deck(),
            Deck(),
            Deck()
        ]

        deck = Deck()
        deck.buildFullDeck()
        deck.shuffle()
        self.__deck = deck
Пример #12
0
 def __init__(self, numPlayers=1, numAI = 3):
   """
   basic set up for a game where:
   numPlayers = the total number of  human players
   numAI = the number of the total players that are AI
   """
   self.totPlayers = numPlayers + numAI
   #checking that there are atleast 2 players
   if (self.totPlayers) < 2:
     raise Exception('need atleast 2 players to play the game')
   
   self.deck = Deck()
   
   self.numPlayers = numPlayers
   self.numAI = numAI
   
   self.winners = []
   
   #setting up the players
   self.players = []
   [self.players.append(Player(len(self.players), game=self, AI = len(self.players) >= numPlayers)) for i in range(numPlayers + numAI)]
   
   for i in range(len(self.players)):
     self.players[i].setPrev(self.players[i-1])
     self.players[i].setNext(self.players[(i + 1) % len(self.players)])
Пример #13
0
	def __init__(self, num_players=1, num_decks=6):
		self.num_decks = num_decks
		self.dealer = Dealer()
		self.bot = Bot('Bot')
		self.players = []
		self.busted = []
		self.stand = []
		self.move = 0
		self.dealer_done = False
		self.bot_moves = []
		for i in xrange(0,num_players):
			self.players.append(Player('Player'+str(i+1)))

		self.players.append(self.bot)
		self.deck = Deck(num_decks)
		self.bot_deck = self.deck.deck * 1
		for player in self.players:
			player.make_bet()
			if player.name == 'Bot':
				player.add(self.bot_deck.pop())
				player.add(self.bot_deck.pop())
				self.bot_deck.pop()
				self.bot_deck.pop()
			else:
				player.add(self.deck.draw())
				player.add(self.deck.draw())
				self.dealer.add(self.deck.draw())
				self.dealer.add(self.deck.draw())

		self.rules = RulesEngine(self.dealer, self.players)
Пример #14
0
	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()
Пример #15
0
    def __init__(self, table, message_handler=None):
        """players should be array of players to be seated.

        deal must be the player who is the current dealer. If None, the
        lowest seated player will be the dealer.

        message handler must be a MessageHandler instance or None."""
        self.table = table
        self.message_handler = message_handler

        #
        # Private state not available to players
        #
        self._deck = Deck()
        self._deck.shuffle()

        active_players = self.table.get_active_players()

        # Create main pot to start with
        self.pot = Pot(contending_players = active_players)
        # Create initial hands
        for player in active_players:
            player.new_hand()
        # Record of betting rounds
        self.betting_rounds = []
Пример #16
0
 def initialize_hand(self):
     self.move_button()
     self.pots = [Pot(self.players.keys())]
     self.rake = [0]
     self.action = self.button_seat
     self.deck = Deck()
     self.deck.shuffle()
     for position, player in self.players.iteritems():
         player.discard_hole_cards()
     self.board = []
Пример #17
0
	def start(self):
		self.currentPlayer = 0

		self.deck = Deck()
		self.deck.shuffle()

		# Deal Cards
		i = 0
		for card in self.deck.getNCards(11 * 4):
			self.players[i].hand.append(card);
			i = (i + 1)%4
Пример #18
0
 def setUpHint(self):
     ''' unschedule any current hint and loads up
     the next one if appropriate'''
     # Need to remove any previous call or else it might be activated too
     # quickly
     Clock.unschedule(self.displayHint)
     Clock.unschedule(self.displayHintSecond)
     # After some time in seconds show a hint
     if self.hintActivated and self.active:
         self.hint = Deck.hint(self.cards)
         Clock.schedule_once(self.displayHint, self.displayHintTimer)
Пример #19
0
    def __init__(self, players):
        self.players_byorder = players # Join order mapped to players

        self.players_bynick = {} # Current nick mapped to players
        for order, player in players.iteritems():
            self.players_bynick[player.nick] = player

        self.answers = Deck(Config.FILENAME_ANSWERS)
        self.questions = Deck(Config.FILENAME_QUESTIONS)
        self.winner = None

        self.ids = []
        for order, player in self.players_byorder.iteritems():
            for i in range(Config.HAND_SIZE):
                player.addCard(self.answers.take()) # Deal initial hand to each player
            self.ids.append(order)

        self.idindex = 0
        self.setter = self.players_byorder[self.ids[self.idindex]] # Current question-setter
        self.played = [] # List of tuples, each tuple composed of a card and the player that played it
Пример #20
0
 def __init__(self, game, cd_kick):
     BaseClass.__init__(self)
     self.game = game
     self.deck = Deck()
     self.current_card = None
     self.players = []
     self.turn = 0
     self.played_time = None
     self.timeout = cd_kick
     self.turn_direction = 1
     self.playing = False
Пример #21
0
    def suggestion(self, table):
        all_sets = Deck.allSets(table)
        set_difficulties = []

        for the_set in all_sets:
            set_difficulties.append(self.get_difficulties(the_set))

        time, index = self.get_time(set_difficulties)
        set_cards1, set_cards2, set_cards3 = all_sets[index]

        return time, (set_cards1, set_cards2, set_cards3)
Пример #22
0
class Game(object):
	def __init__(self):
		self.players = []
		for i in range(4):
			self.players.append(Player())

	def start(self):
		self.currentPlayer = 0

		self.deck = Deck()
		self.deck.shuffle()

		# Deal Cards
		i = 0
		for card in self.deck.getNCards(11 * 4):
			self.players[i].hand.append(card);
			i = (i + 1)%4

	def getCurrentPlayersHand(self):
		return sorted(self.players[self.currentPlayer].hand)
Пример #23
0
 def on_enter(self):
     ''' Sets the game '''
     # You can only enter the game from the intro
     self.deck = Deck()
     self.cards = self.deck.drawGuarantee(numberofcards=12)
     for i in range(len(self.scores_of_players)):
         self.scores_of_players[i] = 0
     self.ai = AI(self.directory)
     self.aiScore = 0
     self.game.active = True
     self.active = True
     self.newRound()
     self.t0 = datetime.datetime.now()
Пример #24
0
	def newRound(self):
		self.deck = Deck()
		self.deck.shuffle()
		self.roundNum += 1
		self.trickNum = 0
		self.trickWinner = -1
		self.heartsBroken = False
		self.dealer = (self.dealer + 1) % len(self.players)
		self.dealCards()
		self.currentTrick = Trick()
		self.passingCards = [[], [], [], []]
		for p in self.players:
			p.discardTricks()
Пример #25
0
 def __init__(self):
     ''' Creates a new Game. '''
     self._playerList = []
     self._deck = Deck()
     self._deck.shuffle()
     self._discardPile = DiscardPile()
     self._currentPlayer = 0
     self._currentCard = self._deck.drawCard()
     self._blankCards = {
             'blue' : Card('blue', 'blank'),
             'yellow' : Card('yellow', 'blank'),
             'red'    : Card('red', 'blank'),
             'green'  : Card('green', 'blank')}
Пример #26
0
class Dealer(object):
    def __init__(self, deck=None, discard_pile=None, payout_table=None):
        self.deck = Deck(52)
        self.discard_pile = DiscardPile()

    def shuffle_deck(self):
        temp_deck = Deck(0)
        for k in range(len(self.deck)):
            temp_deck.append(self.deck.pop(random.randint(0, len(self.deck)-1)))
        self.deck = temp_deck

    def deal_card(self):
        return self.deck.pop(0)

    def deal_indexed_card(self, index):
        return copy.copy(self.deck[index])
        # return self.deck.pop(index))

    def rate_hand(self):
        pass

    def collect_hand(self):
        pass
Пример #27
0
def playwar():
    deck = Deck()
    deck.shuffle()
    n = deck.size()
    playerHand = Hand()
    compHand = Hand()

    deck.moveCards(playerHand, (n//2))
    deck.moveCards(compHand, (n//2))
    # playerHand.sort()
    # compHand.sort()
    print ("Cards in computer hand: ")
    print(compHand)
    print("Cards in player hands: ")
    print(playerHand)
    nowPlay(playerHand, compHand)
Пример #28
0
    def updateRatingsHuman(self, table, setFound, the_time):
        '''updates the ratings of all sets involved in this round
        Please call whenever a human finds a set
        '''
        initialRating = 1500
        setFoundKey = Deck.idOfSet(setFound)
        try:
            setFoundRating = self.ratingList[setFoundKey]
        except KeyError:  # first time this set shows up
            setFoundRating = initialRating

        losingSets = set(Deck.allSets(table)) - set(setFound)
        for the_set in losingSets:
            losingSetKey = Deck.idOfSet(the_set)
            try:
                losingSetRating = self.ratingList[losingSetKey]
            except KeyError:  # first time this set shows up
                losingSetRating = initialRating
            newWinnerRating, newLoserRating = self.newRatings(setFoundRating,
                                                              losingSetRating)
            self.ratingList[setFoundKey] = newWinnerRating
            self.ratingList[losingSetKey] = newLoserRating
        self.dumpData()
Пример #29
0
	def __init__(self, timeout, gameTime, maxConnections):
		self.timeout 			= timeout
		self.gameTime 			= gameTime
		self.maxConnections 	= maxConnections
		self.connections		= []
		self.table				= { '1' : None,
									'2' : None,
									'3' : None,
									'4' : None,
									'5' : None,
									'6' : None }
		self.lobby				= []
		self.deck				= Deck()
		self.gameStarted		= False
		self.dealerHand			= []
		self.hiddenCard			= ''
		self.failJoin			= []
Пример #30
0
	def __init__(self, rounds=1000, *choices):
		# Variable declarations for counting
		self.flush = 0
		self.fullHouse = 0
		self.threeOfAKind = 0
		self.fourOfAKind = 0
		self.onePair = 0
		self.twoPairs = 0
		self.rounds = rounds
		self.choices = choices

		# Check for empty values
		if len(self.choices) == 0:
			sys.exit("Empty poker type not allowed")

		# Run game 10000 times
		for i in range(self.rounds):
			# Instantiate card and decks
			self.deck = Deck()
			self.deck.shuffle()

			# Play 10 rounds
			for j in range(10):
				self.poker = PokerHand()
				# Pick up 5 cards
				for k in range(5):
					self.poker.add(self.deck.deal())

			# Check if cards are cetain types of pokers
			if self.poker.isFlush():
				self.flush += 1

			elif self.poker.hasFullHouse():
				self.fullHouse += 1

			elif self.poker.hasThreeOfAKind():
				self.threeOfAKind += 1

			elif self.poker.hasFourOfAKind():
				self.fourOfAKind += 1

			elif self.poker.hasOnePair():
				self.onePair += 1

			elif self.poker.hasTwoPairs():
				self.twoPairs += 1
Пример #31
0
 def __init__(self):
     self.deck = Deck()
Пример #32
0
from Deck import Deck
from ExtraDeck import ExtraDeck
from YGOPricesAPI import YGOPricesAPI

deck = Deck(list())
extra = ExtraDeck(list())
card_list = YGOPricesAPI().get_names()
Пример #33
0
    chips.lose_bet()


def dealer_wins(player, dealer, chips):
    print("You lost!")
    chips.lose_bet()


def push(player, dealer):
    print("Tied. Push")


while True:
    print("Welcome to my blackjack 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()

    take_bet(player_chips)

    show_some(player_hand, dealer_hand)
Пример #34
0
from Deck import Deck
import copy

ourDeck = Deck(None, None)

CardsDelt = copy.deepcopy(ourDeck.dealCards(10))

for Card in CardsDelt:
    print(type(ourDeck))
Пример #35
0
class Game:
    def __init__(self):
        self.deck = Deck()
        self.turn_count = 0
        self.player_count = 1
        self.index = 1
        self.hands = []

    def text_header(self):
        clear()
        print("UNO!\n")
        draw_pile_count = self.deck.get_draw_pile_count()
        top_card = self.deck.get_top_card()

        if len(self.hands) == self.player_count + 1:
            com_hand_count = len(self.hands[0])
            print("COM hand: {} cards".format(com_hand_count))
        if draw_pile_count >= 0:
            print("Draw pile: {} cards".format(draw_pile_count))
        if top_card:
            print("Top card: {}".format(top_card))
        print("")

    def start(self):
        """
        Start the game:

        Display a header
        Deal cards
        Run until somebody wins
        """
        self.text_header()
        self.deal()

        has_won = False
        while has_won != True:
            self.turn_count += 1
            has_won = self.turn()

            if has_won == False:
                # Nobody won this turn, see what to do next
                next_player = self.index + 1
                if next_player > self.player_count:
                    next_player = 0  # start back at the beginning

                self.index = next_player

        player_name = "Player {}".format(self.index)
        if self.index == 0:
            player_name = "Computer"
        print("\n")
        print("{} won after {} turns!".format(player_name, self.turn_count))
        print("GG :-)\n")

    def deal(self):
        """
        Deal cards to players.
        """
        deck = self.deck

        # Number of human players
        # TODO: adapt deal function to handle more players
        for j in range(0, self.player_count + 1):
            self.hands.append([])

        for i in range(0, 14):
            if i % 2 == 1:
                # give human the card
                self.hands[0].append(deck.draw())
            else:
                # give player the card
                self.hands[1].append(deck.draw())

        deck.discard(deck.draw())

    def turn(self):
        """
        Run the current turn. Call a handler
        function for a human if this is a human
        turn (index does not equal 0)
        """
        self.text_header()
        if self.index == 1:
            return self.human_turn()
        else:
            return self.computer_turn()

    def human_turn(self, message=None):
        """
        Let the human play their turn; ask for instructions.
        """
        self.text_header()

        my_hand = self.hands[self.index]
        my_hand_count = len(my_hand)

        if message:
            print(message)
        else:
            print("It's your turn. You have {} cards.".format(my_hand_count))

        self.view_hand(my_hand)
        action_str = str(input("Type a number to choose a card or action: "))

        if action_str == "D":
            new_card = self.deck.draw()
            my_hand.append(new_card)
            self.confirm("drew", my_hand, new_card)
            return self.human_turn("You drew {} last turn.".format(new_card))
        else:
            action_int = None
            try:
                action_int = int(action_str)
            except ValueError:
                print("something went wrong")

            if action_int != None and action_int >= 0 and action_int <= my_hand_count - 1:
                # Picking a card
                card = my_hand[action_int]

                # Try to discard this card
                attempt = self.deck.discard(card)

                if attempt == True:
                    # Toss the card out of my hand
                    del my_hand[action_int]
                    if my_hand_count - 1 == 0:
                        # GG
                        return True
                    else:
                        # Not yet GG
                        return self.confirm("played", my_hand, card)
                else:
                    return self.human_turn(
                        "You can't play this card, try another!")

            else:
                return self.human_turn("This isn't a valid action!")

    def computer_turn(self):
        """
        Let the computer play its turn.
        """

        com_hand = self.hands[self.index]
        has_won = False
        has_played_card = False

        # Try to play available cards
        for index, card in enumerate(com_hand):
            attempt = self.deck.discard(card)

            if attempt == True:
                # Toss the card out of my hand
                del com_hand[index]
                if len(com_hand) == 0:
                    # GG
                    has_won = True
                    has_played_card = True
                    break  # the for loop
                else:
                    # Not yet GG
                    has_played_card = True
                    break  # the for loop

        # If the computer hasn't played a card,
        # keep drawing until we can play one
        if has_played_card == False:

            # Draw more cards until we get a match
            while has_played_card == False:
                # Draw and try to discard this card
                new_card = self.deck.draw()
                attempt = self.deck.discard(new_card)
                if attempt == True:
                    has_played_card = True
                else:
                    com_hand.append(new_card)

            return self.confirm2("Computer", "drew and played a card")

        else:
            self.confirm2("Computer", "played a card")
            return has_won

    # --- #

    def view_hand(self, hand):
        """View the player's hand."""
        print("D: Draw a card")
        for index, card in enumerate(hand):
            print("{}: {}".format(index, card))
        print("")

    def confirm(self, word, hand, card):
        """Confirmation message when the player acts."""
        self.text_header()
        print("You {} {}, and now have {} cards.".format(
            word, card, len(hand)))
        next = input("Press any key to continue...")
        return False

    def confirm2(self, who, word):
        """Confirmation message when the computer acts."""
        self.text_header()
        print("{} {}.".format(who, word))
        next = input("Press any key to continue...")
        return False
Пример #36
0
class Game:

    filename = "C:/Users/Owner/Documents/GitHub/Western-AI_Poker-Bot/Poker_Data.xlsx"
    wb = Workbook(write_only=True)
    ws = wb.create_sheet()

    def __init__(self, number_of_players):

        # Game Class variables
        self.deck = Deck()
        self.number_of_players = number_of_players

        self.player = [0] * self.number_of_players
        self.card = [0] * 5

        # Review variable
        # self.player_card = [0] * self.number_of_players * 2

        # Instantly start a new game
        self.excel_header()
        self.play()

    # Simulate x number of poker games
    def simulate(self, number_of_games):

        # Simulate poker games
        for n in range(number_of_games):
            if n % 10000 == 0:
                print("Game " + str(n + 1))
            self.play()

            # Evaluate each player's hand
            for player in self.player:
                evaluate = EvaluateHand(self, player)
                hand_assignment = evaluate.count()

            # Export Data to Excel
            self.ws.append(self.extract_game_data(hand_assignment, n))

        # Save Excel File
        self.wb.save(
            r"C:/Users/Owner/Documents/GitHub/Western-AI_Poker-Bot/Poker_Data.xlsx"
        )

    # Play a game of Poker
    def play(self):
        self.deck.reset()

        # Draw Player Cards
        for p in range(self.number_of_players):
            self.player[p] = Player(self.deck, p)

        # Draw Game Cards
        for x in range(5):
            # Store cards in array
            self.card[x] = self.deck.draw()

    def extract_game_data(self, hand_assignment, n):

        p_list = []
        b_list = []

        for p in range(self.number_of_players):
            for card in self.player[p].get_hand():
                p_list.append(card.get_suit())
                p_list.append(card.get_value())

        for card in self.card:
            b_list.append(card.get_suit())
            b_list.append(card.get_value())

        p_list.extend(b_list)
        p_list.extend([hand_assignment])
        return (p_list)

    def excel_header(self):
        headers = [
            'Card 1 suit', 'Card 1 value', 'Card 2 suit', 'Card 2 value',
            'Card 3 suit', 'Card 3 value', 'Card 4 suit', 'Card 4 value',
            'Card 5 suit', 'Card 5 value', 'Card 6 suit', 'Card 6 value',
            'Card 7 suit', 'Card 7 value', 'Label'
        ]

        self.ws.append(headers)

    def save_excel_file(self):
        self.wb.save()

    # Get Functions
    def get_players(self):
        return self.player

    def get_cards(self):
        return self.card

    # Placeholder Code
    def game_state(self):
        return self.card, self.card

    # Set Function
    def set_number_of_players(self, number_of_players):
        self.number_of_players = number_of_players

    def print(self):
        color_map = {0: "red", 1: "red", 2: "white", 3: "white"}
        suit_map = {0: "\u2764", 1: "\u2666", 2: "\u2660", 3: "\u2663"}
        number_map = {
            2: '2',
            3: '3',
            4: '4',
            5: '5',
            6: '6',
            7: '7',
            8: '8',
            9: '9',
            10: '10',
            11: 'J',
            12: 'Q',
            13: 'K',
            14: 'A'
        }

        for player in self.get_players():
            player_cards = player.get_hand()

            print("Player " + str(player.get_name()))

            for card in player_cards:
                string_color = color_map[card.get_suit()]
                string_card = suit_map[card.get_suit()] + " " + number_map[
                    card.get_value()]
                print(colored(string_card, string_color), end=" ")

            print()

        print("Game Cards")
        for card in self.get_cards():
            string_color = color_map[card.get_suit()]
            string_card = suit_map[card.get_suit()] + " " + number_map[
                card.get_value()]
            print(colored(string_card, string_color), end="  ")
        print()
        print()
Пример #37
0
            else:
                print('Please enter a valid move number')


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)


# welcome
print('\nWelcome To Python Blackjack!\n')
deck = Deck()
deck.shuffle()
players = []

# set up players
names = get_player_names()
for name in names:
    players.append(Player(name))

for player in players:
    new_player, player.chips = get_player_bankroll(player.name)
    if new_player:
        print(
            f'Welcome {player.name}! Please accept these 1000 chips to begin.\n'
        )
    else:
Пример #38
0
"""
    A game of War with two players and deck of 52 playing cards
"""
from Deck import Deck
from Player import Player

ranks = [
    'Ace', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine',
    'Ten', 'Jack', 'Queen', 'King'
]
suits = ['Hearts', 'Spades', 'Clubs', 'Diamonds']

#set up the game
#create game deck
game_deck = Deck(suits, ranks)
game_deck.shuffle_deck()

#create players and decks
player_one = Player('Player One')
player_two = Player('Player Two')
while len(game_deck.cards) > 0:
    if len(game_deck.cards) % 2:
        player_one.add_to_deck([game_deck.deal_card()])
    else:
        player_two.add_to_deck([game_deck.deal_card()])

#being 'duel'
AT_WAR = True
GAME_ON = True
round_num = 0
while GAME_ON:
Пример #39
0
	def __init__(self):
		self.Deck = Deck()
		self.Deck.Shuffle()
Пример #40
0
    def playRound(self, n=13):
        # Initialize the round
        self.initializeRound(n)

        # Get the bets
        self.bettingRound()
        self.initialbets = self.bets

        # Initialize some state-dependent metrics to pass to AI
        self.card_played_by = {card.__str__(): None for card in Deck().cards}
        self.suit_trumped_by = {i: set() for i in range(4)}
        self.bet_deficits = list(self.bets)

        # Go through the rounds
        for t in range(0, self.num_rounds):
            # No lead suit yet
            Card.lead = -1
            self.cards_this_round = {i: None for i in range(4)}

            # Save the current hands for history
            self.H_history[t] = deepcopy(self.H)

            order = range(4)

            # Permute player order
            if t > 0:  # The previous winner should go first, then continue in order
                self.play_order[t] = order[self.T[t - 1]:] + order[:self.T[t -
                                                                           1]]
            else:  # Randomly choose who goes first
                first_player = rnd.randint(0, 3)
                self.play_order[
                    t] = order[first_player:] + order[:first_player]

            # Loop through players
            for p in self.play_order[t]:
                self.printVerbose(
                    str(p + 1) + ': ' + str(self.bets[p]) + ' bet, ' +
                    str(self.tricks[p]) + ' won')
                if self.player_strategy[p] == 0:  # Ask for human input
                    self.h[t][p] = self.humanInput(p)
                else:  # Ask for AI input with strategy in player_strategy[p]
                    self.h[t][p] = self.aiInput(p, t, self.player_strategy[p],
                                                self.H[p].validCards())
                # Set the lead suit, if it hasn't been yet
                if Card.lead == -1:
                    Card.lead = self.h[t][p].suit
                    self.leads[t] = Card.lead

                # Update the state for the playing NN
                self.update_state(p, t)

                # Display what was played
                self.printVerbose(str(p + 1) + ':  ' + str(self.h[t][p]))
                self.printVerbose('')

                # Update
                self.cards_this_round[p] = self.h[t][p]
                #update the card_played_by dict
                self.card_played_by[str(self.h[t][p])] = p
                if Card.lead != -1 and Card.lead != Card.trump:
                    if self.h[t][p].suit == Card.trump:
                        self.suit_trumped_by[Card.lead].add(p)

            # Find the winning player from the cards played this round
            self.T[t] = self.winner(self.h[t])
            self.tricks[self.T[t]] = self.tricks[self.T[t]] + 1
            self.printVerbose('Player ' + str(self.T[t] + 1) +
                              ' won the trick.')
            self.bet_deficits[self.T[t]] -= 1
Пример #41
0
# GAMEPLAY!
if __name__ == "__main__":

    player_Chips = Chips()
    print("Welcome to BlackJack!")

    while (True):
        print("How many chips would you like to bet? you have now {} ".format(
            player_Chips.total))

        # if y is int  , and you have Enough Chips to Play
        y = Error().Error_bet(player_Chips.total)
        player = Hand()
        dealer = Hand()
        card_in_game = Deck(Card().all_card)

        #  1 card to dealer
        random_choice = random.choices(
            card_in_game.cards)  # random ...[('3', 'Hearts')]....
        card_in_game.Deck_pop(card_in_game.find_idx(
            random_choice[0]))  # pop obj in card_in_game by idx
        dealer.add_card(
            random_choice,
            card_in_game.cart[random_choice[0][0]])  # add card to player
        #  2 card to dealer
        random_choice = random.choices(
            card_in_game.cards)  # random ...[('3', 'Hearts')]....
        card_in_game.Deck_pop(card_in_game.find_idx(
            random_choice[0]))  # pop obj in card_in_game by idx
        dealer.add_card(
Пример #42
0
def LetsPlay():
    global play_status
    global player_cards_drawn
    global dealer_cards_drawn
    global game_deck
    flag = True
    human_player = Player()

    # clear_output()
    print("Welcome to BLACK-JACK command line GAME!!")
    print("Initially YOU are given 5000 Chips in Hand for play")

    while flag:
        chips_on_bet = 0
        play_status = True
        game_deck = Deck()
        player_cards_drawn = []
        dealer_cards_drawn = []
        game_result = GAME_ON

        while True:
            chips_on_bet = input(
                "Enter Chips you want to bet(in multiples of 500): ")
            if chips_on_bet.isnumeric() and human_player.placebet(
                    int(chips_on_bet)):
                chips_on_bet = int(chips_on_bet)
                break
            else:
                print(
                    "Invalid input, please Try Again (Bet can't be greater than Chips in Hand)"
                )

        print("Drawing 2 cards for PLAYER and 1 card for HOUSE....")
        time.sleep(3)

        player_cards_drawn.append(game_deck.drawcard())
        player_cards_drawn.append(game_deck.drawcard())

        dealer_cards_drawn.append(game_deck.drawcard())

        print_table(play_status, dealer_cards_drawn, player_cards_drawn,
                    game_deck, chips_on_bet, human_player)

        player_choice = True
        count = 1
        while player_choice:
            print("\n1. Hit\n2. Stay\nInput your Choice(input 1 or 2): ")
            if int(input()) == 1:
                player_cards_drawn.append(game_deck.drawcard())
                game_result = generate_result()
                if game_result == GAME_ON:
                    # clear_output()
                    print_table(play_status, dealer_cards_drawn,
                                player_cards_drawn, game_deck, chips_on_bet,
                                human_player)
                    count += 1
                else:
                    play_status = False
                    break
            else:
                player_choice = False

        if game_result == GAME_ON:
            print("Now, Drawing cards for HOUSE....")
            time.sleep(5)
            for _ in range(1, count + 1):
                dealer_cards_drawn.append(game_deck.drawcard())
                game_result = generate_result()
                if game_result == GAME_ON:
                    # clear_output()
                    print_table(play_status, dealer_cards_drawn,
                                player_cards_drawn, game_deck, chips_on_bet,
                                human_player)
                else:
                    break

        game_result = generate_result()
        if game_result == PLAYER_WINS or game_result == DEALER_BUSTED:
            human_player.chips_in_hand += (2 * chips_on_bet)

        play_status = False
        if game_result == PUSH:
            human_player.chips_in_hand += chips_on_bet
        else:
            # clear_output()
            print_table(play_status, dealer_cards_drawn, player_cards_drawn,
                        game_deck, chips_on_bet, human_player)

        print("Do you wish to play again?(y/n): ")

        flag = input().lower() == 'y'

    print("Thank you for playing!")
Пример #43
0
from PrintHelper import print_table
import time
from Deck import Deck
from Player import Player

DEALER_WINS = 1
DEALER_BUSTED = -1
PLAYER_WINS = 2
PLAYER_BUSTED = -2
GAME_ON = 3
PUSH = -3
play_status = True
game_deck = Deck()
player_cards_drawn = []
dealer_cards_drawn = []


def generate_result():
    dealer_result = game_deck.GetSumOfCards(dealer_cards_drawn)
    player_result = game_deck.GetSumOfCards(player_cards_drawn)

    if dealer_result <= 21:
        if dealer_result > player_result and not play_status:
            return DEALER_WINS
        elif player_result > 21:
            return DEALER_WINS
    else:
        return DEALER_BUSTED

    if player_result <= 21:
        if dealer_result < player_result and not play_status:
Пример #44
0
 def compare_ranks(rank1, rank2):
     return Deck.rank_index(rank1) > Deck.rank_index(rank2)
class Game(object):
    def __init__(self):
        self.colors = ['red', 'green', 'blue', 'yellow', 'white']
        self.deck = Deck(self)
        self.player_names = []
        self.get_names()
        self.players = [Player(name) for name in self.player_names]
        self.hints = 8
        self.max_hints = 8
        self.fuses = 3
        self.board = Board(self.colors)
        self.deal_cards()
        self.turns_left = len(self.players)

        self.next_players = {}
        self.current = self.players[0]
        self.make_next_player_names()

        self.journal = {}
        for player in self.player_names:
            self.journal[player] = []

        self.play()

    # def get_names(self):
    #     while True:
    #         if len(self.player_names) >= 5:
    #             break
    #         value = raw_input("Enter a player's name. If all player names have been entered, type done.\n")
    #         if value == 'exit':
    #             os._exit(1)
    #         elif value == "done":
    #             if len(self.player_names) < 2:
    #                 print("There must be at least 2 players.")
    #                 continue
    #             break
    #         elif value in self.player_names:
    #             print("Each name must be unique. Try again.")
    #             continue
    #         else:
    #             self.player_names.append(value)

    def make_next_player_names(self):
        g = iter(list(range(1, len(self.player_names))))
        for player in self.players:
            try:
                self.next_players[player.name] = self.players[next(g)]
            except StopIteration:
                self.next_players[player.name] = self.players[0]

    def get_player(self, name):
        for player in self.players:
            if player.name == name:
                return player
        return None

    def deal_cards(self):
        for each in self.players:
            if len(self.players) <= 3:
                while len(each.hand) < 5:
                    each.hand.append(self.deck.deal())
            else:
                while len(each.hand) < 4:
                    each.hand.append(self.deck.deal())

    def play(self):
        possible_actions = ['empty', 'discard_card', 'play_card', 'give_hint']

        while self.turns_left > 0:
            self.print_board()

            if self.deck.len() == 0:
                self.turns_left -= 1
                print(
                    "\n There are no more cards to draw. This is your last turn."
                )

            if self.hints == 0:
                action = self.get_valid_string(
                    "\nPlayer {0}, choose an action: \n  [1] Discard \n  [2] Place a card. \n  There are no more hints left. \n \n"
                    .format(self.current.name), ['1', '2'])

            if self.hints > 0:
                action = self.get_valid_string(
                    "\nPlayer {0}, choose an action: \n  [1] Discard \n  [2] Place a card \n  [3] Give a hint. \n \n"
                    .format(self.current.name), ['1', '2', '3'])

            getattr(self.current, possible_actions[int(action)])(self)

            self.journal[self.current.name] = []
            self.current = self.next_players[self.current.name]
            print("Your turn is over.")
            self.clear_screen()
            print(
                "Pass the computer to {0}. Tell me when you're ready.".format(
                    self.current.name))
            self.clear_screen()

        final_score = sum(
            [card.number for card in self.board.displayed.values()])
        # print("Game over. Your final score is {0}.".format(final_score))
        # os._exit(1)

    #
    # def get_valid_string(self, prompt, valid_answers):
    #     while True:
    #         value = raw_input(prompt)
    #         if value == 'exit':
    #             os._exit(1)
    #         if value not in valid_answers:
    #             self.invalid_answers(value, valid_answers)
    #             continue
    #         else:
    #             break
    #     return value

    # def invalid_answers(self, value, valid_answers):
    #     os.system('clear')
    #     self.print_board()
    #     print(
    #         "\n{0} is not a valid response. Please try: {1}.\n".format(value, pretty_list_or(map(str, valid_answers))))

    def print_board(self):
        if self.journal[self.current.name]:
            print("\nSince you last played: ")
            for line in self.journal[self.current.name]:
                print(line)
        print("\n" + self.board.__repr__())
        print("Hints available: " + str(self.hints))
        print("Fuses left: {0}\n".format(str(self.fuses)))
        if self.board.no_more:
            print("There are no more [{0}] cards. \n".format("] [".join(
                map(Card.__repr__, self.board.no_more))))

        self.current.my_cards()
        other_player = self.next_players[self.current.name]
        while other_player != self.current:
            print(other_player.__repr__())
            other_player = self.next_players[other_player.name]
Пример #46
0
from typing import List

colors = dict(pink='\033[95m',
              blue='\033[94m',
              cyan='\033[96m',
              green='\033[92m',
              yelow='\033[93m',
              red='\033[91m',
              white='\033[0m',
              bold='\033[1m',
              under='\033[4m')

match: bool = True
order_numbers = 'Q J K A 2 3'
order_suits = '♦ ♠ ♥ ♣'
deck: Deck = Deck('Q J K A 2 3'.split(), '♠ ♣ ♥ ♦'.split())
teams: List[pl.Team] = []
players: List[pl.Player] = []


def set_number_of_players() -> int:
    while True:
        try:
            number: int = int(
                input(colors['white'] +
                      "Enter the number of players (2, 4 or 6): "))
            if number not in [2, 4, 6]:
                print(colors['red'] + 'invalid number')
            else:
                return number
        except ValueError:
class Game(object):
  def __init__(self, numPlayers=1, numAI=1):
    """
    basic set up for a game where:
    numPlayers = the total number of  human players
    numAI = the number of the total players that are AI
    """
    self.totPlayers = numPlayers + numAI
    # checking that there are atleast 2 players
    if (self.totPlayers) < 2:
      raise Exception('need atleast 2 players to play the game')

    self.deck = Deck()

    self.numPlayers = numPlayers
    self.numAI = numAI

    self.winners = []
    self.losers = []
    self.tied = []

    # For games with lives and discard piles.
    self.lives = [3 for i in range(self.totPlayers)]
    self.discardPile = []
    self.theOneWhoKnocked = None

    # setting up the players
    self.players = []
    [self.players.append(Player(len(self.players), game=self, AI=len(self.players) >= numPlayers)) for i in
     range(numPlayers + numAI)]

    for player in self.players:
      self.defineMoves(player)

    for i in range(len(self.players)):
      self.players[i].setPrev(self.players[i - 1])
      self.players[i].setNext(self.players[(i + 1) % len(self.players)])

  def play(self):
    self.dealHands()
    self.played = [self.deck.cards.pop()]

    player = self.players[0]
    while not self.endCondition():
      print("--------------------------------------")
      print("It is player " + str(player.idNum) + " turn")
      played = player.play(self.played[-1])
      if played: self.played.append(played)
      player = self.playerPlayed(player, played) if played else self.cantPlay(player)

    self.winMessage()

  def refillDeck(self):
    keep = [self.played.pop()]
    add = []
    toAdd = self.played
    for it in toAdd:
      if type(it) is Card:
        add.append(it)

    self.deck.refill(add)
    self.played = keep
    # print("+++++++++++++++++++++++++++deck refilled from discarded +++++++++++++++")
    print(self.played)

  def defineMoves(self, player):
    if player.AI:
      player.AIFunction = self.defineAI
    else:
      player.humanFunction = self.defineHuman

  def endCondition(self):
    raise Exception("implemention must define this")

  def calculateScore(self, player):
    raise Exception("implemention must define this")

  def validPlays(self, player):
    raise Exception("implemention must define this")

  def cantPlay(self, player):
    raise Exception("implemention must define this")

  def playerPlayed(self, player, played):
    raise Exception("implemention must define this")

  def dealHands(self):
    raise Exception("implemention must define this")

  def winMessage(self):
    raise Exception("implementation must define this")

  def defineAI(self, player, allowed, prevPlay):
    raise Exception("implementation must define this")

  def defineHuman(self, player, allowed, prevPlay):
    raise Exception("implementation must define this")

  def __str__(self):
    return str(self.players)
Пример #48
0
class Game:
    def __init__(self):
        self.deck = Deck()
        self.players = self.playerSetUp()
        self.cardsPlayed = []
        self.dealerChosen = False
        self.startingPlayerIndex = 0

    def deal(self):
        while self.deck.cards:
            for player in self.players:
                player.draw(self.deck)
        for player in self.players:
            player.sortHand()

    def playerSetUp(self):
        players = []
        for i in range(4):
            if i == 0:
                name = input("Please enter YOUR name: ")
                players.append(Player(name))
            else:
                name = input("Please enter a player name: ")
                players.append(Player(name))
        return players

    def cutForDealer(self):
        cutCards = []
        lowPlayers = []
        for i in range(4):
            d = self.deck.drawCard()
            cutCards.append(d)
            print(self.players[i].name + " drew the " + d.name())
        lowestCard = Card("Plops", 99)
        for i in range(4):
            if cutCards[i].value < lowestCard.value:
                lowestCard = cutCards[i]
        lowestCard.show()
        for i in range(4):
            if cutCards[i].value <= lowestCard.value:
                lowPlayers.append(i)
        print(lowPlayers)
        if len(lowPlayers) != 1:
            print("Low players are:")
            print(lowPlayers)
            print("Equal lowest cards. Try again!")
        else:
            print(self.players[lowPlayers[0]].name +
                  " drew the lowest card so they will pitch.")
            self.startingPlayerIndex = lowPlayers.copy()[0]
            self.dealerChosen = True
            return self.startingPlayerIndex

    def round(self):
        self.trick(self.startingPlayerIndex)

    def trick(self, leadPlayerIndex):
        trick = []
        for i in range(4):
            if i == 0:
                leadCard = Card("Plops", 99)
            else:
                leadCard = trick[0]
            currentPlayerIndex = (leadPlayerIndex + i) % 4
            if currentPlayerIndex == 0:
                print("Your legal cards are: ")
                for c in self.players[0].legalCards(leadCard):
                    c.show()
                # self.players[0].legalCards(leadCard,self.heartsBroken).show()
                number = int(input("Input number of card you want: "))
                try:
                    card = self.players[0].legalCards(leadCard)[number]
                except:
                    print("NOT GOOD")
            else:
                rand = random.randint(
                    0,
                    len(self.players[currentPlayerIndex].legalCards(
                        leadCard, self.heartsBroken)) - 1)
                card = self.players[currentPlayerIndex].legalCards(
                    leadCard)[rand]
            self.players[currentPlayerIndex].hand.remove(card)
            trick.append(card)
            self.cardsPlayed.append(card)
            # print(self.players[currentPlayerIndex].name + " played the " + str(card.value) + " of " + card.suit)
            print(self.players[currentPlayerIndex].name + " played the " +
                  card.name())
        winningValue = 0
        for c in trick:
            if c.suit == leadCard.suit and c.value > winningValue:
                winningCard = c
                winningValue = c.value
        winner = self.players[(self.startingPlayerIndex +
                               trick.index(winningCard)) % 4]
        print(winner.name + " won the trick.")
        for c in trick:
            if c.suit == "Hearts":
                winner.points += 1
            if c.equals(Card("Spades", 12)):
                winner.points += 13
        self.startingPlayerIndex = self.players.index(winner)

    def run(self):
        if self.deck.cards == []:
            self.deck = Deck()
        self.deck.shuffle()
        while self.dealerChosen == False:
            self.startingPlayerIndex = self.cutForDealer()
            self.deck = Deck()
            self.deck.shuffle()
        self.deal()
        print("Your starting hand is: ")
        self.players[0].showHand()
        while len(self.cardsPlayed) != 52:
            self.round()
        for p in self.players:
            p.showScore()
        self.cardsPlayed = []
Пример #49
0
 def __init__(self):
     self.deck = Deck()
     self.turn_count = 0
     self.player_count = 1
     self.index = 1
     self.hands = []
Пример #50
0
 def __init__(self):
     self.deck = Deck()
     self.players = self.playerSetUp()
     self.cardsPlayed = []
     self.dealerChosen = False
     self.startingPlayerIndex = 0
Пример #51
0
class Game:
    def __init__(self):
        # self.players_cards = []
        # self.dealers_cards = []

        self.player = Player()
        self.dealer = Dealer()
        self.deck = Deck()
        self.deck.build_deck()
        self.deck.shuffle()

    #This runs the game
    def game_running(self):
        in_play = True
        while in_play:
            deck = Deck()
            # If either hand has 0 cards, deal a random card from the card list
            while len(self.player.hand) < 1 and len(self.player.hand) < 1:
                player_first_card = deck.deal()
                self.player.add_card(player_first_card)
                dealer_first_card = deck.deal()
                self.dealer.add_card(dealer_first_card)
            # Show the hand and ask player to hit or stay
            print(f" Your hand is: {self.player.show_hand()}")
            # print(f"Dealer's hand is: {self.dealer.display()}")
            choice = input("Please choose [Hit / Stay] ").lower()
            while choice not in ["h", "s", "hit", "stay"]:
                choice = input(
                    "Please enter 'hit' or 'stay' (or H/S) ").lower()
            # If they hit, add card to their hand and update the score
            if choice == "hit" or choice == "h":
                #Deal a card to both player and dealer
                self.player.add_card(deck.deal())
                self.dealer.add_card(deck.deal())
                #This checks if dealer or player has blackjack
                player_blackjack, dealer_blackjack = self.check_blackjack()
                #If blackjack is True, this ends the game
                if player_blackjack or dealer_blackjack:
                    return player_blackjack, dealer_blackjack
            elif choice == "stay" or choice == "s":
                #If player has higher score, player wins
                if self.player.get_hand() > self.dealer.get_hand():
                    print("Your hand was higher, you win!")
                    print("Final Results")
                    print("Dealer's hand:", self.dealer.reveal())
                else:
                    #If dealer has higher score, dealer wins, and reveals their cards
                    print("You busted. The dealer wins")
                    print("Final Results")
                    print("Dealer's hand:", self.dealer.reveal())

    # Checks if player or dealer has reached 21 or if the player has higher hand
    def check_blackjack(self):
        player_blackjack = False
        dealer_blackjack = False
        players_hand = self.player.calculate_hand()
        dealers_hand = self.dealer.calculate_hand()
        if players_hand == 21 or dealers_hand > 21:
            player_blackjack = True
        if dealers_hand == 21 or players_hand > 21:
            dealer_blackjack = True
        return player_blackjack, dealer_blackjack

    # When game is over ask to play
    # This method returns true or false if the player wants to play again
    def is_game_over(self, player_has_blackjack, dealer_has_blackjack):
        game_over = False
        # If this returns True then the game is over
        if player_has_blackjack and dealer_has_blackjack:
            game_over = True
            print("Draw!")
        if player_has_blackjack:
            game_over = True
            print("dealer busted. you win!")
            print(self.dealer.reveal())
            print(self.player.show_hand())
        if dealer_has_blackjack:
            game_over = True
            print(self.dealer.reveal())
            print(self.player.show_hand())
            print("You busted. The dealer wins")
        if game_over == True:
            play_again = input("Would you like to play again? Y/N ").lower()
            if play_again == "n":
                print("Thanks for playing BlackJack!")
                return True
            else:
                return False
Пример #52
0
class Game():
    """docstring for Game"""
    def __init__(self):
        self.deck = Deck()
        self.deck.shuffle()

        self.table = Table()

        for i in range(12):
            self.table.addCard(self.deck.draw())
        self.table.print()

    def begin(self):
        while not self.table.existSet():
            for i in range(3):
                self.table.addCard(self.deck.draw())

        print("How many players will be playing?")
        num_players = int(input("Enter a number greater than 0: "))

        while num_players < 1:
            num_players = input("Enter a number greater than 0: ")

        self.table.print()
        self.players_score = []
        for i in range(0, num_players):
            self.players_score.append(0)

        #for test
        print(self.players_score)

    def play(self):
        print("Who finds a set?")
        print(
            "Please enter your player number and the cards you pick (separated by space): "
        )
        print(
            "For example, player1 picks cards 1, 2 ,3 should enter 1 1 2 3 in the command line."
        )
        userInput = input().split()

        player = int(userInput.pop(0))

        userInput = list(map(int, userInput))
        userInput.sort()
        userInput.reverse()

        print(userInput)
        card1 = self.table.getCard(int(userInput[0]))
        card2 = self.table.getCard(int(userInput[1]))
        card3 = self.table.getCard(int(userInput[2]))

        while not self.table.isSet(card1, card2, card3):
            print("Sorry, it is not a set! Try again!")
            print(
                "Please enter your player number and the cards you pick (separated by space): "
            )
            print(
                "For example, player1 picks cards 1, 2 ,3 should enter 1 1 2 3 in the command line."
            )
            userInput = input().split()
            player = int(userInput.pop(0))

            userInput = list(map(int, userInput))
            userInput.sort()
            userInput.reverse()

            card1 = self.table.getCard(userInput[0])
            card2 = self.table.getCard(userInput[1])
            card3 = self.table.getCard(userInput[2])

        self.players_score[player - 1] += 1
        print("Congraduations, Player%i found a set!" % (player))

        self.table.removeCard(userInput[0])
        self.table.removeCard(userInput[1])
        self.table.removeCard(userInput[2])

        for i in range(1, 4):
            self.table.addCard(self.deck.draw())

        while not self.table.existSet():
            for i in range(1, 4):
                self.table.addCard(self.deck.draw())

        self.table.print()

    def players_score(self):
        return self.players_score

    def finish(self):
        return self.deck.size() == 0 and not self.table.existSet()
Пример #53
0
    def __init__(self):
        self.winner = 0
        self.draw = False
        self.has_winner = False
        self.table: List[List[Card]] = [
            [
                W_C.copy(),
                S_10.copy(),
                S_Q.copy(),
                S_K.copy(),
                S_A.copy(),
                D_2.copy(),
                D_3.copy(),
                D_4.copy(),
                D_5.copy(),
                W_C.copy()
            ],
            [
                S_9.copy(),
                H_10.copy(),
                H_9.copy(),
                H_8.copy(),
                H_7.copy(),
                H_6.copy(),
                H_5.copy(),
                H_4.copy(),
                H_3.copy(),
                D_6.copy()
            ],
            [
                S_8.copy(),
                H_Q.copy(),
                D_7.copy(),
                D_8.copy(),
                D_9.copy(),
                D_10.copy(),
                D_Q.copy(),
                D_K.copy(),
                H_2.copy(),
                D_7.copy()
            ],
            [
                S_7.copy(),
                H_K.copy(),
                D_6.copy(),
                C_2.copy(),
                H_A.copy(),
                H_K.copy(),
                H_Q.copy(),
                D_A.copy(),
                S_2.copy(),
                D_8.copy()
            ],
            [
                S_6.copy(),
                H_A.copy(),
                D_5.copy(),
                C_3.copy(),
                H_4.copy(),
                H_3.copy(),
                H_10.copy(),
                C_A.copy(),
                S_3.copy(),
                D_9.copy()
            ],
            [
                S_5.copy(),
                C_2.copy(),
                D_4.copy(),
                C_4.copy(),
                H_5.copy(),
                H_2.copy(),
                H_9.copy(),
                C_K.copy(),
                S_4.copy(),
                D_10.copy()
            ],
            [
                S_4.copy(),
                C_3.copy(),
                D_3.copy(),
                C_5.copy(),
                H_6.copy(),
                H_7.copy(),
                H_8.copy(),
                C_Q.copy(),
                S_5.copy(),
                D_Q.copy()
            ],
            [
                S_3.copy(),
                C_4.copy(),
                D_2.copy(),
                C_6.copy(),
                C_7.copy(),
                C_8.copy(),
                C_9.copy(),
                C_10.copy(),
                C_6.copy(),
                D_K.copy()
            ],
            [
                S_2.copy(),
                C_5.copy(),
                S_A.copy(),
                S_K.copy(),
                S_Q.copy(),
                S_10.copy(),
                S_9.copy(),
                S_8.copy(),
                S_7.copy(),
                D_A.copy()
            ],
            [
                W_C.copy(),
                C_6.copy(),
                C_7.copy(),
                C_8.copy(),
                C_9.copy(),
                C_10.copy(),
                C_Q.copy(),
                C_K.copy(),
                C_A.copy(),
                W_C.copy()
            ],
        ]

        self.deck = Deck()
        self.player1 = Player(self.deck, 1, self)
        self.player2 = Player(self.deck, 2, self)
Пример #54
0
 def __shuffle(self):  #creates new deck
     self.Deck = Deck()
     self.Deck.shuffle()
Пример #55
0
 def gen_all_child_states(self, expand_type):
     if self.node_type == 'random':
         curr_deck = self.game_state.curr_player().deck
         other_deck = self.game_state.other_player().deck
         grouped = Deck.group(other_deck)
         types = [group[0].get_type() for group in grouped]
         probs = [len(group) / len(grouped) for group in grouped]
         probs /= np.sum(probs)
         new_children = []
         for t, p in zip(types, probs):
             new_state = self.game_state.copy()
             new_state.turn_stop()
             new_state.turn_start(t)
             new_children.append(
                 MTCSPlayer.MTCSNode(new_state,
                                     node_type='move',
                                     card_type=t,
                                     prob=p))
         self.add_children(new_children)
     elif self.node_type == 'move':
         if expand_type == 'Full':
             curr_hand = self.game_state.curr_player().hand
             curr_table = self.game_state.curr_player().on_table
             spots_on_table = TABLE_SIZE - len(curr_table)
             legal_play_cards = list_of_possible_card_plays(
                 curr_hand, spots_on_table,
                 self.game_state.curr_player().mana)
             all_posible_plays = [
                 a + b for a, b in list(
                     itertools.product(legal_play_cards, [
                         list(e)
                         for e in self.game_state.possible_plays()
                     ]))
             ]
             new_children = []
             for nsa in all_posible_plays:
                 try:
                     new_state = self.game_state.copy()
                     for a in nsa:
                         new_state.make_action(*a)
                     new_children.append(
                         MTCSPlayer.MTCSNode(new_state,
                                             node_type='random',
                                             actions_from_parent=nsa))
                 except:
                     pass
             self.add_children(new_children)
         elif expand_type == 'PlayCardNum' or expand_type == 'PlayCardScr':
             curr_hand = self.game_state.curr_player().hand
             curr_table = self.game_state.curr_player().on_table
             spots_on_table = TABLE_SIZE - len(curr_table)
             legal_play_cards = list_of_possible_card_plays(
                 curr_hand, spots_on_table,
                 self.game_state.curr_player().mana)
             k = 2 if len(legal_play_cards) < 5 else 4
             scores = [len(e) for e in legal_play_cards] if expand_type == 'PlayCardNum' else \
                 [calc_att_plus_hp_for_cards(cards) for cards in [[id_from(self.game_state.curr_player().hand, play[1]) for play in plays] for plays in legal_play_cards]]
             best_inds = np.argpartition(scores, -k)[-k:]
             all_posible_plays = [
                 a + b for a, b in list(
                     itertools.product(
                         [legal_play_cards[i] for i in best_inds], [
                             list(e)
                             for e in self.game_state.possible_plays()
                         ]))
             ]
             new_children = []
             for nsa in all_posible_plays:
                 try:
                     new_state = self.game_state.copy()
                     for a in nsa:
                         new_state.make_action(*a)
                     new_children.append(
                         MTCSPlayer.MTCSNode(new_state,
                                             node_type='random',
                                             actions_from_parent=nsa))
                 except:
                     pass
             self.add_children(new_children)
         else:
             raise Exception('bad expand_type value')
Пример #56
0
class Dealer(object):
    def __init__(self):
        self.Deck = Deck()
        self.__shuffle()
        self.cards = []
        self.winStatus = True
        self.bust = False
        self.matchBet = 0

    def makeBet(self, playerBet):
        self.matchBet += playerBet

    def getMatchBet(self):
        return self.matchBet

    def clearHand(self):
        self.cards = []
        self.bust = False
        self.matchBet = 0

    def __shuffle(self):  #creates new deck
        self.Deck = Deck()
        self.Deck.shuffle()

    def deal(self):
        return self.Deck.topCard()

    def checkCardsLeftInDeck(self):
        if len(self.Deck) < 20:
            self.__shuffle()

    #skip card[0] to keep it unknown until the end.
    #also, stop picking up cards when dealer has a total of 17 points
    def hand(self):
        print("Dealer has ", end="")
        for i in range(len(self.cards)):
            if i > 0:
                print(", ", end="")
            if i == (len(self.cards) - 1) and len(self.cards) >= 1:
                print("and ", end="")
            self.cards[i].showCard()
        return self.totalScore()

    def addCard(self, Card):
        self.cards.append(Card)

    def totalScore(self):
        total = 0
        for i in range(len(self.cards)):
            total += self.cards[i].getPlayableValue(
            )  # doesn't incorporate Ace yet
        return total

    def getCards(self):
        return self.cards

    def playerWon(self):
        self.winStatus = True

    def hasPlayerWon(self):
        return self.winStatus

    def playerBust(self):
        return self.bust

    def bustPlay(self):
        self.bust = True
Пример #57
0
from Player import Player
from Deck import Deck
from Dealer import Dealer

player = Player([], False, 100, 0, True)
dealer = Dealer([], False, False, False, False)
gameEnd = False

# When the game starts, player turn is automatically set to true.
while player.playerTurn:
    player.gameType(dealer)

# Game running
while not gameEnd:
    deck = Deck([])
    deck.createDeck()

    player = Player([], player.isUser, player.balance, 0, True)
    dealer = Dealer([], dealer.isUser, False, False, False)

    # Player bets
    if player.isUser:
        print(f"Your current balance is: {player.balance}")
        player.desiredBet()
        print(f"Bet: {player.bet}")
    # Player bet is fixed, if dealer gametype is chosen
    if not player.isUser:
        player.bet = 20

    # Creating the starting hands, and printing to terminal
    player.hand.append(dealer.dealCards(deck.deck))
Пример #58
0
 def createDeck(self):
     if self.rigged:
         self.deck = RiggedDeck(1)
     else:
         self.deck = Deck(1)
Пример #59
0
 def make_deck(self, joker):
     """Initialize the deck with the joker parameter."""
     deck = Deck(joker, 100 - Card.width / 2, 75 - Card.height / 2)
     deck_area = DeckArea(self.scheme[3], self.hands)
     deck_area.update(deck)
     return deck, deck_area
Пример #60
0
 def fetchDeck(self, url):
     html = self.getHTML(url)
     for a in html.find_all('a'):
         if a.get('href') and '/deck/download' in a.get('href'):
             return self.fetchDeckList('https://www.mtggoldfish.com/{0}'.format(a.get('href')))
     return Deck(url)