本文整理汇总了Python中Deck.Deck.shuffle方法的典型用法代码示例。如果您正苦于以下问题:Python Deck.shuffle方法的具体用法?Python Deck.shuffle怎么用?Python Deck.shuffle使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Deck.Deck
的用法示例。
在下文中一共展示了Deck.shuffle方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: battle
# 需要导入模块: from Deck import Deck [as 别名]
# 或者: from Deck.Deck import shuffle [as 别名]
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')
示例2: DeckTest
# 需要导入模块: from Deck import Deck [as 别名]
# 或者: from Deck.Deck import shuffle [as 别名]
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()
示例3: __initializeDeck
# 需要导入模块: from Deck import Deck [as 别名]
# 或者: from Deck.Deck import shuffle [as 别名]
def __initializeDeck(self):
# Initialize discard columns
self.__discardPiles = [
Deck(),
Deck(),
Deck(),
Deck()
]
deck = Deck()
deck.buildFullDeck()
deck.shuffle()
self.__deck = deck
示例4: playwar
# 需要导入模块: from Deck import Deck [as 别名]
# 或者: from Deck.Deck import shuffle [as 别名]
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)
示例5: Game
# 需要导入模块: from Deck import Deck [as 别名]
# 或者: from Deck.Deck import shuffle [as 别名]
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)
示例6: Hand
# 需要导入模块: from Deck import Deck [as 别名]
# 或者: from Deck.Deck import shuffle [as 别名]
cards = []
cards.append(Card("K", "H"))
cards.append(Card("K", "D"))
cards.append(Card("4", "S"))
cards.append(Card("4", "C"))
cards.append(Card("10", "H"))
hand4 = Hand(cards)
assert hand4.handType == 3, "Unit Test Failed : Two Pairs"
assert hand3 < hand4, "Unit Test Failed : Two pairs comparison"
# Random testing (todo: oracle)
for i in range(100):
deck = Deck()
deck.shuffle()
cards = []
for c in range(5):
cards.append(deck.pop())
hand1 = Hand(cards)
while len(cards) > 0:
deck.push(cards.pop())
deck.shuffle()
for c in range(5):
cards.append(deck.pop())
hand2 = Hand(cards)
if (hand1.compare(hand2) == 0):
print("1 : ", hand1)
print("2 : ", hand2)
print("1 < 2 : ", hand1.compare(hand2))
print("-----")
示例7: Blackjack
# 需要导入模块: from Deck import Deck [as 别名]
# 或者: from Deck.Deck import shuffle [as 别名]
class Blackjack(object):
def __init__(self, player = Player("")):
self.player = player;
self.deck = Deck()
self.deck.create_default_deck()
self.deck.shuffle()
def print_player_name(self):
print self.player.get_name()
def print_hand(self, player = Player("")):
print player.get_name()+"'s cards:"
for c in player.get_hand():
print c.get_name()
def bust(self, player = Player("")):
sum = 0
for c in player.get_hand():
sum += c.get_value()
if(sum>21):
return True
return False
def count_cards(self, cards):
sum = 0
ace = 0
for c in cards:
if c.get_val==11 :
ace += 1
else:
sum += c.get_val()
if ace>0: ## Aces have varying values
for i in range(ace):
if sum+11 > 21:
sum+=1
else:
sum+=11
return sum
def hit(self, player = Player("")):
self.deck.deal(1, player)
def should_hit(self, ai_card_val):
return ai_card_val < 17
def dist_winnings(self, player = Player("")):
print "Congratulations to "+player.get_name()+" for winning this round!";
def dist_winnings_equally(self, ai = Player("")):
print "Tie! Winnings will be distributed equally"
def play(self):
ai = Player ("AI")
self.deck.deal(2, self.player)
self.deck.deal(2, ai)
player_card_val = self.count_cards(self.player.get_hand())
ai_card_val = self.count_cards(ai.get_hand())
self.print_hand(self.player)
while "yes" in raw_input("Do you want to hit?: ").lower():
self.hit(self.player)
player_card_val = self.count_cards(self.player.get_hand())
if (player_card_val>21):
print self.player.get_name()+" busted!"
self.dist_winnings(ai)
self.deck.add(self.player.return_hand())
self.deck.add(ai.return_hand())
return
self.print_hand(self.player)
while self.should_hit(ai_card_val):
self.hit(ai)
ai_card_val = self.count_cards(ai.get_hand())
if(ai_card_val >21):
print ai.get_name()+" busted!"
self.dist_winnings(self.player)
self.deck.add(self.player.return_hand())
self.deck.add(ai.return_hand())
return
self.print_hand(ai)
if player_card_val > ai_card_val :
self.dist_winnings(self.player)
elif ai_card_val > player_card_val:
self.dist_winnings(ai)
else:
self.dist_winnings_equally(ai)
self.deck.add(self.player.return_hand())
self.deck.add(ai.return_hand())
return
示例8: HandState
# 需要导入模块: from Deck import Deck [as 别名]
# 或者: from Deck.Deck import shuffle [as 别名]
class HandState(object):
"""State of a given hand.
After creation, use process_action() to add actions. Complete processing
with finish_processing() after which no more acctions should be processed.
"""
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 = []
def deal_cards(self, number_of_cards=1):
"""Deal number_of_cards to each player."""
for card in range(number_of_cards):
for player in self.table.get_active_players():
player.deal_card(self._deck)
def new_betting_round(self):
"""Create a new betting round"""
new_round = BettingRound(self.table,
self.pot,
message_handler=self.message_handler)
self.betting_rounds.append(new_round)
return new_round
def get_current_betting_round(self):
"""Return the current betting round"""
return self.betting_rounds[len(self.betting_rounds) - 1]
def dump_to_string(self):
"""Dump our state to a string for debugging."""
s = ""
s += str(self.table)
s += str(self.pot)
s += "On betting round %d" % (len(self.betting_rounds) + 1)
return s
def _message(self, msg):
"""Handle a message"""
if self.message_handler is not None:
self.message_handler.message(msg)
def _debug(self, msg):
"""Handle a debug message"""
if self.message_handler is not None:
self.message_handler.debug(msg)
示例9: play
# 需要导入模块: from Deck import Deck [as 别名]
# 或者: from Deck.Deck import shuffle [as 别名]
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
示例10: Deck
# 需要导入模块: from Deck import Deck [as 别名]
# 或者: from Deck.Deck import shuffle [as 别名]
from Deck import Deck
## Testing the Deck() constructor.
print('#<====== Creating Deck ======>#\n')
d = Deck()
print('The __str__ method shows the deck like so:\n')
print(d)
print('The length of this deck is', len(d.cards))
print('\nAnd the other property is d.next =', str(d.next))
print()
## Testing the Shuffle method.
print('\n#<====== Shuffling Deck ======>#\n')
d.shuffle()
print('The shuffle method will return the deck as:\n')
print(d, '\n')
## Testing the sort method.
print('\n#<====== Sorting Deck ======>#\n')
d.sort()
print('The sort method will return the deck as:\n')
print(d, '\n')
## Testing the Deal method.
print('\n#<====== Dealing Deck ======>#\n')
print('Card #1 is', d.deal())
print('Card #2 is', d.deal())
示例11: Game
# 需要导入模块: from Deck import Deck [as 别名]
# 或者: from Deck.Deck import shuffle [as 别名]
class Game(object):
'''
This represents a game of UNO. It keeps track of a list of the players currently involved in the game.
'''
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')}
def getDeck(self):
''' Returns the deck used for this game '''
return self._deck
def addPlayerToGame(self, name):
''' Add a human player to the game '''
self._playerList.append(Player(name, self._deck.draw7Cards()))
def addAIPlayerToGame(self, name):
''' Add an AI player to the game '''
self._playerList.append(AIPlayer(name, self._deck.draw7Cards()))
def getCurrentCard(self):
''' Returns the current card in play for this game '''
return self._currentCard
def isFinished(self):
''' Returns True if the game is finished, that is if one player has 0 cards '''
for player in self._playerList:
if len(player.getCurrentHand()) == 0:
return True
return False
def testMove(self, card):
''' Test to see if the Card card is a valid move given the current card in play '''
if not self.currentPlayer().testMove(self._currentCard, card):
raise InvalidMoveException
def hasUno(self, player):
''' Returns True if the Player player has UNO, that is has only one card left '''
return len(player.getCurrentHand()) == 1
def nextPlayerHasUno(self):
''' Returns true if the next player has UNO (to help the AI) '''
try:
return len(self._playerList[self._currentPlayer-1].getCurrentHand) == 1
except:
return len(self._playerList[0].getCurrentHand()) == 1
def applySpecial(self,card, color=None):
''' Applies the special ability of Card card. '''
ability = card.getData()
if ability == 'skip':
self._currentPlayer+=1
if self._currentPlayer >= len(self._playerList):
self._currentPlayer = 0
return True
elif ability == 'reverse':
self._playerList = self._playerList[::-1] #reverse the list
if len(self._playerList) > 2:
self._currentPlayer = abs(self._currentPlayer-len(self._playerList)) #fix order
if self._currentPlayer > len(self._playerList)-1:
self._currentPlayer=0
return len(self._playerList) == 2
elif ability == 'draw 2':
try:
nextplayer = self._playerList[self._currentPlayer+1]
self.playerDrawCard(nextplayer, 2)
self._currentPlayer+=1
except:
self.playerDrawCard(self._playerList[0], 2)
self._currentPlayer = 0
return True
elif ability == 'wild' or ability == 'wild draw four':
self._currentCard = self._blankCards[color]
if ability == "wild draw four":
try:
nextplayer = self._playerList[self._currentPlayer+1]
self.playerDrawCard(nextplayer, 4)
self._currentPlayer+=1
except:
self.playerDrawCard(self._playerList[0], 4)
self._currentPlayer=0
return True
def playerDrawCard(self, player, amount):
try:
player.giveCard(self._deck.drawCard(amount))
except EmptyDeckException:
self._discardPile.shuffle()
self._deck = self._discardPile
#.........这里部分代码省略.........
示例12: play_game
# 需要导入模块: from Deck import Deck [as 别名]
# 或者: from Deck.Deck import shuffle [as 别名]
def play_game():
deck = Deck()
bankroll = Bankroll()
deck.shuffle()
print(f"Current bankroll is {bankroll.player_bank}")
dep_draw = input("Deposit/Withdraw? D/W or Enter to pass: ").upper()
# BANKROLL: Deposit
if dep_draw == "D" or bankroll.player_bank <= 0:
while True:
try:
if bankroll.player_bank <=0:
print("Sorry your bankroll is 0!")
bankroll.deposit(int(input("Please enter deposit amount: ")))
except:
print("Whoops! That is not a number")
else:
break
# BANKROLL: Withdraw
if dep_draw == "W":
while True:
try:
bankroll.withdraw(int(input("Please enter withdraw amount: ")))
except:
print("Whoops! That is not a number")
else:
break
# BANKROLL: Place bet
while True:
try:
bankroll.bet(int(input("Please place your bet: ")))
except:
print("Whoops! That is not a number")
else:
break
# RUN GAME (Consider adding to 'Game' class as .deal_game)
for i in range(4):
if deck.turn == 'Player':
deck.turn = 'Dealer'
else:
deck.turn = 'Player'
deck.draw_card()
deck.tally()
print(f"Dealer: {deck.dealer_hand[0]}")
print(f"Player: {deck.player_hand}")
print(f"Player count: {deck.player_count_A11} & {deck.player_count_A1}")
play = True
hit_stand = ''
while play:
invalid_play = True
while invalid_play:
hit_stand = input("Hit or stand? H/S: ").upper()
invalid_play = (hit_stand != 'H' and hit_stand != 'S')
if invalid_play:
print ("Please enter either 'H' or 'S'.")
deck.player_play(hit_stand)
print(f"\nPlayer: {deck.player_hand}")
print(f"Player count: {deck.player_count_A11} & {deck.player_count_A1}")
play = ((deck.player_count_A11 < 21 or deck.player_count_A1 < 21) and
(deck.player_count_A11 != 21 and deck.player_count_A1 != 21) and hit_stand == "H")
if deck.player_count_A11 > 21 and deck.player_count_A1 > 21:
# Player loses
print("Bust")
else:
while (deck.score_check()[1] != -1) and (deck.score_check()[0] > deck.score_check()[1]) and (deck.dealer_count_A1 < 17):
deck.dealer_play("H")
print("\n")
print(deck.player_hand)
print(deck.dealer_hand)
print(deck.dealt)
print(f"Player count: {deck.player_count_A11} & {deck.player_count_A1}")
print(f"Dealer count: {deck.dealer_count_A11} & {deck.dealer_count_A1}")
if deck.score_check()[0] > deck.score_check()[1]:
print("Player wins!")
bankroll.player_bank += bankroll.curr_bet
print(f"Your bankroll is now: {bankroll.player_bank}")
elif deck.score_check()[0] == deck.score_check()[1]:
print("Push! Bets returned")
print(f"Your bankroll is now: {bankroll.player_bank}")
else:
print("Dealer wins!")
bankroll.player_bank -= bankroll.curr_bet
print(f"Your bankroll is now: {bankroll.player_bank}")
make_deposit = "N"
make_withdraw = "N"
示例13: __init__
# 需要导入模块: from Deck import Deck [as 别名]
# 或者: from Deck.Deck import shuffle [as 别名]
class Hearts:
def __init__(self):
self.roundNum = 0
self.trickNum = 0 # initialization value such that first round is round 0
self.dealer = -1 # so that first dealer is 0
self.passes = [1, -1, 2, 0] # left, right, across, no pass
self.currentTrick = Trick()
self.trickWinner = -1
self.heartsBroken = False
self.losingPlayer = None
self.passingCards = [[], [], [], []]
# Make four players
self.players = [Player("Danny"), Player("Desmond"), Player("Ben"), Player("Tyler")]
'''
Player physical locations:
Game runs clockwise
p3
p2 p4
p1
'''
# Generate a full deck of cards and shuffle it
self.newRound()
def handleScoring(self):
p, highestScore = None, 0
print "\nScores:\n"
for player in self.players:
print player.name + ": " + str(player.score)
if player.score > highestScore:
p = player
highestScore = player.score
self.losingPlayer = p
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()
def getFirstTrickStarter(self):
for i,p in enumerate(self.players):
if p.hand.contains2ofclubs:
self.trickWinner = i
def dealCards(self):
i = 0
while(self.deck.size() > 0):
self.players[i % len(self.players)].addCard(self.deck.deal())
i += 1
def evaluateTrick(self):
self.trickWinner = self.currentTrick.winner
p = self.players[self.trickWinner]
p.trickWon(self.currentTrick)
self.printCurrentTrick()
print p.name + " won the trick."
# print 'Making new trick'
self.currentTrick = Trick()
print self.currentTrick.suit
def passCards(self, index):
print self.printPassingCards()
passTo = self.passes[self.trickNum] # how far to pass cards
passTo = (index + passTo) % len(self.players) # the index to which cards are passed
while len(self.passingCards[passTo]) < cardsToPass: # pass three cards
passCard = None
while passCard is None: # make sure string passed is valid
passCard = self.players[index].play(option='pass')
if passCard is not None:
# remove card from player hand and add to passed cards
self.passingCards[passTo].append(passCard)
self.players[index].removeCard(passCard)
def distributePassedCards(self):
for i,passed in enumerate(self.passingCards):
for card in passed:
self.players[i].addCard(card)
self.passingCards = [[], [], [], []]
#.........这里部分代码省略.........
示例14: __init__
# 需要导入模块: from Deck import Deck [as 别名]
# 或者: from Deck.Deck import shuffle [as 别名]
class Probability:
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
def show(self):
# Results
self.head = "%s hands dealt\n%s\n"
self.head = self.head % (self.rounds, (len(self.head) - 1) * "=")
print(self.head)
for choice in self.choices:
choice = choice.lower().replace(" ", "")
if choice == "f" or choice == "flush":
print("Flush occurred %s times" % self.flush)
print("Estimated P(Flush) is: %.3f\n" % ((self.flush * 100)/self.rounds))
elif choice == "fh" or choice == "fullhouse":
print("Full House occurred %s times" % self.fullHouse)
print("Estimated P(Full House) is: %.3f\n" % ((self.fullHouse * 100)/self.rounds))
elif choice == "toak" or choice == "threeofakind":
print("Three of a kind %s times" % self.threeOfAKind)
print("Estimated P(Three of a kind) is: %.3f\n" % ((self.threeOfAKind * 100)/self.rounds))
elif choice == "foak" or choice == "fourofakind":
print("Four of a kind %s times" % self.fourOfAKind)
print("Estimated P(Four of a kind) is: %.3f\n" % ((self.fourOfAKind * 100)/self.rounds))
elif choice == "op" or choice == "onepair":
print("One Pair %s times" % self.onePair)
print("Estimated P(One Pair) is: %.3f\n" % ((self.onePair * 100)/self.rounds))
elif choice == "tp" or choice == "twopairs":
print("Two Pairs %s times" % self.twoPairs)
print("Estimated P(Two Pairs) is: %.3f\n" % ((self.twoPairs * 100)/self.rounds))
def plot(self):
pokerlists = []
header = []
for choice in self.choices:
choice = choice.lower().replace(" ", "")
if choice == "f" or choice == "flush":
pokerlists.append(self.flush)
header.append("Flush")
elif choice == "fh" or choice == "fullhouse":
pokerlists.append(self.fullHouse)
header.append("Full House")
elif choice == "toak" or choice == "threeofakind":
pokerlists.append(self.threeOfAKind)
#.........这里部分代码省略.........
示例15: Table
# 需要导入模块: from Deck import Deck [as 别名]
# 或者: from Deck.Deck import shuffle [as 别名]
class Table(object):
'''This is essentially the House. It runs the game.'''
def __init__(self):
# self.players is going to be a dict with ints as keys denoting the seats each player has.
self.players = {}
self.button_seat = -1
# Here's how the rake works: $1 for every $10 in pot that is CALLED. Take first from main pot, then side pots in order until limit is reached ($5 here).
self.rake_rules = {
'limit': 5,
'amt': 1,
'in': 10,
}
self.box = 0
self.tips = 0
self.units = [2, 2, 4, 4]
self.limits = [10, 10, 20, 20]
self.action = None
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 = []
def take_blinds(self):
self.take_bet(1)
self.incr_action()
self.take_bet(2)
def burn_one_card(self):
return self.deck.deal()
def deal_one_hole_card_to_all_players(self):
# I'm not 100% happy with this, but it works.
while True:
self.incr_action()
self.players[self.action].hole_cards.append(self.deck.deal())
if self.action == self.button_seat:
break
def deal_one_community_card(self):
self.board.append(self.deck.deal())
def flop(self):
self.burn_one_card()
for i in xrange(3):
self.deal_one_community_card()
def turn(self):
self.burn_one_card()
self.deal_one_community_card()
def river(self):
self.turn()
def pots_need_action(self, position):
for pot in self.pots:
if pot.action_needed(position):
return True
return False
def run_betting_round(self):
last_to_act = None
pots_ended = False
while self.action != last_to_act:
if self.pots_need_action(self.action):
error = None
decision = self.players[self.action].decide(error)
if decision == Decision.FOLD:
for pot in self.pots:
pot.make_ineligible_to_win(self.action)
elif decision == Decision.CHECK:
pass # I may accommodate this under CALL
elif decision == Decision.CALL:
# Remember that if you skim for a side pot, you have to effectively fold the current action out of any new side pot you make
# Um is that true? Or does Pot skim method do that for me?
self.take_bet(self.current_call_amt())
elif decision == Decision.RAISE:
pass
last_to_act = self.action
potential_winner = self.look_for_winner()
if potential_winner is not None:
for pot in self.pots:
pot.end_round()
return potential_winner
if not self.incr_action(): # Side effect of moving action
for pot in self.pots:
pot.end_round()
pots_ended = True
break # Betting is done
if not pots_ended:
for pot in self.pots:
pot.end_round()
self.take_rake()
#.........这里部分代码省略.........