def randomStarter(self): newCard = Card(random.randint(1, 13), random.randint(1, 4)) while newCard in self.hand: newCard = Card(random.randint(1, 13), random.randint(1, 4)) return newCard
def __init__(self): self.displayed = { 'red': Card('red', 0), 'green': Card('green', 0), 'blue': Card('blue', 0), 'yellow': Card('yellow', 0), 'white': Card('white', 0) } self.important_discards = [] self.no_more = []
def test_tie(): print('Testing two players tieing') pool = PP('pool') pool.add_card(Card(10,'S')) pool.add_card(Card(10,'C')) pool.add_card(Card(14,'D')) pool.add_card(Card(4,'H')) pool.add_card(Card(7,'C')) alice = Player.Player('Alice') alice.add_card(Card(9,'H')) alice.add_card(Card(9,'D')) poker_alice = PH(alice.hand, pool.hand) poker_alice.get_score() bob = Player.Player('Bob') bob.add_card(Card(9,'C')) bob.add_card(Card(9,'S')) poker_bob = PH(bob.hand, pool.hand) poker_bob.get_score() print('{}'.format(pool)) print('{}:\n\t\t final hand:{}\n{}:\n\t\t final hand:{}'.format(alice, poker_alice.final_hand, bob, poker_bob.final_hand)) if poker_alice.is_tie(poker_bob.score, poker_bob.rank_cards, poker_bob.kicker_cards): print('\nHands are equal, there is a tie!') else: print('\nHands are not equal, no tie :(')
def selectCardToPlay(self, gameState): cardToPlay = None cardScores = np.zeros(len(self.playhand)) # Select A according to w and x if len(self.playhand) != 0: for i in range(0, len(self.playhand)): # Check that the card can be played if (gameState['count'] + self.playhand[i].value() < 32): newHand = [] for i in range(0, len(self.playhand)): newHand.append( Card(self.playhand[i].rank, self.playhand[i].suit)) newHand.pop(i) newCount = gameState['count'] + self.playhand[i].value() cardScores[i] = np.matmul( self.peggingWeights, self.getFeaturesPegging( newHand, newCount, gameState['numCards'][self.number % 2])) else: cardScores[i] = -np.Inf if not (np.isinf(np.amax(cardScores))): cardToPlay = self.playhand[max(range(len(cardScores)), key=cardScores.__getitem__)] return cardToPlay
def next_card(self): if len(self) == 0 and self.starting_num is None: return None if len(self) == 0 and self.starting_num is not None: return Card(self.suit, self.starting_num) if len(self) == 8: return None curr = self.curr_card() return HungarianDeck.next_card(curr)
def throwCribCards(self, numCards, gameState): cribCards = [] self.cribThrow = [] cardIndices = list(range(0, len(self.hand))) maxValue = -np.inf if gameState['dealer'] == self.number - 1: dealerFlag = 1 else: dealerFlag = 0 for combination in combinations(cardIndices, len(self.hand) - numCards): handCards = [] thrownCards = [] for i in range(0, len(cardIndices)): if i in combination: handCards.append(Card(self.hand[i].rank, self.hand[i].suit)) else: thrownCards.append( Card(self.hand[i].rank, self.hand[i].suit)) q = self.throwValue( self.getThrowingFeatures(handCards, thrownCards, dealerFlag)) if q > maxValue: maxValue = q cribCards = [thrownCards.pop(), thrownCards.pop()] for i in range(len(cribCards)): for j in range(len(self.hand)): if cribCards[i].isIdentical(self.hand[j]): self.cribThrow.append( Card(self.hand[j].rank, self.hand[j].suit)) self.hand.pop(j) break if self.verbose: print("{} threw {} cards into the crib".format( self.getName(), numCards)) super().createPlayHand() return cribCards
def throwCribCards(self, numCards, gameState): self.cardsThrown = [] cribCards = [] cardIndices = list(range(len(self.hand))) maxValue = -np.inf for combination in combinations(cardIndices, len(self.hand) - numCards): handCards = [] thrownCards = [] for i in range(0, len(cardIndices)): if i in combination: handCards.append(Card(self.hand[i].rank, self.hand[i].suit)) else: thrownCards.append( Card(self.hand[i].rank, self.hand[i].suit)) q = np.matmul( np.transpose(self.throwingWeights), self.getFeaturesThrowing(handCards, thrownCards, gameState['dealer'])) if q > maxValue: maxValue = q cribCards = [] cribCards.append(thrownCards.pop()) cribCards.append(thrownCards.pop()) for i in range(0, len(cribCards)): for j in range(0, len(self.hand)): if cribCards[i].isIdentical(self.hand[j]): self.cardsThrown.append( Card(self.hand[j].rank, self.hand[j].suit)) self.hand.pop(j) break if (self.verbose): print("{} threw {} into the crib".format( self.getName(), cardsString(self.cardsThrown))) super().createPlayHand() return cribCards
def __init__(self): self.cards = [] suits = ['spades', 'clubs', 'hearts', 'diamonds'] values = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'jack', 'queen', 'king', 'ace'] for rank in values: for suit in suits: self.cards.append(Card(suit, rank)) random.shuffle(self.cards)
def learnFromHandScores(self, scores, gameState): reward = scores[self.number - 1] if gameState['dealer'] == (self.number - 1): reward += scores[2] dealerFlag = 1 else: reward -= scores[2] dealerFlag = 0 possibleThrows = list(self.cribCardCombinations.keys()) possibleThrows.remove("00") throwProbabilities = list(self.cribCardCombinations.values()) throwProbabilities.remove(self.cribCardCombinations["00"]) if not throwProbabilities: possibleThrows = [ "AA", "22", "33", "44", "55", "66", "77", "88", "99", "TT", "JJ", "QQ", "KK" ] throwProbabilities = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] throwProbabilities = throwProbabilities / np.sum(throwProbabilities) oppThrow = np.random.choice(possibleThrows, p=throwProbabilities) oppCards = [] for j in range(2): cardRank = oppThrow[j:j + 1] if cardRank == "A": cardRank = 1 elif cardRank == "T": cardRank = 10 elif cardRank == "J": cardRank = 11 elif cardRank == "Q": cardRank = 12 elif cardRank == "K": cardRank = 13 oppCards.append(Card(int(cardRank), np.random.randint(1, 5))) state = self.getThrowingFeatures(self.hand, self.cribThrow, oppCards, dealerFlag) qValue = self.throwValue(state) update = self.alpha * ( reward + np.max(self.SAValues(self.throwingState)) - qValue) self.throwingBrain.partial_fit([state], np.ravel([qValue + update])) if self.verbose: print(self.name + ": Learning from hand scores!") print('\tState: {}'.format(state)) print('\tQ-value (pre): {}'.format(qValue)) print('\tReward: {}'.format(reward)) print('\tUpdate Value : {}'.format(update)) if self.saveFlag: self.backup()
def get_starting_card(self): '''chooses the starting card and returns it''' best_cards = self.best_starting_cards() # remove if we only have one card of the suit & it's not a big diff # for future: get statistics about this and have a better guess lonely_suits = [] for suit, num_of_cards in self.cards_per_suit().items(): if num_of_cards == 1: lonely_suits.append(suit) # ~the amount of less points if we start with lonely card: # LONELY = 3 # since best_cards is an OrderedDict we can do this: examined_card = None while True: examined_card = best_cards.popitem(last=False)[0] suit = examined_card.split(' ')[0] if suit not in lonely_suits: break return Card.from_string(examined_card)
def calculate_sum_dist(self, starting_card): '''calculates the number of holes with given starting card''' HDeck = HungarianDeck cards_p_suit = self.cards_per_suit() num_of_holes = 0 for suit in HungarianDeck.suits: # Temporary starting card for calculation tmp_card = Card(suit, starting_card.number) # Every cards distance from the starting card # 0 if not same suit, distance if same dists = [HDeck.distance(tmp_card, card) for card in self.cards] # number of holes given a suit. max of the list created above # minus the number of cards in that suit num_of_holes += max(dists) - cards_p_suit[suit] # if the starting card is not in our hand we add that one to # the number aswell (because we created a temporary card) if cards_p_suit[suit] != 0: num_of_holes += 1 return num_of_holes
def learnFromPegging(self, gameState): if len(self.state) > 0: # Choose A' greedily from S' using w nextCard = self.selectCardToPlay(gameState) nextCount = gameState['count'] newHand = [] for card in self.playhand: newHand.append(Card(card.rank, card.suit)) if not (nextCard is None): for i in range(0, len(newHand)): if newHand[i].isIdentical(nextCard): newHand.pop(i) break nextCount += nextCard.value() # Get x and x' x = self.state xPrime = self.getFeaturesPegging( newHand, nextCount, gameState['numCards'][self.number % 2]) # Calculate Q, Q', R and delta q = np.matmul(self.peggingWeights, x) qPrime = np.matmul(self.peggingWeights, xPrime) R = self.getRelativeScore(gameState) - self.score delta = R + qPrime - q # Update memory and weights self.peggingMemory = (self.traceDecay * self.peggingMemory) + ( (1 - (self.stepSize * self.traceDecay * np.matmul(np.transpose(self.peggingMemory), x))) * x) update = (self.stepSize * (delta + q - self.qOld) * self.peggingMemory) - (self.stepSize * (q - self.qOld) * x) self.peggingWeights = self.peggingWeights + update # Bookkeeping to prepare for the next step self.qOld = qPrime np.save("./NLBpegWeights.npy", self.peggingWeights)
def createPlayHand(self): for i in range(0, len(self.hand)): self.playhand.append(Card(self.hand[i].rank, self.hand[i].suit))
def one_face_down(self): hidden = Card('Hidden', 'Hidden') return [hidden] + self.cards[1:]
def explainThrow(self, numCards, gameState): hand = [] for i in range(len(self.hand)): hand.append(self.hand[i]) for i in range(numCards): hand.append(self.cribThrow[i]) cardIndices = list(range(0, len(hand))) if gameState['dealer'] == self.number - 1: dealerFlag = 1 else: dealerFlag = 0 print("DeepPeg ({}) is considering a hand of: {}".format( self.number, cardsString(hand)), end="") if dealerFlag == 1: print(". Own crib.") else: print(". Opponent's crib.") maxValue = -np.inf for combination in combinations(cardIndices, len(hand) - numCards): handCards = [] thrownCards = [] for i in range(0, len(cardIndices)): if i in combination: handCards.append(Card(hand[i].rank, hand[i].suit)) else: thrownCards.append(Card(hand[i].rank, hand[i].suit)) q = 0 possibleThrows = list(self.cribCardCombinations.keys()) possibleThrows.remove("00") throwProbabilities = list(self.cribCardCombinations.values()) throwProbabilities.remove(self.cribCardCombinations["00"]) if not throwProbabilities: possibleThrows = [ "AA", "22", "33", "44", "55", "66", "77", "88", "99", "TT", "JJ", "QQ", "KK" ] throwProbabilities = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] throwProbabilities = throwProbabilities / np.sum( throwProbabilities) for i in range(self.numSims): oppThrow = np.random.choice(possibleThrows, p=throwProbabilities) oppCards = [] for j in range(2): cardRank = oppThrow[j:j + 1] if cardRank == "A": cardRank = 1 elif cardRank == "T": cardRank = 10 elif cardRank == "J": cardRank = 11 elif cardRank == "Q": cardRank = 12 elif cardRank == "K": cardRank = 13 oppCards.append( Card(int(cardRank), np.random.randint(1, 5))) q = q + self.throwValue( self.getThrowingFeatures(handCards, thrownCards, oppCards, dealerFlag)) if q > maxValue: maxValue = q cribCards = [] cribCards.append(thrownCards[0]) cribCards.append(thrownCards[1]) print("\t{}: {}".format(cardsString(thrownCards), q)) print("I chose to throw: {}".format(cardsString(cribCards))) print("")
def throwCribCards(self, numCards, gameState, criticThrow): cribCards = [] self.cribThrow = [] cardIndices = list(range(0, len(self.hand))) maxValue = -np.inf if gameState['dealer'] == self.number - 1: dealerFlag = 1 else: dealerFlag = 0 self.opponentEstimate = np.ones(13) for i in range(len(self.hand)): idx = self.hand[i].getRank().value - 1 self.opponentEstimate[idx] = self.opponentEstimate[idx] - 0.25 for combination in combinations(cardIndices, len(self.hand) - numCards): handCards = [] thrownCards = [] for i in range(0, len(cardIndices)): if i in combination: handCards.append(Card(self.hand[i].rank, self.hand[i].suit)) else: thrownCards.append( Card(self.hand[i].rank, self.hand[i].suit)) q = 0 possibleThrows = list(self.cribCardCombinations.keys()) possibleThrows.remove("00") throwProbabilities = list(self.cribCardCombinations.values()) throwProbabilities.remove(self.cribCardCombinations["00"]) if not throwProbabilities: possibleThrows = [ "AA", "22", "33", "44", "55", "66", "77", "88", "99", "TT", "JJ", "QQ", "KK" ] throwProbabilities = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] throwProbabilities = throwProbabilities / np.sum( throwProbabilities) for i in range(self.numSims): oppThrow = np.random.choice(possibleThrows, p=throwProbabilities) oppCards = [] for j in range(2): cardRank = oppThrow[j:j + 1] if cardRank == "A": cardRank = 1 elif cardRank == "T": cardRank = 10 elif cardRank == "J": cardRank = 11 elif cardRank == "Q": cardRank = 12 elif cardRank == "K": cardRank = 13 oppCards.append( Card(int(cardRank), np.random.randint(1, 5))) q = q + self.throwValue( self.getThrowingFeatures(handCards, thrownCards, oppCards, dealerFlag)) if q > maxValue: maxValue = q cribCards = [] cribCards.append(thrownCards.pop()) cribCards.append(thrownCards.pop()) for i in range(0, len(cribCards)): for j in range(0, len(self.hand)): if cribCards[i].isIdentical(self.hand[j]): self.cribThrow.append( Card(self.hand[j].rank, self.hand[j].suit)) self.hand.pop(j) break if (self.verbose): print("{} threw {} cards into the crib".format( self.getName(), numCards)) super().createPlayHand() if not (criticThrow is None): if not (areCardsEqual(self.cribThrow, criticThrow)): self.explainThrow(numCards, gameState) else: print("The critic agreed with {}'s throw.".format( self.getName())) # Note which cards have been thrown into the crib cardKeys = list() for i in range(2): cardKeys.append(str(cribCards[i].getRank().value)) if cardKeys[i] == '1': cardKeys[i] = 'A' elif cardKeys[i] == '10': cardKeys[i] = 'T' elif cardKeys[i] == '11': cardKeys[i] = 'J' elif cardKeys[i] == '12': cardKeys[i] = 'Q' elif cardKeys[i] == '13': cardKeys[i] = 'K' if cribCards[0].getRank().value <= cribCards[1].getRank().value: cardKey = cardKeys[0] + cardKeys[1] else: cardKey = cardKeys[1] + cardKeys[0] if cardKey in self.cribCardCombinations: self.cribCardCombinations[ cardKey] = self.cribCardCombinations[cardKey] + 1 else: self.cribCardCombinations[cardKey] = 1 self.cribCardCombinations["00"] = self.cribCardCombinations["00"] + 1 return cribCards
def runTrials(self, numTrials): cumulativeScore = 0 for trial in range(0, numTrials): # Initialize the hand self.deck = Deck(1) self.deck.shuffle() hands = [] scores = [] # Deal two hands of four for i in range(0, self.numPlayers): hands.append([]) scores.append(0) for j in range(0, 4): hands[i].append(self.deck.cards.pop()) #print("Hand 1 is "+cardsString(hands[0])) #print("Hand 2 is "+cardsString(hands[1])) # Assign these hands to the players for i in range(0, len(hands[0])): self.cribbageDojo.players[0].playhand.append( Card(hands[0][i].rank, hands[0][i].suit)) self.cribbageDojo.players[1].playhand.append( Card(hands[1][i].rank, hands[1][i].suit)) #print(self.cribbageDojo.players[0].getName()+" has the cards "+cardsString(self.cribbageDojo.players[0].playhand)) #print(self.cribbageDojo.players[1].getName()+" has the cards "+cardsString(self.cribbageDojo.players[1].playhand)) self.cribbageDojo.dealer = 0 self.cribbageDojo.play() for i in range(0, self.numPlayers): scores[i] = scores[i] + self.cribbageDojo.players[i].pips print("Score for this hand was " + self.cribbageDojo.scoreString()) self.cribbageDojo.resetGame() # Assign the opposite hands to the players for i in range(0, len(hands[0])): self.cribbageDojo.players[1].playhand.append( Card(hands[0][i].rank, hands[0][i].suit)) self.cribbageDojo.players[0].playhand.append( Card(hands[1][i].rank, hands[1][i].suit)) #print(self.cribbageDojo.players[0].getName()+" has the cards "+cardsString(self.cribbageDojo.players[0].playhand)) #print(self.cribbageDojo.players[1].getName()+" has the cards "+cardsString(self.cribbageDojo.players[1].playhand)) self.cribbageDojo.dealer = 1 self.cribbageDojo.play() for i in range(0, self.numPlayers): scores[i] = scores[i] + self.cribbageDojo.players[i].pips print("Score for this hand was " + self.cribbageDojo.scoreString()) self.cribbageDojo.resetGame() print("The point differential for " + self.cribbageDojo.players[0].getName() + " was {0}.\n".format(scores[0] - scores[1])) cumulativeScore = cumulativeScore + scores[0] - scores[1] print("The overall point differential for " + self.cribbageDojo.players[0].getName() + " was {0}, or {1} points-per-hand.\n".format( cumulativeScore, cumulativeScore / (numTrials * 2)))
def setUp(self): self.card = Card("Hearts", "A")
# Run 100 games wonGames = 0 N = 100 qPlayer = QPlayer(None, loadFromFile=False) for i in range(N): print("Game: " + str(i)) table = Table(1) table.piles = [] for stack in table.stacks: stack.faceDownCards = [] stack.faceUpCards = [] cards = [ Card(1, 0), Card(2, 0), Card(3, 0), Card(4, 0), Card(5, 0), Card(6, 0), Card(7, 0), Card(8, 0), Card(9, 0), Card(10, 0), Card(11, 0), Card(12, 0), Card(13, 0) ] random.shuffle(cards) for i in range(13):
import Deck from Deck import Card as Card import Player from Game import PokerPool as PP from Game import PokerHand as PH d = Deck.Deck() a = Player.Player('a') b = Player.Player('b') c = Player.Player('c') d.deal_card(a) d.deal_card(a) d.deal_card(b) d.deal_card(b) c.add_card(Card(2,'D')) c.add_card(Card(3,'H')) print('{0} < {1} ? {2}'.format(a,c,a.hand<c.hand)) print('{0} < {1} ? {2}'.format(a,b,a.hand<b.hand)) print('{0} < {1} ? {2}'.format(c,b,c.hand<b.hand)) print('{0} = {1} ? {2}'.format(a,c,a.hand==c.hand)) print('{0} = {1} ? {2}'.format(a,b,a.hand==b.hand)) print('{0} = {1} ? {2}'.format(c,b,c.hand==b.hand)) def aa(): print('A')
from DeepPeg import DeepPeg from Deck import Card, Rank, Suit if __name__ == '__main__': player = DeepPeg(1, True, False, True) player.playhand = [ Card(Rank.Ace, Suit.Hearts), Card(Rank.Two, Suit.Spades) ] state = dict() scores = [0, 0] state['scores'] = scores numCards = [2, 1] state['numCards'] = numCards inplay = [Card(Rank.Ten, Suit.Clubs), Card(Rank.Three, Suit.Hearts)] state['inplay'] = inplay state['playorder'] = inplay state['dealer'] = 0 state['starter'] = Card(Rank.Ace, Suit.Spades) state['count'] = sum([card.value() for card in inplay]) played = player.playCard(state, Card(Rank.Ace, Suit.Hearts)) print(played)
def one_face_down(self): ''' prints dealer's hand with first card hidden ''' hidden = Card('Hidden', 'Hidden') return [hidden] + self.cards[1:]
def runTrials(self, numTrials): cumulativeScore = 0 cumulativePegging = 0 cumulativeHands = 0 for trial in range(numTrials): # Initialize the hand self.deck = Deck(1) self.deck.shuffle() hands = [] scores = [] pegScores = [] handScores = [] # Deal two hands of four for i in range(0, self.numPlayers): hands.append([]) scores.append(0) pegScores.append(0) handScores.append(0) for j in range(0, 6): hands[i].append(self.deck.cards.pop()) # print("Hand 1 is "+cardsString(hands[0])) # print("Hand 2 is "+cardsString(hands[1])) starterCard = self.deck.cards.pop() # Assign these hands to the players for i in range(len(hands[0])): self.cribbageDojo.players[0].hand.append( Card(hands[0][i].rank, hands[0][i].suit)) self.cribbageDojo.players[1].hand.append( Card(hands[1][i].rank, hands[1][i].suit)) # print(self.cribbageDojo.players[0].getName()+" has the cards "+cardsString(self.cribbageDojo.players[0].playhand)) # print(self.cribbageDojo.players[1].getName()+" has the cards "+cardsString(self.cribbageDojo.players[1].playhand)) self.cribbageDojo.dealer = 0 self.cribbageDojo.createCrib() self.cribbageDojo.cut(starterCard) #print("The starter card is cut: "+str(self.cribbageDojo.starter)) self.cribbageDojo.play() for i in range(self.numPlayers): pegScores[i] = self.cribbageDojo.players[i].pips print("Pegging for this hand was {0} - {1}".format( pegScores[0], pegScores[1])) self.cribbageDojo.scoreHands() for i in range(self.numPlayers): handScores[ i] = self.cribbageDojo.players[i].pips - pegScores[i] scores[i] = scores[i] + self.cribbageDojo.players[i].pips print("Hand and crib points for this hand were {0} - {1}".format( handScores[0], handScores[1])) print("Overall score for this hand was " + self.cribbageDojo.scoreString()) self.cribbageDojo.resetGame() cumulativePegging = cumulativePegging + pegScores[0] - pegScores[1] cumulativeHands = cumulativeHands + handScores[0] - handScores[1] # Assign the opposite hands to the players for i in range(len(hands[0])): self.cribbageDojo.players[1].hand.append( Card(hands[0][i].rank, hands[0][i].suit)) self.cribbageDojo.players[0].hand.append( Card(hands[1][i].rank, hands[1][i].suit)) for i in range(self.numPlayers): pegScores[i] = 0 handScores[i] = 0 # print(self.cribbageDojo.players[0].getName()+" has the cards "+cardsString(self.cribbageDojo.players[0].playhand)) # print(self.cribbageDojo.players[1].getName()+" has the cards "+cardsString(self.cribbageDojo.players[1].playhand)) self.cribbageDojo.dealer = 1 self.cribbageDojo.createCrib() self.cribbageDojo.cut(starterCard) #print("The starter card is cut: "+str(self.cribbageDojo.starter)) self.cribbageDojo.play() for i in range(self.numPlayers): pegScores[i] = self.cribbageDojo.players[i].pips print("Pegging for this hand was {0} - {1}".format( pegScores[0], pegScores[1])) self.cribbageDojo.scoreHands() for i in range(self.numPlayers): handScores[ i] = self.cribbageDojo.players[i].pips - pegScores[i] scores[i] = scores[i] + self.cribbageDojo.players[i].pips print("Hand and crib points for this hand were {0} - {1}".format( handScores[0], handScores[1])) print("Overall score for this hand was " + self.cribbageDojo.scoreString()) self.cribbageDojo.resetGame() cumulativePegging = cumulativePegging + pegScores[0] - pegScores[1] cumulativeHands = cumulativeHands + handScores[0] - handScores[1] print("The point differential for " + self.cribbageDojo.players[0].getName() + " was {0}.\n".format(scores[0] - scores[1])) cumulativeScore = cumulativeScore + scores[0] - scores[1] print("\nThe pegging differential for " + self.cribbageDojo.players[0].getName() + " was {0}, or {1} points-per-hand.\n".format( cumulativePegging, cumulativePegging / (numTrials * 2))) print("The hand scores differential for " + self.cribbageDojo.players[0].getName() + " was {0}, or {1} points-per-hand.\n".format( cumulativeHands, cumulativeHands / (numTrials * 2))) print("The overall point differential for " + self.cribbageDojo.players[0].getName() + " was {0}, or {1} points-per-hand.\n".format( cumulativeScore, cumulativeScore / (numTrials * 2)))