def redistribute(self, board): #gets all cards from players # if printsOn: # print ("Redistributing cards... Current hands:") # for player in board.players: # print player.hand cards = [] numOfCards = {} for player in board.players: if player.name != self.ai: num = 0 for suit in player.hand.hand: cards = cards + suit num += len(suit) numOfCards[player.name] = num #distribute randomly for player in board.players: if player.name != self.ai: hand = Hand() for x in range(numOfCards[player.name]): index = randint(0,len(cards)-1) cardAdd = cards[index] cards.remove(cardAdd) hand.addCard(cardAdd) player.hand = hand
class Player(): var = 5 def __init__(self, name, cards=None): self.name = name self.hand = Hand(cards) def hit(self, card): self.hand.addCard(card) def score(self): return self.hand.score()
class Player: def __init__(self, name): self.name = name self.hand = Hand() self.score = 0 self.roundScore = 0 self.tricksWon = [] def addCard(self, card): self.hand.addCard(card) def getInput(self, option): card = None while card is None: card = raw_input(self.name + ", select a card to " + option + ": ") return card def play(self, option='play', c=None, auto=False, state=None): if not c is None: return self.hand.playCard(c) elif auto: card = self.hand.getRandomCard() else: card = self.getInput(option) return card def trickWon(self, trick): self.roundScore += trick.points def add26(self): self.score += 26 def subtract26(self): self.score -= 26 def hasSuit(self, suit): return len(self.hand.hand[suit.iden]) > 0 def removeCard(self, card): self.hand.removeCard(card) def discardTricks(self): self.tricksWon = [] def hasOnlyHearts(self): return self.hand.hasOnlyHearts()
class Player(object): def __init__(self, playerLogic, name): self.iplayer = playerLogic self.name = name self.hand = Hand() self.money = 1000 self.active = True def acceptCard(self, card): self.hand.addCard(card) def isBroke(self): return self.money <= 0 def bust(self): self.active = False def getHandValue(self): value = self.hand.getValue() if value > 21: self.bust() return value def cardCount(self): return len(self.hand.cards) def makeWager(self): wager = self.iplayer.makeWager(self.money) return wager def isActive(self): return self.active def adjustBalance(self, amount): self.money += amount def resetHand(self): self.hand = Hand() self.active = True def executeAction(self, admin): legalActions = [] for action in constants.ACTIONS: if action.legal(self, admin): legalActions.append(action) action = self.iplayer.chooseAction(self.hand, admin, legalActions) print self.name + " chooses to " + action.actionName() action.effect(self, admin)
def discard(players): '''Promp players to discard cards and use discarded cards to build the crib. returns crib (Hand)''' crib = Hand() playerNum = 1 for player in players: for i in range(0, 2): if i == 0: string = 'first' else: string = 'second' string = string + " card to discard: \n" print(player.hand) discardIndex = getInput(playerNum, string) crib.addCard(player.hand.remCard(int(discardIndex) - 1)) playerNum += 1 return crib
class Player: def __init__(self, name, no): self.name = name self.hand = Hand() self.playerNum=no self.score = 0 self.tricksWon = [] def addCard(self, card): self.hand.addCard(card) def getInput(self, option): card = None while card is None: card = raw_input(self.name + ", select a card to " + option + ": ") return card def play(self): input = raw_input(self.name) rank=Hand.strToCard(input)[0] suit=Hand.strToCard(input)[1] card=Card(rank,suit) self.removeCard(card) return card def clearCards(self): self.hand = Hand() def trickWon(self, trick): self.score += trick.points def hasSuit(self, suit): return len(self.hand.hand[suit.iden]) > 0 def removeCard(self, card): self.hand.removeCard(card) def discardTricks(self): self.tricksWon = [] def hasOnlyHearts(self): return self.hand.hasOnlyHearts()
class Player: def __init__(self, name, auto=False): self.name = name self.hand = Hand() self.score = 0 self.tricksWon = [] def addCard(self, card): self.hand.addCard(card) def getInput(self, option): card = None while card is None: card = raw_input(self.name + ", select a card to " + option + ": ") return card def play(self, option='play', c=None, auto=False): if auto: card = self.hand.getRandomCard() elif c is None: card = self.getInput(option) else: card = c if not auto: card = self.hand.playCard(card) return card def trickWon(self, trick): self.score += trick.points def hasSuit(self, suit): return len(self.hand.hand[suit.iden]) > 0 def removeCard(self, card): self.hand.removeCard(card) def discardTricks(self): self.tricksWon = [] def hasOnlyHearts(self): return self.hand.hasOnlyHearts()
class Player(): def __init__(self, nme: str, lt: int): self.deck = Deck() self.hand = Hand() self.manaPool = [0, 0, 0, 0, 0, 0] #wubrg self.name = nme self.lifetotal = lt self.graveyard = [] self.exile = [] self.permanents = [] def draw(self): self.hand.addCard(self.deck.draw()) def showHand(self): self.hand.showHand() def tutor(self, name): self.hand.addCard(self.deck.tutor(name))
class Player: def __init__(self, name, auto=False): self.name = name self.hand = Hand() self.score = 0 self.tricksWon = [] def addCard(self, card): self.hand.addCard(card) def getInput(self, option): card = None while card is None: card = input(self.name + ", select a card to " + option + ": ") return card def play(self, option='play', c=None, auto=False): # if auto: # card = self.hand.getRandomCard() # elif c is None: # card = self.getInput(option) # else: # card = c # if not auto: # card = self.hand.playCard(card) # return card raise NotImplementedError("Must define type of player") def trickWon(self, trick): self.score += trick.points def hasSuit(self, suit): return len(self.hand.hand[suit.iden]) > 0 def removeCard(self, card): self.hand.removeCard(card) def discardTricks(self): self.tricksWon = [] def hasOnlyHearts(self): return self.hand.hasOnlyHearts()
def redistribute(self, board): cards = [] numOfCards = {} for player in board.players: if player.name != self.ai: num = 0 for suit in player.hand.hand: cards = cards + suit num += len(suit) numOfCards[player.name] = num #distribute randomly for player in board.players: if player.name != self.ai: hand = Hand() for x in range(numOfCards[player.name]): index = randint(0, len(cards) - 1) cardAdd = cards[index] cards.remove(cardAdd) hand.addCard(cardAdd) player.hand = hand
class Player(object): ''' Represents a player in the UNO game. Can be human, or can be controlled by an AI. ''' def __init__(self, name, initcards): ''' Constructs a new Player ''' self._name = name self._hand = Hand() for card in initcards: self._hand.addCard(card) def getCurrentHand(self): ''' Returns the current set of cards in the Players hand. ''' return self._hand.getCards() def testMove(self, current, card): ''' Test if playing card with the current card current is a valid move ''' if card.isWild(): #may always be played, however WD4 requires player to not have current color if card.getData() == "wild draw four" and self.hasCardsOfColor(current.getColor()): return False return True if card.getColor() == current.getColor() or card.getData() == current.getData(): return True else: return False def hasCardsOfColor(self, color): for card in self._hand.getCards(): if card.getColor() == color: return True def getPlayableCards(self, current): ''' Return a list of cards that are valid moves''' res = [] for card in self._hand.getCards(): if self.testMove(current, card): res.append(card) return res def getName(self): ''' Returns name of player ''' return self._name def giveCard(self, cards): ''' Add card(s) to the player's hand ''' if isinstance(cards, Card): self._hand.addCard(cards) else: for card in cards: self._hand.addCard(card) def removeFromHand(self, card): ''' Remove given card from player's hand ''' self._hand.removeCard(card)
class Player: def __init__(self, name, player_type, game, player=None): if player is not None: self.name = player.name self.hand = player.hand self.score = player.score self.roundscore = player.roundscore self.tricksWon = player.tricksWon self.type = player.type self.gameState = player.gameState else: self.name = name self.hand = Hand() self.score = 0 self.roundscore = 0 self.tricksWon = [] self.type = player_type self.gameState = game def __eq__(self, other): return self.name == other.name def __str__(self): return self.name def __repr__(self): return self.__str__() def __hash__(self): return hash(repr(self)) def addCard(self, card): self.hand.addCard(card) # 随机选则一张可以出的牌 def randomPlay(self): return choice(self.gameState.getLegalPlays(self)) # 出大牌 def naiveMaxAIPlay(self): gameState = self.gameState validClubs = [] validDiamonds = [] validSpades = [] validHearts = [] validHand = [validClubs, validDiamonds, validSpades, validHearts] for suit in range(0,4): handSuit = self.hand.hand[suit] for card in handSuit: if gameState.isValidCard(card,self): validHand[suit].append(card) #if first, play highest card in a random suit if gameState.currentTrick.isUnset(): if gameState.heartsBroken == True or self.hasOnlyHearts(): suitRange = 3 else: suitRange = 2 randomSuit = randint(0,suitRange) return Hand.highestCard(validHand[randomSuit]) #if not first: else: # print("Not going first!") trickSuit = gameState.currentTrick.suit.iden #if there are cards in the trick suit play highest card in trick suit if(len(validHand[trickSuit]) > 0): # print("Still cards in trick suit") return Hand.highestCard(validHand[trickSuit]) else: # print("No cards in trick suit") #play cards by points, followed by rank minPoints = sys.maxsize minCard = None for suit in range(0,4): for card in validHand[suit]: cardPoints = -card.rank.rank if card.suit == Suit(hearts): cardPoints -= 15 #Greater than rank of all non-point cards if card.suit == Suit(spades) and card.rank == Rank(queen): cardPoints -= 13 if cardPoints < minPoints: minPoints = cardPoints minCard = card return minCard #should never get here #raise Exception("failed programming") #return None # 尽量避免获得牌权 def naiveMinAIPlay(self): #get list of valid cards gameState = self.gameState validClubs = [] validDiamonds = [] validSpades = [] validHearts = [] validHand = [validClubs, validDiamonds, validSpades, validHearts] for suit in range(0,4): handSuit = self.hand.hand[suit] for card in handSuit: if gameState.isValidCard(card,self): validHand[suit].append(card) # self.print_hand(validHand) #if first, play lowest card in a random suit if gameState.currentTrick.isUnset(): # print("Going first!") #include hearts if hearts not broken or only has hearts if gameState.heartsBroken == True or self.hasOnlyHearts(): suitRange = 3 else: suitRange = 2 randomSuit = randint(0,suitRange) #return lowest card # print("Current trick suit is: ", gameState.currentTrick.suit.iden) # print("Going first and playing lowest card") return Hand.lowestCard(validHand[randomSuit]) #if not first: else: # print("Not going first!") trickSuit = gameState.currentTrick.suit.iden #if there are cards in the trick suit play lowest card in trick suit if(len(validHand[trickSuit]) > 0): # print("Still cards in trick suit") return Hand.lowestCard(validHand[trickSuit]) else: # print("No cards in trick suit") #play cards by points, followed by rank maxPoints = -sys.maxsize maxCard = None for suit in range(0,4): for card in validHand[suit]: cardPoints = card.rank.rank if card.suit == Suit(hearts): cardPoints += 15 #Greater than rank of all non-point cards if card.suit == Suit(spades) and card.rank == Rank(queen): cardPoints += 13 if cardPoints > maxPoints: maxPoints = cardPoints maxCard = card return maxCard # 模特卡罗模拟 def monteCarloAIPlay(self): mcObj = MonteCarlo(self.gameState, self.name) mcObj.update(self.gameState.cardsPlayed) card = mcObj.getPlay() return card # 出牌框架 def play(self, option='play', c=None, auto=False): card = None if c is not None: card = c card = self.hand.playCard(card) #elif self.type == PlayerTypes.Human: #card = self.humanPlay(option) elif self.type == PlayerTypes.Random: card = self.randomPlay() elif self.type == PlayerTypes.NaiveMinAI: card = self.naiveMinAIPlay() elif self.type == PlayerTypes.NaiveMaxAI: card = self.naiveMaxAIPlay() elif self.type == PlayerTypes.MonteCarloAI: card = self.monteCarloAIPlay() return card def trickWon(self, trick): # 赢牌后更新得分 self.roundscore += trick.points def hasSuit(self, suit): return len(self.hand.hand[suit.iden]) > 0 def removeCard(self, card): self.hand.removeCard(card) def hasOnlyHearts(self): return self.hand.hasOnlyHearts()
class Player: def __init__( self, name ): #keep track of player name self.name = name # keep track of where the player is self.position = 0 # keep track of player's hand self.hand = Hand() # keep track of played cards self.playable = Hand() self.playableVals = [] #keep track of if we can play self.ableToPeg = True self.playing = True # method to move the player forward in position by a number of points def move( self, points ): #move the position forward by the number of points self.position += points #check if we have won if self.position > 120: print( self.name + " has won the game! Exiting..." ) exit() #otherwise print where we are else: #print current location print( self.name + " is now at " + str( self.position ) ) # function for updating the hand def update( self ): # add vals to playable and playableVals for x in range( 0, 4 ): # add the cards to the hands self.playableVals.append( self.hand.cardVals[x][0] + 1 ) self.playable.addCard( self.hand.cardNums[x] ) # denote we have a new hand and therefore can play self.ableToPlay = True self.playing = True def parse( self, card ): try: toThrow = int( card ) return toThrow except: print( card + " is not a valid integer!" ) return -1 # function for playing in pegging def play( self, score, discard, ai, isAi ): # denote whos turn it is print( self.name + "'s turn! \n" ) # make variable to store played card played = -1 # check if we can play any cards if len( self.playableVals ) == 0: #denote we are out of cards print( self.name + " is out of cards!" ) self.playing = False self.ableToPeg = False return -1 # make boolean for keeping track of if we can play any cards canPlay = [False] * len( self.playableVals ) playPossible = False # check if we have any playable cards for x in range( 0, len( self.playableVals ) ): #check if we have any playable face cards if self.playableVals[x] > 10: if score + 10 <= 31: # denote we can play a card canPlay[x] = True playPossible = True # check if we have any playable cards else: #check if we can play the card if score + self.playableVals[x] <= 31: # denote we can play a card canPlay[x] = True playPossible = True # make sure we can play something if not playPossible: # denote we are skipping print( self.name + " says go!" ) self.ableToPeg = False return 0 # print the playable cards if this player is human if not isAi: self.playable.showCards( len(self.playableVals) ) while played == -1: # ask which card the user wants to throw if isAi: # make a copy of the discard pile dCopy = list( discard ) toThrow = ai.determinePeg( score, dCopy, self.playableVals ) if toThrow < 0: print( "Something is wrong; your AI sucks!" ) return -1 else: # ask the user what card they'd like to throw in1 = input( "Which card would you like to play?: " ) toThrow = self.parse( in1 ) # make sure card is in a valid index if( toThrow >= 0 and toThrow < len(self.playableVals) ): #make sure card is playable if( canPlay[toThrow] ): #store the played value played = self.playableVals[toThrow] #add played value to discard discard.append( played ) #remove the card from the playable and playableVals del self.playableVals[ toThrow ] self.playable.removeCard( toThrow ) #if the card is not playable else: #denote this card cannot be thrown print( "Cannot play " + Hand.cardString( self.playable.cardNums[ toThrow ] ) + ". Try again." ) else: #tell the user to try again print( "Please give a number between 0 and " + str( len( self.playableVals ) - 1 ) ) return played
def evaluate( self, newHand, cut ): # make a copy of the hand with the cut hand = Hand() for x in range( 0, 4 ): hand.addCard( newHand.cardNums[x] ) hand.addCard( cut ) #create variable for keeping track of points points = 0.0 #check for pairs for i in range( 0, 4 ): for j in range( i + 1, 5 ): #add two points to score and shout if pair found if( hand.cardVals[i][0] == hand.cardVals[j][0] ): points += 2 #store suit of first card suit = hand.cardVals[0][1] #check for all other cards to be in same suit if ( hand.cardVals[1][1] == suit and hand.cardVals[2][1] == suit and hand.cardVals[3][1] == suit ): points += 4 # check the cut if( hand.cardVals[4][1] == suit ): points += 1 # sort the ranges lst = [] for x in range( 0, 5 ): lst.append( hand.cardVals[x][0] ) lst.sort() # make list of all combinations of 3 runFour = [list(x) for x in itertools.combinations( lst, 4 )] runThree = [list(x) for x in itertools.combinations(lst, 3)] # keep track of if we have found a run runFound = False runFive = False # check for a run of 5 first = lst[0] if first == lst[1] - 1 and first == lst[2]-2 and first == lst[3]-3 and first == lst[4]-4: # denote we found a run runFive = True points += 5 if not runFive: # check for a run of 4 for x in range( 0, len(runFour) ): # sort the list runFour[x].sort() if runFour[x][1] == runFour[x][0] + 1 and runFour[x][2] == runFour[x][0] + 2 and runFour[x][3] == runFour[x][0] + 3: #denote we found a run of 4 points += 4 runFound = True #check for runs of 3 if not runFound: #check for runs of 3 for x in range( 0, len( runThree ) ): if runThree[x][1] == runThree[x][0] + 1 and runThree[x][2] == runThree[x][0] + 2: # denote we found a run of 3 points += 3 # give preference to jacks for x in range( 0, 4 ): if lst[x] == 10: points += 0.25 # make the correct 15 nums for x in range( 0, len( lst ) ): if lst[x] >= 9: lst[x] = 10 else: lst[x] += 1 #check for 15s for x in range( 1, 5 ): #make an array of combinations test = [list(y) for y in itertools.combinations( lst, x )] # check if the cards give a 15 for cards in test: # add points if we have a 15 if sum(cards) == 15: points += 2 return points
class DumbAI: def __init__( self ): #hand to be stored by the AI self.hand = Hand() self.GUESSCUT = 9 def evaluateProb( self, hand ): # make a deck deck = [] for x in range( 1, 52 ): # assume card is not in your hand inHand = False for y in range( 0, 4 ): if x == hand.cardNums[y]: #make note this card is already in your hand inHand = True if not inHand: # populate deck deck.append( x ) # created sorted hand lst = list( hand.cardNums ) lst.sort() # initialize a best hand score = 0.0 # evaluate each of throws and pick the best one for x in range( 0, len( deck ) ): #evaluate with the cut card score += self.evaluate( hand, deck[x] ) # return total score return score def evaluate( self, newHand, cut ): # make a copy of the hand with the cut hand = Hand() for x in range( 0, 4 ): hand.addCard( newHand.cardNums[x] ) hand.addCard( cut ) #create variable for keeping track of points points = 0.0 #check for pairs for i in range( 0, 4 ): for j in range( i + 1, 5 ): #add two points to score and shout if pair found if( hand.cardVals[i][0] == hand.cardVals[j][0] ): points += 2 #store suit of first card suit = hand.cardVals[0][1] #check for all other cards to be in same suit if ( hand.cardVals[1][1] == suit and hand.cardVals[2][1] == suit and hand.cardVals[3][1] == suit ): points += 4 # check the cut if( hand.cardVals[4][1] == suit ): points += 1 # sort the ranges lst = [] for x in range( 0, 5 ): lst.append( hand.cardVals[x][0] ) lst.sort() # make list of all combinations of 3 runFour = [list(x) for x in itertools.combinations( lst, 4 )] runThree = [list(x) for x in itertools.combinations(lst, 3)] # keep track of if we have found a run runFound = False runFive = False # check for a run of 5 first = lst[0] if first == lst[1] - 1 and first == lst[2]-2 and first == lst[3]-3 and first == lst[4]-4: # denote we found a run runFive = True points += 5 if not runFive: # check for a run of 4 for x in range( 0, len(runFour) ): # sort the list runFour[x].sort() if runFour[x][1] == runFour[x][0] + 1 and runFour[x][2] == runFour[x][0] + 2 and runFour[x][3] == runFour[x][0] + 3: #denote we found a run of 4 points += 4 runFound = True #check for runs of 3 if not runFound: #check for runs of 3 for x in range( 0, len( runThree ) ): if runThree[x][1] == runThree[x][0] + 1 and runThree[x][2] == runThree[x][0] + 2: # denote we found a run of 3 points += 3 # give preference to jacks for x in range( 0, 4 ): if lst[x] == 10: points += 0.25 # make the correct 15 nums for x in range( 0, len( lst ) ): if lst[x] >= 9: lst[x] = 10 else: lst[x] += 1 #check for 15s for x in range( 1, 5 ): #make an array of combinations test = [list(y) for y in itertools.combinations( lst, x )] # check if the cards give a 15 for cards in test: # add points if we have a 15 if sum(cards) == 15: points += 2 return points # find out what to throw by scoring all possible throws def determineThrow( self, hand ): #make variables to throw a = -1 b = -1 #make new hands with combinations of 4 cards fourCardHands = [list(x) for x in itertools.combinations( hand.cardNums, 4 )] # populate the hand with the first combination for x in range( 0, 4 ): self.hand.addCard( fourCardHands[0][x] ) # make a score to beat scoreToBeat = self.evaluateProb( self.hand ) # create a hand from the array for x in range( 1, len( fourCardHands ) ): # make a hand pointer testHand = Hand() testHand.clear() for y in range( 0, 4 ): # make new hand testHand.addCard( fourCardHands[x][y] ) score = self.evaluateProb( testHand ) # check the score of the test hand if score > scoreToBeat: # update the hand pointer self.hand = testHand score = scoreToBeat # find the indices we threw for x in range ( 0, 6 ): # assume we threw this card thrown = True # check if we didn't throw it for y in range( 0, 4 ): # compare the original hand's value at that index to our new hand if hand.cardNums[x] == self.hand.cardNums[y]: # denote the number is in the array thrown = False # if we threw it if thrown: # denote what this index is # make sure we reassigned a already if a == -1: a = x # reassign b else: b = x return [a, b] #stuff for checking the score def scorePeg( self, card, score, discardReal ): # keep track of points earned for this throw points = 0 score += card # copy the passed in array discard = list( discardReal ) # add the proposed throw to the array discard.append( card ) #make 5ddsure the pile is nonempty if len( discard ) == 0: # exit prematurely return 0 #check if we are at 15 if score == 15: # denote and move player 2 points += 2 elif score == 31: # denote and move player 2 points += 2 #make variable for last index depth = len( discard ) - 1 #booleans for keeping track of 4, 3 of a kind fourFound = False threeFound = False #booleans for keeping track of runs run = False for x in range( 6, 1, -1 ): # check for runs of x if depth >= x: # make a copy of the last x cards in the discard pile for checking runs discardCopy = [] for y in range( depth, depth - x - 1, -1 ): discardCopy.append( discard[y] ) # sort the copied array discardCopy.sort() #get the greatest card top = discardCopy[ len( discardCopy ) - 1 ] # assume we have a run run = True # check the cards for a run of 7 for z in range( 1, x + 1 ): if top - z != discardCopy[ x - z ]: run = False # keep track of the points found for a run if run: points += x + 1 break #check for 4 of a kind top = discard[ depth ] if depth >= 3: #check for 4 of a kind if top == discard[depth-1] and top == discard[depth-2] and top == discard[depth-3]: # denote we have a 4 of a kind and move points += 12 fourFound = True #check for a 3 of a kind if not fourFound: # make sure there are three cards in the pile if depth >= 2: if top == discard[depth-1] and top == discard[depth-2]: # denote we have a 3 of a kind and move points += 6 threeFound = True if depth >= 1 and not threeFound: # check for pair if top == discard[depth-1]: points += 2 return points # function for playing in pegging def determinePeg( self, score, discard, playable ): # make variable to store played card played = -1 # check if we can play any cards if len( playable ) == 0: print( "len(playable) = 0. Abort!") return -1 # make boolean for keeping track of if we can play any cards canPlay = [False] * len( playable ) playPossible = False # check if we have any playable cards for x in range( 0, len( playable ) ): #check if we have any playable face cards if playable[x] > 10: if score + 10 <= 31: # denote we can play a card canPlay[x] = True playPossible = True # check if we have any playable cards else: #check if we can play the card if score + playable[x] <= 31: # denote we can play a card canPlay[x] = True playPossible = True # make sure we can play something if not playPossible: print( "No play possible! Abort!" ) return -1 # initialize scoreToBeat scoreToBeat = 0 # initialize toThrow variable for x in range( 0, len( playable ) ): # make sure we can throw this card if canPlay[x]: # make this the card to throw and exit toThrow = x break # detemine optimal throw for x in range( toThrow, len( playable ) ): # make sure this card is playable if canPlay[x]: # determine how many points throwing this card gives us score = self.scorePeg( playable[x], score, discard ) #determine if this card is better scorewise if score > scoreToBeat: # make this the new card to throw and update score to beat toThrow = x scoreToBeat = score # determine if this card is better because it's a higher number elif score == scoreToBeat and playable[x] > playable[toThrow]: #make this the new card toThrow = x #if the card is not playable if not canPlay[ toThrow ]: #denote this card cannot be thrown print( "Cannot throw " + Hand.cardString( self.playable.cardNums[ toThrow ] ) + ". Try again." ) return -1 # otherwise return the optimal index thrown else: #print( "Throwing " + str( playable[toThrow] ) ) return toThrow
def determineThrow( self, hand ): #make variables to throw a = -1 b = -1 #make new hands with combinations of 4 cards fourCardHands = [list(x) for x in itertools.combinations( hand.cardNums, 4 )] # populate the hand with the first combination for x in range( 0, 4 ): self.hand.addCard( fourCardHands[0][x] ) # make a score to beat scoreToBeat = self.evaluateProb( self.hand ) # create a hand from the array for x in range( 1, len( fourCardHands ) ): # make a hand pointer testHand = Hand() testHand.clear() for y in range( 0, 4 ): # make new hand testHand.addCard( fourCardHands[x][y] ) score = self.evaluateProb( testHand ) # check the score of the test hand if score > scoreToBeat: # update the hand pointer self.hand = testHand score = scoreToBeat # find the indices we threw for x in range ( 0, 6 ): # assume we threw this card thrown = True # check if we didn't throw it for y in range( 0, 4 ): # compare the original hand's value at that index to our new hand if hand.cardNums[x] == self.hand.cardNums[y]: # denote the number is in the array thrown = False # if we threw it if thrown: # denote what this index is # make sure we reassigned a already if a == -1: a = x # reassign b else: b = x return [a, b]
class Player: def __init__(self, name, player_type, game, player=None): if player is not None: self.name = player.name self.hand = player.hand self.score = player.score self.roundscore = player.roundscore self.tricksWon = player.tricksWon self.type = player.type self.gameState = player.gameState # potentially check if changes in copied player affect original else: self.name = name self.hand = Hand() self.score = 0 self.roundscore = 0 self.tricksWon = [] self.type = player_type self.gameState = game def __eq__(self, other): return self.name == other.name def __str__(self): return self.name def __repr__(self): return self.__str__() def __hash__(self): return hash(repr(self)) def addCard(self, card): self.hand.addCard(card) def getInput(self, option): card = None while card is None: #display game information self.gameState.printGameState() print() print("Your hand: ", self.hand) # print("Your legal plays: %s" % self.gameState.getLegalPlays(self)) card = raw_input(self.name + ", select a card to " + option + ": ") return card def humanPlay(self, option): card_str = self.getInput(option) cardInfo = self.hand.strToCard(card_str) if cardInfo is None: return None else: cardRank, suitIden = cardInfo[0], cardInfo[1] #see if player has that card in hand if self.hand.containsCard(cardRank, suitIden): return Card.Card(cardRank, suitIden) else: return None def randomPlay(self): #get list of valid cards # gameState = self.gameState # validClubs = [] # validDiamonds = [] # validSpades = [] # validHearts = [] # validHand = [validClubs, validDiamonds, validSpades, validHearts] # for suit in range(0,4): # handSuit = self.hand.hand[suit] # for card in handSuit: # if gameState.isValidCard(card,self): # validHand[suit].append(card) return choice(self.gameState.getLegalPlays(self)) # return self.hand.getRandomCard() def print_hand(self, validHand): for suit in range(0, 4): print("Suit ", suit, ":"), for card in validHand[suit]: print(str(card), " "), print def naiveMaxAIPlay(self): gameState = self.gameState validClubs = [] validDiamonds = [] validSpades = [] validHearts = [] validHand = [validClubs, validDiamonds, validSpades, validHearts] for suit in range(0, 4): handSuit = self.hand.hand[suit] for card in handSuit: if gameState.isValidCard(card, self): validHand[suit].append(card) #if first, play highest card in a random suit if gameState.currentTrick.isUnset(): # print("Going first!") #include hearts if hearts not broken or only has hearts if gameState.heartsBroken == True or self.hasOnlyHearts(): suitRange = 3 else: suitRange = 2 randomSuit = randint(0, suitRange) #return highest card # print("Current trick suit is: ", gameState.currentTrick.suit.iden) # print("Going first and playing highest card") return Hand.highestCard(validHand[randomSuit]) #if not first: else: # print("Not going first!") trickSuit = gameState.currentTrick.suit.iden #if there are cards in the trick suit play highest card in trick suit if (len(validHand[trickSuit]) > 0): # print("Still cards in trick suit") return Hand.highestCard(validHand[trickSuit]) else: # print("No cards in trick suit") #play cards by points, followed by rank minPoints = sys.maxsize minCard = None for suit in range(0, 4): for card in validHand[suit]: cardPoints = -card.rank.rank if card.suit == Card.Suit(hearts): cardPoints -= 15 #Greater than rank of all non-point cards if card.suit == Card.Suit( spades) and card.rank == Card.Rank(queen): cardPoints -= 13 if cardPoints < minPoints: minPoints = cardPoints minCard = card return minCard #should never get here raise Exception("failed programming") return None #Always tries to avoid taking the trick def naiveMinAIPlay(self): #get list of valid cards gameState = self.gameState validClubs = [] validDiamonds = [] validSpades = [] validHearts = [] validHand = [validClubs, validDiamonds, validSpades, validHearts] for suit in range(0, 4): handSuit = self.hand.hand[suit] for card in handSuit: if gameState.isValidCard(card, self): validHand[suit].append(card) # self.print_hand(validHand) #if first, play lowest card in a random suit if gameState.currentTrick.isUnset(): # print("Going first!") #include hearts if hearts not broken or only has hearts if gameState.heartsBroken == True or self.hasOnlyHearts(): suitRange = 3 else: suitRange = 2 randomSuit = randint(0, suitRange) #return lowest card # print("Current trick suit is: ", gameState.currentTrick.suit.iden) # print("Going first and playing lowest card") return Hand.lowestCard(validHand[randomSuit]) #if not first: else: # print("Not going first!") trickSuit = gameState.currentTrick.suit.iden #if there are cards in the trick suit play lowest card in trick suit if (len(validHand[trickSuit]) > 0): # print("Still cards in trick suit") return Hand.lowestCard(validHand[trickSuit]) else: # print("No cards in trick suit") #play cards by points, followed by rank maxPoints = -sys.maxsize maxCard = None for suit in range(0, 4): for card in validHand[suit]: cardPoints = card.rank.rank if card.suit == Card.Suit(hearts): cardPoints += 15 #Greater than rank of all non-point cards if card.suit == Card.Suit( spades) and card.rank == Card.Rank(queen): cardPoints += 13 if cardPoints > maxPoints: maxPoints = cardPoints maxCard = card return maxCard #should never get here raise Exception("failed programming") return None def monteCarloAIPlay(self): mcObj = MonteCarlo(self.gameState, self.name) mcObj.update(self.gameState.cardsPlayed) card = mcObj.getPlay() return card def play(self, option='play', c=None, auto=False): card = None if c is not None: card = c card = self.hand.playCard(card) elif self.type == PlayerTypes.Human: card = self.humanPlay(option) elif self.type == PlayerTypes.Random: card = self.randomPlay() elif self.type == PlayerTypes.NaiveMinAI: card = self.naiveMinAIPlay() elif self.type == PlayerTypes.NaiveMaxAI: card = self.naiveMaxAIPlay() elif self.type == PlayerTypes.MonteCarloAI: card = self.monteCarloAIPlay() return card def trickWon(self, trick): self.roundscore += trick.points def hasSuit(self, suit): return len(self.hand.hand[suit.iden]) > 0 def removeCard(self, card): self.hand.removeCard(card) def discardTricks(self): self.tricksWon = [] def hasOnlyHearts(self): return self.hand.hasOnlyHearts() def validPlays(self, trickSuit, heartsBroken, trickNum): if self.hasOnlyHearts(): return self.hand.hearts if heartsBroken: if trickSuit == -1: return self.hand.clubs + self.hand.diamonds + self.hand.spades + self.hand.hearts else: if len(self.hand.hand[trickSuit]) == 0: return self.hand.clubs + self.hand.diamonds + self.hand.spades + self.hand.hearts else: return self.hand.hand[trickSuit] else: if trickSuit == -1: allCards = self.hand.clubs + self.hand.diamonds + self.hand.spades + self.hand.hearts else: if len(self.hand.hand[trickSuit]) == 0: if trickNum == 0: cards = self.hand.clubs + self.hand.diamonds + self.hand.spades cards.remove(Card(12, 2)) return cards else: return self.hand.clubs + self.hand.diamonds + self.hand.spades + self.hand.hearts else: return self.hand.hand[trickSuit]
def play(): deck = Deck() dealerHand = Hand() playerHand = Hand() deck.shuffle() dealerHand.addCard(deck.dealCard()) dealerHand.addCard(deck.dealCard()) playerHand.addCard(deck.dealCard()) playerHand.addCard(deck.dealCard()) print ' - ' print ' - ' if dealerHand.getHandValue() == 21: print 'Dealers cards: ' print dealerHand.getCard(0) + ' and ' + dealerHand.getCard(1) print 'Players cards: ' + playerHand.getCard(0) + ' and ' \ + playerHand.getCard(1) print ' ' print 'Dealer has Blackjack. Dealer wins.' return False if playerHand.getHandValue() == 21: print 'Dealers cards: ' print dealerHand.getCard(0) + ' and ' + dealerHand.getCard(1) print 'Players cards: ' + playerHand.getCard(0) + ' and ' \ + playerHand.getCard(1) print ' ' print 'Player has Blackjack. Player wins.' return True while True: print ' == ' print ' == ' print 'Players cards: ' for i in range(playerHand.getCardCount()): print ' ' + playerHand.getCard(i) print 'Player total hand value: ' + playerHand.getHandValue() print ' ' print 'Dealers cards: ' + dealerHand.getCard(0) print ' ' choice = input('(H)it or (S)tand?') if choice != 'H' and choice != 'S': print 'H or S' test2 = True while test2 == True: print ' ' choice = input('(H)it or (S)tand?') if choice != 'H' and choice != 'S': print 'H or S' test2 = True else: test2 = False if choice == 'S': return False else: drawCard = deck.dealCard() playerHand.addCard(drawCard) print ' ' print 'Player hits!' print 'Player gets card ' + drawCard print 'Player total is now: ' + playerHand.getHandValue() if playerHand.getHandValue() > 21: print '!' print 'Player busted!' print "Dealer's other card was: " + dealerHand.getCard(1) return False print '' print 'Player stands.' print 'Dealers cards: ' print ' ' + dealerHand.getCard(0) print ' ' + dealerHand.getCard(1) while dealerHand.getHandValue() <= 16: drawCard = (deck, dealCard()) print 'Dealer hits and draws a ' + drawCard dealerHand.addCard(drawCard) if dealerHand.getHandValue() > 21: print '!' print 'Dealer busted! Player wins!' return True print 'Dealer total is ' + dealerHand.getHandValue() print '-' if dealerHand.getHandValue() == playerHand.getHandValue(): print "It's a tie. Dealer wins." return False elif dealerHand.getHandValue() > playerHand.getHandValue(): print 'Dealer wins with the total of: ' \ + dealerHand.getHandValue() + '. Versus players total: ' \ + playerHand.getHandValue() + '.' return False else: print 'Player wins with the total: ' \ + playerHand.getHandValue() + '. Versus dealers total: ' \ + dealerHand.getHandValue() return True
class Game: # Constructor def __init__(self): pass # Function to run the whole Blackjack game def runGame(self): # Create stats for player print("Welcome to Blackjack!") playerName = input("What is your name? ") cashAmount = int(input("How much money would you like to play with? ")) playerWins = 0 playerLosses = 0 ties = 0 # Infinite loop to keep game going for as long as the player wants to keepPlaying = True while keepPlaying: # Ask for bet amount print("The maximum amount you can bet is ", cashAmount) betAmount = int(input("How much would you like to bet? ")) cashAmount -= betAmount # Create deck and shuffle it self.deck = Deck() self.deck.shuffle() # Create hand objects for dealer and player self.playersHand = Hand(isDealer=False) self.dealersHand = Hand(isDealer=True) # Deal 2 cards each to dealer and player for i in range(2): self.playersHand.addCard(self.deck.hit()) self.dealersHand.addCard(self.deck.hit()) # Show hands of dealer and player print("Dealer's hand is: ") self.dealersHand.showHand() print() print("Your hand is: ") self.playersHand.showHand() # Loop for players turn stopGame = False while not stopGame: # Ask player if they want to hit or stand choice = input( "Do you want to hit or stand? (h/hit or s/stand) ") choice = choice.lower() while choice not in ["h", "s", "hit", "stand"]: choice = input( "That is not a valid input! Please choose to hit or stand: " ) choice = choice.lower() # Deal card if player chooses to hit if choice == "hit" or choice == "h": self.playersHand.addCard(self.deck.hit()) self.playersHand.showHand() # Check if player has busted after adding card if self.playersHand.getHandValue() > 21: print("You busted and therefore have lost!") stopGame = True # Option if player chose to stand else: # Display both hands and values playerHandValue = self.playersHand.getHandValue() dealerHandValue = self.dealersHand.getHandValue() print("Dealer's hand: ") for card in self.dealersHand.cards: print(card) print("Dealer's hand value: ", dealerHandValue) print("Your hand: ") for card in self.playersHand.cards: print(card) print("Your hand value: ", playerHandValue) # Win, loss, or tie checker if playerHandValue > dealerHandValue: print("You win and the dealer loses!") playerWins += 1 cashAmount += betAmount * 2 elif playerHandValue == dealerHandValue: print("Tie!") ties += 1 cashAmount += betAmount else: print("You lose and the dealer wins!") playerLosses += 1 # Print stats print(playerName) print("Wins: ", playerWins) print("Losses: ", playerLosses) print("Ties: ", ties) print("Cash: ", cashAmount) print() print("Dealer") print("Wins: ", playerLosses) print("Losses: ", playerWins) print("Ties: ", ties) stopGame = True # Check if player wants to continue playing playAgain = input("Do you want to play again? (y/yes or n/no) ") playAgain = playAgain.lower() while playAgain not in ["y", "yes", "n", "no"]: playAgain = input( "This is not a valid input! Please enter y or n: ") playAgain = playAgain.lower() if playAgain == "y": gameOver = True else: print("Game will now end. Thank you!") keepPlaying = False
def play(): deck = Deck() dealerHand = Hand() playerHand = Hand() deck.shuffle() dealerHand.addCard( deck.dealCard() ) dealerHand.addCard( deck.dealCard() ) playerHand.addCard( deck.dealCard() ) playerHand.addCard( deck.dealCard() ) print(" - ") print(" - ") if dealerHand.getHandValue() == 21: print("Dealers cards: ") print(dealerHand.getCard(0) + " and " + dealerHand.getCard(1)) print("Players cards: " + playerHand.getCard(0) + " and " + playerHand.getCard(1)) print(" "); print("Dealer has Blackjack. Dealer wins.") return False if playerHand.getHandValue() == 21: print("Dealers cards: ") print(dealerHand.getCard(0) + " and " + dealerHand.getCard(1)) print("Players cards: " + playerHand.getCard(0) + " and " + playerHand.getCard(1)) print(" "); print("Player has Blackjack. Player wins.") return True while True: print(" == ") print(" == ") print("Players cards: ") for i in range(playerHand.getCardCount()): print(" " + playerHand.getCard(i)) print("Player total hand value: " + playerHand.getHandValue()) print(" ") print("Dealers cards: " + dealerHand.getCard(0)) print(" ") choice = input("(H)it or (S)tand?") if choice != "H" and choice != "S": print("H or S") test2 = True while test2 == True: print(" ") choice = input("(H)it or (S)tand?") if choice != "H" and choice != "S": print("H or S") test2 = True else: test2 = False if choice == "S": return False else: drawCard = deck.dealCard() playerHand.addCard( drawCard ) print(" ") print("Player hits!") print("Player gets card " + drawCard) print("Player total is now: " + playerHand.getHandValue()) if playerHand.getHandValue() > 21: print("!") print("Player busted!") print("Dealer's other card was: " + dealerHand.getCard(1)) return False print("") print("Player stands.") print("Dealers cards: ") print(" " + dealerHand.getCard(0)) print(" " + dealerHand.getCard(1)) while dealerHand.getHandValue() <= 16: drawCard = deck,dealCard() print("Dealer hits and draws a " + drawCard) dealerHand.addCard(drawCard) if dealerHand.getHandValue() > 21: print("!") print("Dealer busted! Player wins!") return True print("Dealer total is " + dealerHand.getHandValue()) print("-") if dealerHand.getHandValue() == playerHand.getHandValue(): print("It's a tie. Dealer wins.") return False elif dealerHand.getHandValue() > playerHand.getHandValue(): print("Dealer wins with the total of: " + dealerHand.getHandValue()) + ". Versus players total: " + playerHand.getHandValue() + "." return False else: print("Player wins with the total: " + playerHand.getHandValue() + ". Versus dealers total: " + dealerHand.getHandValue()) return True