def __init__(self): self.players = Players() self.players.createPlayer('** Dealer **', Player.PlayerType[2]) self.deck = Deck() self.tableMax = 10 self.tableMin = 1 self.players.createPlayer('Human Player', Player.PlayerType[0], 100) self.players.createPlayer('CPU Player 1', Player.PlayerType[1], 100)
def __init__(self, players): self.deck = Deck() self.deck.fillDeck() self.playing = False self.actions = {} self.players = players self.nextPlayer = iter(self.nextPlayerIterFunc()) self.currentPlayer = next(self.nextPlayer)
def __init__(self, players): super(Stress, self).__init__(players) self.playFlag = False self.currentPlayer = None self.skipNextTurn = False # Discard pile used to pick up with cheat moves self.played = Deck() # Dictionary to define possible actions to take self.actions = { "{players}" : self.getPlayers, "{start}" : self.playStress, "{play}" : self.playCards, "{hand}" : self.showHand, "{help}" : self.getHelp }
def __init__(self, table=None): self.winners = [] self.alreadyShowedGameRound = False self.table = table self.deck = Deck() self.gameRound = GameRound.PREFLOP self.maxBet = 0 self.currentPlayer = None for player in self.table.players: player.game = self self.table.board = Board() self.table.board.game = self
class Blackjack: def __init__(self): self.__house = Hand('house') self.__player = Hand('player') self.__cards = Deck() self.__cards.deal(self.__house, 2) self.__house.__deckList[0].status = 'not hidden' self.__cards.deal(self.__player, 2) for card in self.__player.__deckList: card.status = 'not hidden' def ask(self): answer = input('HIT OR STAND? ') while not (answer.lower() == 'hit' or answer.lower() == 'stand'): answer = input('ERROR. HIT OR STAND? ') return answer def printBoard(self): print('House') print() def main(self): answer = self.ask() while answer.lower() == 'hit': self.__cards.deal(self.__player, 1) if self.__player.sum() >= 21: break answer = self.ask() while self.__house.sum() < 17: self.__cards.deal(self.__house, 1)
def __init__(self, WinningHands= '',NumberHoleCards=2, NumberCommunityCards=3): self.Deck = Deck() self.Deck.shuffle() self.HoleCards = [self.Deck.draw(), self.Deck.draw()] self.CommunityCards = [] self.NumberHoleCards = NumberHoleCards self.NumberCommunityCards = NumberCommunityCards self.NumberCards = NumberHoleCards + NumberCommunityCards
def __init__(self, noplayers, initial_stake): self.players = [] self.dealer = Player("Dealer", 10000) self.deck = Deck() self.deck.shuffle() cards = self.deck.deal(2) dealerHand = Hand() dealerHand.add_cards(cards) self.dealer.initialHand(dealerHand) for i in range(0, noplayers): player = Player("Player" + str(i + 1), initial_stake) cards = self.deck.deal(2) playerHand = Hand() playerHand.add_cards(cards) player.initialHand(playerHand) self.players.append(player) print_all_hands(self.dealer, self.players) self.play_rounds()
def __init__(self): self.__house = Hand('house') self.__player = Hand('player') self.__cards = Deck() self.__cards.deal(self.__house, 2) self.__house.__deckList[0].status = 'not hidden' self.__cards.deal(self.__player, 2) for card in self.__player.__deckList: card.status = 'not hidden'
def __init__(self, players): super(Cheat, self).__init__(players) self.playFlag = False self.cheatcaller = None self.nextRank = iter(self.nextRankIterFunc()) self.currentPlayer = None self.currentRank = None # Discard pile used to pick up with cheat moves self.discard = Deck() # Buffer deck to hold cards while cheaters may cheat self.bufferDeck = CardStack() # Dictionary to define possible actions to take self.actions = { "{players}": self.getPlayers, "{start}": self.playCheat, "{play}": self.playCards, "{hand}": self.showHand, "{cheat}": self.callCheat, "{help}": self.getHelp }
def generateAllFullHands(verbose=False): previousPercentage = 0. deck = Deck() fhs = [0] * 2598960 for i, cards in enumerate(combinations(deck, 5)): fhs[i] = FullHand(*cards) if verbose: percentage = round(i / 2598960, 3) if percentage > previousPercentage: previousPercentage = percentage print("{:.1f}%".format(percentage * 100)) return fhs
def __init__(self, players): super(BigTwo, self).__init__(players) self.playFlag = False self.cheatcaller = None self.currentNumCards = 0 self.nextRank = 0 self.currentPlayer = None self.currentRank = None self.endTrick = True self.passCount = 0 # Discard pile used to pick up with cheat moves self.discard = Deck() # Buffer deck to hold cards while cheaters may cheat self.bufferDeck = CardStack() # Dictionary to define possible actions to take self.actions = { "{players}": self.getPlayers, "{start}": self.playBigTwo, "{play}": self.playCards, "{hand}": self.showHand, "{pass}": self.callPass, "{help}": self.getHelp }
class PlayCards(): def __init__(self): self.pot_size = 0 self.bet_size = 0 self.correct = 0 self.success_ratio = 0 def setup_deck(self): self.dealer_deck = Deck() self.cards_dealt = Deck() self.dealer_deck.fresh_deck(suits, ranks) self.dealer_deck.shuffle() def set_pot_size(self): self.pot_size = int(input('Please select your starting pot size: ')) return self.pot_size def get_pot_size(self): return self.pot_size def set_bet_size(self, bet_style, whole): if (whole) and self.pot_size == 1: return 1 if bet_style == 'quarter': bet_size = self.pot_size / 4 elif bet_style == 'half': bet_size = self.pot_size / 2 elif bet_style == 'max': bet_size = self.pot_size else: bet_size = input('Please select your bet amount: ') if int(float(bet_size)) > self.pot_size: print("Bet too large. Setting bet to max.") bet_size = self.pot_size if whole: return int(float(bet_size)) else: return bet_size def colour_guess(self, colour_selector, auto_fin): colours = self.dealer_deck.count_colours() if (auto_fin) and (0 in colours): self.bet_style = 'max' if colour_selector == 'random': return choice(('r', 'b')) elif colour_selector == 'smart': if colours[0] > colours[1]: return 'r' elif colours[1] > colours[0]: return 'b' else: return choice(['r', 'b']) else: colour = input("Please choose a card colour ('r' or 'b'): ") if colour not in ('r', 'b'): print("Invalid colour selection.") self.colour_guess(colour_selector, auto_fin) def make_bet(self, colour, bet_size): drawn_card = self.dealer_deck.get_top_card() if colour == 'r': colour_str = 'red' else: colour_str = 'black' print("---Drawing a card---") print("You bet {} that the card will be {}".format( bet_size, colour_str)) print("The card is: {}".format(drawn_card)) if drawn_card.colour == colour: self.pot_size += bet_size print("Correct! You win {}.".format(bet_size)) else: self.pot_size -= bet_size print("Incorrect.. You lose {}.".format(bet_size)) self.cards_dealt.add_card(self.dealer_deck.remove_card()) def play(self, colour_selector=None, bet_style=None, auto_fin=False, slow=True, whole=True): self.setup_deck() self.bet_style = bet_style self.pot_size = self.set_pot_size() playing = True while playing: if len(self.dealer_deck) > 0 and (self.pot_size > 0): colour = self.colour_guess(colour_selector, auto_fin) bet_size = self.set_bet_size(self.bet_style, whole) self.make_bet(colour, bet_size) else: playing = False break ##TODO display stats ## print("Your current pot size is: {}.".format(self.pot_size)) self.dealer_deck.show_colours() if slow: q = input("----------------------------------------------") else: print("----------------------------------------------") print("You finished with a pot size of: {}".format(self.pot_size))
from itertools import combinations from multiprocessing import Lock, Process, Array, Value from time import time from scipy.special import comb from Cards import Cards, Deck, FullHand from Enums import GameRound from Player import Player from Table import Table showdownCombinations = combinations(Deck(), 9) numberOfCombinations = comb(52, 9, exact=True, repetition=False) chunks = [] chunkSize = 100 def generateAllFullHands(verbose=False): previousPercentage = 0. deck = Deck() fhs = [0] * 2598960 for i, cards in enumerate(combinations(deck, 5)): fhs[i] = FullHand(*cards) if verbose: percentage = round(i / 2598960, 3) if percentage > previousPercentage: previousPercentage = percentage print("{:.1f}%".format(percentage * 100)) return fhs
from Cards import Card, Deck from Game21 import Game21 f = open('data.txt', 'w') count = 1000 f.write('A list of {} Random 21 Hands\r\n'.format(count)) deck = Deck() game21 = Game21() for x in range(1, count): deck.cleanShuffle() cards = deck.dealCard(2) while (game21.handValue(cards) < 21): cards.append(deck.dealCard(1).pop()) cardsString = '' for c in cards: cardsString += '{}{} '.format(c.rank, c.suit) f.write('{}\r\n'.format(cardsString)) print("{}% done".format((float(x + 1) / float(count)) * 100)) f.close()
class Game21: global inProgress global players global deck global tableMax global tableMin def __init__(self): self.players = Players() self.players.createPlayer('** Dealer **', Player.PlayerType[2]) self.deck = Deck() self.tableMax = 10 self.tableMin = 1 self.players.createPlayer('Human Player', Player.PlayerType[0], 100) self.players.createPlayer('CPU Player 1', Player.PlayerType[1], 100) def startGame(self): for player in self.players.getPlayers(): player.returnAllCards() self.deck.cleanShuffle() #prompt for wager startingAmount for player in self.players.getPlayers(): if player.playerType is not Player.PlayerType[ 2] and player.money <= 0: print("{} has no money and is no longer playing.".format( player.getName())) self.players.remove(player) if player.playerType == Player.PlayerType[1]: # CPU logic, this should be updated if player.money < 5: player.wagerAmount = 2 else: player.wagerAmount = 1 elif player.playerType == Player.PlayerType[0]: userInput = '' while (userInput is ''): userInput = raw_input( "{} enter wager amount ({}-{}) or (Q)uit: ".format( player.getName(), self.tableMin, self.tableMax)) if not userInput.isdigit(): if userInput.capitalize() in ['Q']: self.gameOver() break print("'{}' is not a valid wager amount".format( userInput)) userInput = '' elif int(userInput) < self.tableMin: print( "Enter a wager greater than {}, the table minimum." .format(self.tableMin)) userInput = '' elif int(userInput) > self.tableMax: print("Enter a wager less than {}, the table maximum.". format(self.tableMax)) userInput = '' else: player.wagerAmount = int(userInput) print("{} bets {}".format(player.getName(), player.wagerAmount)) self.dealAllPlayers(2) self.displayGameStatus() self.playHands() def gameOver(self): print("Thanks for playing!") quit() def handValue(self, cards): value = 0 aceCount = 0 for card in cards: if card.rank == '1': aceCount += 1 value += 10 elif card.rank in ['J', 'Q', 'K']: value += 10 else: value += int(card.rank) while value > 21 and aceCount > 0: value -= 9 aceCount -= 1 return value def dealAllPlayers(self, cardsToDeal): for player in self.players.getPlayers(): player.dealt(self.deck.dealCard(cardsToDeal)) print("All players dealt {} cards".format(cardsToDeal)) def hit(self, player): print("{} takes a hit".format(player.getName())) cardDealt = self.deck.dealCard(1) player.dealt(cardDealt) print("{} drew a {}{}".format(player.getName(), cardDealt[0].rank, cardDealt[0].suit)) def displayHand(self, player): print("{}'s Hand".format(player.getName())) for x in range(0, len(player.getHand())): print("Card {} is a {}{}".format(x + 1, player.getHand()[x].rank, player.getHand()[x].suit)) hv = self.handValue(player.getHand()) print("{} has a total had value of {}".format(player.getName(), hv)) if (hv > 21): print("{} HAS **BUSTED**".format(player.getName())) def displayGameStatus(self): for player in self.players.getPlayers(): self.displayHand(player) def playHands(self): for player in self.players.getPlayers(): if player.playerType == Player.PlayerType[1]: # CPU logic, this should be updated while self.handValue(player.getHand()) < 17: self.hit(player) self.displayHand(player) if player.getHand() <= 21: print("{} stays with {}".format( player.getName(), self.handValue(player.getHand()))) elif player.playerType == Player.PlayerType[0]: usersTurn = True userInput = '' while (usersTurn): while (userInput not in ['H', 'D', 'S', 'ST']): userInput = raw_input( 'Enter action, (H)it, (D)ouble, (SP)lit, (S)tay: ' ).capitalize() if userInput == "S": self.displayHand(player) print("{} stays".format(player.getName())) usersTurn = False if userInput == "H": self.hit(player) self.displayHand(player) if self.handValue(player.getHand()) >= 21: usersTurn = False userInput = '' #check if all player busted highHand = -1 for player in self.players.getPlayers(): if player.playerType is not Player.PlayerType[2]: currentHand = self.handValue(player.getHand()) if currentHand <= 21 and currentHand > highHand: highHand = currentHand if highHand < 0: print("All Players busted, no need to play dealers hand.") else: dealer = self.players.getDealer() dealerHandScore = self.handValue(dealer.getHand()) while dealerHandScore < highHand and dealerHandScore <= 17: print("Dealer had {}, needs to hit.".format(dealerHandScore)) self.hit(dealer) dealerHandScore = self.handValue(dealer.getHand()) self.displayHand(dealer) self.evaluateGame() def displayCurrentMoneyState(self): print(" ***** Money ***** ") for player in self.players.getPlayers(): print("${} - {}".format(player.money, player.getName())) print(" ***************** ") def evaluateGame(self): print("Evaluating Game") print("Dealer First") dealer = self.players.getDealer() dealerHandValue = self.handValue(dealer.getHand()) if dealerHandValue > 21: print("Dealer Busted!") dealerHandValue = -1 else: print("{} had a total of {}".format(dealer.getName(), dealerHandValue)) for player in self.players.getPlayers(): if (player.playerType is not Player.PlayerType[2]): hv = self.handValue(player.getHand()) if hv > 21: print("{} Busted".format(player.getName())) player.money -= player.wagerAmount elif hv == 21 and len(player.getHand()) == 2: print("{} has BLACKJACK!".format(player.getName())) player.money += ( player.wagerAmount + (player.wagerAmount / 2) ) # what happens if you bet an odd ammount? We need to make money a float... else: print("{} had a total of {}".format(player.getName(), hv)) if hv == dealerHandValue: print("{} pushes".format(player.getName())) elif (hv < dealerHandValue): print("{} lost".format(player.getName())) player.money -= player.wagerAmount else: print("{} is a WINNER!".format(player.getName())) player.money += player.wagerAmount self.displayCurrentMoneyState() self.startGame()
# deal random hands to all players (2) # simulate run out till showdown # keep win counter for all players # display win % at the end # sort hands in ascending order from left to right import sys import csv import time from PokerHands import PokerHand from Cards import Card from Cards import Deck from Player import Player from Game import Game deck = Deck() # MERGE SORT def merge(left, right): if not len(left) or not len(right): return left or right result = [] i, j = 0, 0 while len(result) < len(left) + len(right): if left[i].rcmp(right[j]) < 0: result.append(left[i]) i += 1 else: result.append(right[j])
def testDeckRemove(self): deck = Deck() card23 = Card(2, 3) deck.remove(card23)
class Manager: def __init__(self, noplayers, initial_stake): self.players = [] self.dealer = Player("Dealer", 10000) self.deck = Deck() self.deck.shuffle() cards = self.deck.deal(2) dealerHand = Hand() dealerHand.add_cards(cards) self.dealer.initialHand(dealerHand) for i in range(0, noplayers): player = Player("Player" + str(i + 1), initial_stake) cards = self.deck.deal(2) playerHand = Hand() playerHand.add_cards(cards) player.initialHand(playerHand) self.players.append(player) print_all_hands(self.dealer, self.players) self.play_rounds() def hit_or_hold(self): while determine_if_anyone_can_play(self.players): for player in self.players: if player.status == "play": print("==============================================") print(player.identifier) inputString = input('Do you want to hit or hold?') print("==============================================") if inputString == "hold": player.status = "hold" elif inputString == "hit": card = self.deck.deal(1)[0] player.hand.add_card(card) handvalue = player.hand.adjust_for_ace() print("The value of the current hand is " + str(handvalue)) print("==============================================") if handvalue > 21: player.status = 'bust' def finish_dealer_hand(self): print("Here are the dealer's cards") for card in self.dealer.hand.cards: print(card) print("+==================================================") dealervalue = self.dealer.hand.adjust_for_ace() print("Initial hand value for dealer: " + str(dealervalue)) while dealervalue < 17: card = self.deck.deal(1)[0] print(card) self.dealer.hand.add_card(card) dealervalue = self.dealer.hand.adjust_for_ace() print("The value of dealer hand with card added is: " + str(dealervalue)) if dealervalue > 21: self.dealer.status = 'bust' def pay_bets(self): for player in self.players: if player.status == 'bust': player.lose_bet() elif self.dealer.status == 'bust': player.win_bet() elif player.hand.adjust_for_ace( ) > self.dealer.hand.adjust_for_ace(): player.win_bet() else: player.lose_bet() print( '==================================================================' ) print(player.identifier + " now has this total : " + str(player.total)) def play_rounds(self): want_to_play_game = True while want_to_play_game: place_bets(self.players) self.hit_or_hold() self.finish_dealer_hand() print_player_statuses(self.dealer, self.players) self.pay_bets() print( '==================================================================' ) inputString = input('Do you want to play again: yes/no?') if inputString == 'no': want_to_play_game = False else: cards = self.deck.deal(2) dealerHand = Hand() dealerHand.add_cards(cards) self.dealer.initialHand(dealerHand) for player in self.players: cards = self.deck.deal(2) playerHand = Hand() playerHand.add_cards(cards) player.initialHand(playerHand) player.status = 'play' print( '==================================================================' )
def setup_deck(self): self.dealer_deck = Deck() self.cards_dealt = Deck() self.dealer_deck.fresh_deck(suits, ranks) self.dealer_deck.shuffle()
class Stress(Game): #--------------------------------------------------- # Initializing attributes, and adding action methods #--------------------------------------------------- def __init__(self, players): super(Stress, self).__init__(players) self.playFlag = False self.currentPlayer = None self.skipNextTurn = False # Discard pile used to pick up with cheat moves self.played = Deck() # Dictionary to define possible actions to take self.actions = { "{players}" : self.getPlayers, "{start}" : self.playStress, "{play}" : self.playCards, "{hand}" : self.showHand, "{help}" : self.getHelp } #--------------------------------------------------- # Defining game actions #--------------------------------------------------- def getHelp(self, player, msglist): player.tell("To play cards on your turn, write {play} followed by the card you want to drop and the card you want to take. ") player.tell("For example, write \"{play} H4 S4\" to drop the 4 of Hearts and pick up the 4 of Spades. ") player.tell("In order to play a card, the card must you're picking up must be on the table. ") player.tell("The goal of the game is to have " + str(48 / len(self.players)) + " piles of four of a kind. ") player.tell("To see your hand, write {hand}. For help, write {help}.") def showHand(self, player, msglist): player.tell("The cards in your hand:") player.tell(player.getHand()) def playStress(self, player, msglist): size = len(self.players) if size != 2 and size != 3 and size != 4 and size != 6 and size != 12: player.tell("The number of players must divide twelve (2, 3, 4, 6, or 12 people") else: self.playing = True def getPlayers(self, player, msglist): player.tell("Current players: ") msg = "" for p in self.players: msg += (p.name + "\n") player.tell(msg[:-1]) def playCards(self, player, msglist): cards = msglist[1:] playedCards = [] for card in cards: card = Card(str(card[0]),str(card[1:])) playedCards.append(card) if not self.playing: player.tell("Wait for the game to start...") elif player != self.currentPlayer: player.tell("Wait for your turn...") elif (len(msglist) != 3): player.tell("You must drop one card and pick up one card.") elif (playedCards[1] not in self.played.cards): player.tell("You must pick up one of the played cards.") elif (playedCards[0] not in player.hand.cards): player.tell("You must own the card you want to drop.") else: self.played.addToDeck(playedCards[0]) player.hand.cards.remove(playedCards[0]) player.addToHand(self.played.remove(playedCards[1])) self.broadcast(str(self.currentPlayer) + " dropped " + str(playedCards[0]) + " and picked up " + str(playedCards[1])) self.showGUIHand(self.currentPlayer) self.playFlag = True #--------------------------------------------------- # Defining game rules #--------------------------------------------------- def pregameActions(self): # Set to players self.nextPlayer = iter(self.nextPlayerIterFunc()) # Make game announcements self.broadcast("The Stress Game is starting!") self.broadcast("There are %d players playing!" % len(self.players)) self.wait(1) for p in self.players: self.getHelp(p, None) self.wait(2) self.deck.shuffle() self.deck.dealCards(self.players, 48 / len(self.players)) self.played.addToDeck(self.deck.draw()) self.played.addToDeck(self.deck.draw()) self.played.addToDeck(self.deck.draw()) self.played.addToDeck(self.deck.draw()) for p in self.players: p.tell("//{hand}//" + p.getHand()) return True def preplayGuards(self): self.broadcast("It is %s\'s turn!\n" % self.currentPlayer.name) self.wait(.25) self.broadcast("Current cards are " + str(self.played)) self.wait(1) self.showHand(self.currentPlayer, None) return True def doPlay(self): while not self.playFlag: pass self.playFlag = False return True def checkForVictory(self): types = [] suits = { "H" : 0, "S" : 0, "D" : 0, "C" : 0 } for card in self.currentPlayer.hand.cards: if card.rank not in types: types.append(card.rank) suits[card.suit] = 1 return suits["H"] == 1 and suits["D"] == 1 and suits["S"] == 1 and suits["C"] and types == 48 / len(self.players) def endGame(self): self.wait(1) self.broadcast(str(self.currentPlayer) + " has " + str(48 / len(self.players)) + " piles of four of a kind and wins!") self.broadcast("Thanks for playing!")
class Bartok(Game): #--------------------------------------------------- # Initializing attributes, and adding action methods #--------------------------------------------------- def __init__(self, players): super(Bartok, self).__init__(players) self.playFlag = False self.currentPlayer = None self.skipNextTurn = False # Discard pile used to pick up with cheat moves self.played = Deck() # Dictionary to define possible actions to take self.actions = { "{players}": self.getPlayers, "{start}": self.playBartok, "{play}": self.playCards, "{hand}": self.showHand, "{draw}": self.drawCard, "{help}": self.getHelp } #--------------------------------------------------- # Defining game actions #--------------------------------------------------- def getHelp(self, player, msglist): player.tell( "To play cards on your turn, write {play} followed by the cards. ") player.tell( "For example, write \"{play} H4 S4\" to play the 4 of Hearts and the 4 of Spades. " ) player.tell( "In order to play a card, the card must match either the rank or the suite of the displayed card. " ) player.tell( "If you cannot play a card, you must draw. To draw the card, write {draw}. " ) player.tell("To see your hand, write {hand}. For help, write {help}.") def showHand(self, player, msglist): player.tell("The cards in your hand:") player.tell(player.getHand()) def playBartok(self, player, msglist): if len(self.players) < 2 or len(self.players) >= 9: player.tell("Not enough players to start the game...") else: self.playing = True def getPlayers(self, player, msglist): player.tell("Current players: ") msg = "" for p in self.players: msg += (p.name + " --- hand size: " + str(p.getHandSize()) + "\n") player.tell(msg[:-1]) def playCards(self, player, msglist): if not self.playing: player.tell("Wait for the game to start...") elif player != self.currentPlayer: player.tell("Wait for your turn...") elif (len(msglist) != 2): player.tell("You must play one card.") else: cards = msglist[1:] playedCards = [] for card in cards: card = Card(str(card[0]), str(card[1:])) playedCards.append(card) try: if playedCards[0].rank == self.played.lastCard( ).rank or playedCards[0].suit == self.played.lastCard().suit: player.playFromHand(playedCards, self.played) self.broadcast( str(self.currentPlayer) + " played " + str(playedCards[0])) self.showGUIHand(self.currentPlayer) # if playedCards[0].rank == '2': # self.nextPlayer.addToHand(self.deck.draw()) # self.nextPlayer.addToHand(self.deck.draw()) # self.skipNextTurn = True self.playFlag = True else: player.tell( "You cannot play this card! Play a card from the same suit or rank." ) return self.broadcast("They currently hold " + str(player.hand.size()) + " cards.") except NotInStackException: player.tell("You can only play cards that are in your hand.") def drawCard(self, player, msglist): if not self.playing: player.tell("Wait for the game to start...") elif player != self.currentPlayer: player.tell("Wait for your turn...") else: if (len(msglist) != 1): player.tell("Draw uses no arguments! Type {draw}") else: if self.deck.isEmpty() and self.played.isEmpty(): player.tell( "Both played and unplayed decks are empty, skip the turn." ) else: self.currentPlayer.addToHand(self.deck.draw()) self.showGUIHand(self.currentPlayer) self.broadcast(str(self.currentPlayer) + " drew one card!") self.playFlag = True #--------------------------------------------------- # Defining game rules #--------------------------------------------------- def pregameActions(self): # Set to players self.nextPlayer = iter(self.nextPlayerIterFunc()) # Make game announcements self.broadcast("The Bartok Game is starting!") self.broadcast("There are %d players playing!" % len(self.players)) self.wait(1) for p in self.players: self.getHelp(p, None) self.wait(2) self.deck.shuffle() self.deck.dealCards(self.players, 5) self.played.addToDeck(self.deck.draw()) for p in self.players: p.tell("//{hand}//" + p.getHand()) return True def preplayGuards(self): self.broadcast("It is %s\'s turn!" % self.currentPlayer.name) self.wait(.25) self.broadcast("Current card is " + str(self.played.lastCard())) self.wait(1) self.showHand(self.currentPlayer, None) return True def doPlay(self): while not self.playFlag: pass self.playFlag = False return True def checkForVictory(self): return self.currentPlayer.hand.isEmpty() def endGame(self): self.wait(1) self.broadcast( str(self.currentPlayer) + " has emptied their hand, and wins!") self.broadcast("Thanks for playing!")
print("How many players?") while num_players < 2: num_players = int(input()) if num_players == -1: quit() if num_players < 2: print("You need at least 2 players to play s******d! Try again...") for i in range(num_players): print("Enter Name for Player",i+1,":") name = input() players.append(ShitheadPlayer(name)) num_decks = 1+num_players//3 playing_deck = Deck(num_decks) playing_deck.shuffle() discard_pile = [] # Deal Cards for place in ['fd','fu','hand']: for i in range(3): for j in range(num_players): players[j].add_card(playing_deck.pop(),place) # Game player_ind = 0 direction = 1
class Game(object): #---------------------------------------- # Constructs a Game object #---------------------------------------- def __init__(self, players): self.deck = Deck() self.deck.fillDeck() self.playing = False self.actions = {} self.players = players self.nextPlayer = iter(self.nextPlayerIterFunc()) self.currentPlayer = next(self.nextPlayer) #---------------------------------------- # Parses whether a player input is an action. #---------------------------------------- def parseAction(self, player, msg): msglist = msg.split() if msglist[0] in self.actions: self.actions[msglist[0]](player, msglist) else: self.broadcast(msg, player.name + ": ") #---------------------------------------- # Broadcast a message to all the clients #---------------------------------------- def broadcast(self, msg, prefix=""): for p in self.players: p.tell(prefix + msg) #---------------------------------------- # Show a client their hand from the GUI #---------------------------------------- def showGUIHand(self, player): player.tell("//{hand}//" + player.getHand()) self.wait(.25) #---------------------------------------- # Sleep for given time #---------------------------------------- def wait(self, sleepTime): sleep(sleepTime) #---------------------------------------- # Iterator to return next player #---------------------------------------- def nextPlayerIterFunc(self): currPlayer = 0 while True: yield self.players[currPlayer] if (currPlayer < (len(self.players) - 1)): currPlayer = currPlayer + 1 else: currPlayer = 0 #---------------------------------------- # Phases of a turn #---------------------------------------- class StartPhase(State): #Begin the turn tag = "!" class PreplayPhase(State): #Things that can occur before a play tag = "@" class PlayPhase(State): #Things that occur to constitute a play tag = "#" class PostplayPhase(State): #Things that can occur after a play tag = "$" class EndPhase(State): #End the turn tag = "%" def quit(self): return True def onExit(self): return self.model.game.checkForVictory() #-------------------------------------------- # State machine to abstractly define a turn. # m is the machine # s is the list of states # t is the list of transitions #-------------------------------------------- def turnSpec(self, m, s, t): start = s("!") preplay = s("@") play = s("#") postplay = s("$") end = s("%") t("start", m.true, start) t(start, self.startGuards, preplay) t(preplay, self.preplayGuards, play) t(play, self.doPlay, postplay) t(postplay, self.postplayGuards, end) #------------------------------------------- # Methods to be extended by implementation. # Use to define rules of the game. #------------------------------------------- def startGuards(self): return True def preplayGuards(self): return True def doPlay(self): return True def postplayGuards(self): return True def checkForVictory(self): return True #---------------------------------------- # Phases of the game #---------------------------------------- class GameStart(State): tag = "^" class Turn(State): tag = "&" class GameOver(State): tag = "*" def quit(self): return True def onExit(self): self.model.game.endGame() self.model.game.playing = False #-------------------------------------------- # State machine to abstractly define the game. # m is the machine # s is the list of states # t is the list of transitions #-------------------------------------------- def gameSpec(self, m, s, t): start = s("^") turn = s("&") end = s("*") t("start", m.true, start) t(start, self.pregameActions, turn) t(turn, self.runTurn, end) t(turn, m.true, turn) # TODO Make this work #------------------------------------------- # Methods to be extended by implementation. # Use to define what happens before and after # the game. #------------------------------------------- def pregameActions(self): print("Game started") return True def endGame(self): print("Game completed") #-------------------------------------------- # Methods to control the state machines. # Can be extended but shouldn't be. #-------------------------------------------- def runTurn(self): self.currentPlayer = next(self.nextPlayer) return make( InnerMachine(self.currentPlayer.name + "\'s turn.", self.currentPlayer, self), self.turnSpec).run() def runGame(self): self.playing = True make(OuterMachine("Welcome to the game!", len(self.players), self), self.gameSpec).run()
def __init__(self, name): Deck.__init__(self) self.__deckList = [] self.__name = name self.value = [11,2,3,4,5,6,7,8,9,10,10,10,10]
from Cards import CardStack, Deck unplayedDeck = Deck() playedDeck = Deck() playedDeck.changeVisibility() # stuff outside this class should be in machine, just used it for testing class Player(object): """Represents a player object""" def __init__(self, name): super().__init__() self.name = name self.hand = CardStack() self.handSize = 0 def getHand(self): return str(self.hand.cards) def draw(self, num=1): if unplayedDeck.isEmpty(): saveCard = playedDeck.draw() while not playedDeck.isEmpty(): unplayedDeck.addToDeck(playedDeck.draw()) unplayedDeck.shuffle() playedDeck.addToDeck(saveCard) for i in range(num): self.hand.cards.append(unplayedDeck.draw()) self.handSize += 1 def takeAll(self):
class Game: def __init__(self, table=None): self.winners = [] self.alreadyShowedGameRound = False self.table = table self.deck = Deck() self.gameRound = GameRound.PREFLOP self.maxBet = 0 self.currentPlayer = None for player in self.table.players: player.game = self self.table.board = Board() self.table.board.game = self def __str__(self): representation = "" if not self.alreadyShowedGameRound: if self.gameRound != GameRound.PREFLOP: representation += "\n\n" representation += "Game Round: {}\n\n".format(self.gameRound.name) if self.gameRound != GameRound.END: representation += "Player playing: {}\n\n{}\n".format( self.currentPlayer, self.table) else: representation += "Winner: " + str(self.winners) return representation def handleGameRound(self): self.currentPlayer = self.table.firstToSpeak() if self.gameRound == GameRound.PREFLOP: self.handlePreFlop() elif self.gameRound == GameRound.FLOP: self.handleFlop() elif self.gameRound == GameRound.TURN: self.handleTurn() elif self.gameRound == GameRound.RIVER: self.handleRiver() elif self.gameRound == GameRound.END: bestFiveCards = { player: player.getBestFiveCards() for player in self.table.players } ranking = sorted(bestFiveCards, key=lambda x: bestFiveCards[x].point, reverse=True) bestPoint = bestFiveCards[ranking[0]].point self.winners.extend( filter(lambda x: bestFiveCards[x].point == bestPoint, ranking)) # handle winners, tiers and losers money return self.winners else: raise GameShouldHaveEndedException # print(self) self.handleGameRound() def handlePreFlop(self): if self.maxBet == 0: self.table.handleSmallBlind() self.table.handleBigBlind() self.maxBet = self.table.bigBlind # for player in self.table.players: # player.cards = Cards(*self.getRandomCardsFromDeck(2)) self.currentPlayer.play() self.advanceInGame() def handleFlop(self): if self.maxBet == 0: self.table.board[0], self.table.board[1], self.table.board[ 2] = self.getRandomCardsFromDeck(3) self.currentPlayer.play() self.advanceInGame() def handleTurn(self): if self.maxBet == 0: self.table.board[3] = self.getRandomCardsFromDeck(1)[0] self.currentPlayer.play() self.advanceInGame() def handleRiver(self): if self.maxBet == 0: self.table.board[4] = self.getRandomCardsFromDeck(1)[0] self.currentPlayer.play() self.advanceInGame() def prepareForNextRound(self): for player in self.table.players: player.hasSpoken = False player.currentBet = 0 self.alreadyShowedGameRound = False def advanceInGame(self): if len(list(filter(lambda x: not x.isActive, self.table.players))) == 1: self.gameRound = GameRound.END self.prepareForNextRound() if all( map(lambda x: x.isReadyToProceedToNextRound(), self.table.players)): self.gameRound = GameRound(self.gameRound + 1) self.prepareForNextRound() self.currentPlayer = self.table.firstToSpeak() else: self.currentPlayer = self.currentPlayer.nextToSpeak() def getRandomCardsFromDeck(self, numberOfCards): return [ self.deck.pop(random.randrange(len(self.deck))) for _ in range(numberOfCards) ] def updateGameRound(self): if any(map(lambda x: x.hand is None, self.table.players)): self.gameRound = GameRound.PREFLOP numberOfCardsFlipped = len( list(filter(lambda x: x is not None, self.table.board))) if numberOfCardsFlipped == 0: self.gameRound = GameRound.FLOP elif numberOfCardsFlipped == 3: self.gameRound = GameRound.TURN elif numberOfCardsFlipped == 4: self.gameRound = GameRound.RIVER elif numberOfCardsFlipped == 5: self.gameRound = GameRound.END else: raise IncorrectNumberOfCardsFlippedException
class Cheat(Game): def __init__(self, players): super(Cheat, self).__init__(players) self.playFlag = False self.cheatcaller = None self.nextRank = iter(self.nextRankIterFunc()) self.currentPlayer = None self.currentRank = None # Discard pile used to pick up with cheat moves self.discard = Deck() # Buffer deck to hold cards while cheaters may cheat self.bufferDeck = CardStack() # Dictionary to define possible actions to take self.actions = { "{players}": self.getPlayers, "{start}": self.playCheat, "{play}": self.playCards, "{hand}": self.showHand, "{cheat}": self.callCheat, "{help}": self.getHelp } #--------------------------------------------------- # Current rank iterator #--------------------------------------------------- def nextRankIterFunc(self): currRank = 0 while True: yield ranks()[currRank] if (currRank < (len(ranks()) - 1)): currRank += 1 else: currRank = 0 #--------------------------------------------------- # Defining game actions #--------------------------------------------------- def getHelp(self, player, msglist): player.tell( "To play cards on your turn, write {play} followed by the cards. ") player.tell( "For example, write \"{play} H4 S4\" to play the 4 of Hearts and the 4 of Spades. " ) player.tell( "If you think a player played cards that aren't of the current rank, announce {cheat}. " ) player.tell( "If they were lying, they have to pick up all the played cards... but if the weren't... you do! " ) player.tell("To see your hand, write {hand}. For help, write {help}.") def showHand(self, player, msglist): player.tell("The cards in your hand:") player.tell(player.getHand()) def playCheat(self, player, msglist): if len(self.players) < 3: player.tell("Not enough players to start the game...") else: self.playing = True def getPlayers(self, player, msglist): player.tell("Current players: ") msg = "" for p in self.players: msg += (p.name + " --- hand size: " + str(p.getHandSize()) + "\n") player.tell(msg[:-1]) def playCards(self, player, msglist): if not self.playing: player.tell("Wait for the game to start...") elif player != self.currentPlayer: player.tell("Wait for your turn...") elif len(msglist) == 1: player.tell("You have to play a card.") else: cards = msglist[1:] playedCards = [] for card in cards: card = Card(str(card[0]), str(card[1:])) playedCards.append(card) try: player.playFromHand(playedCards, self.bufferDeck) self.showGUIHand(self.currentPlayer) self.broadcast(player.name + " has played " + str(self.bufferDeck.size()) + " card(s).") self.broadcast("They currently hold " + str(player.hand.size()) + " cards.") self.playFlag = True except NotInStackException: player.tell("You can only play cards that are in your hand.") def callCheat(self, player, msglist): if not self.playing: player.tell("Wait for the game to start...") elif player == self.currentPlayer: player.tell("You can\'t call Cheat on yourself...") else: self.cheatCaller = player #--------------------------------------------------- # Defining game rules #--------------------------------------------------- def pregameActions(self): # Set to players self.nextPlayer = iter(self.nextPlayerIterFunc()) # Make game announcements self.broadcast("The Cheat Game is starting!") self.broadcast("There are %d players playing!" % len(self.players)) self.wait(1) for p in self.players: self.getHelp(p, None) self.wait(2) self.deck.shuffle() while not self.deck.isEmpty(): self.currentPlayer = next(self.nextPlayer) self.currentPlayer.addToHand(self.deck.draw()) for p in self.players: self.showGUIHand(p) return True def preplayGuards(self): self.currentRank = next(self.nextRank) self.broadcast("It is %s\'s turn!" % self.currentPlayer.name) self.wait(.25) self.broadcast("The rank this turn is " + self.currentRank + ".") self.wait(1) self.showHand(self.currentPlayer, None) return True def doPlay(self): while not self.playFlag: pass self.playFlag = False return True def postplayGuards(self): cheating = False for c in self.bufferDeck.cards: self.discard += c if c.rank != self.currentRank: cheating = True self.bufferDeck.empty() self.wait(1) self.broadcast("You have 10 seconds to announce {cheat}.") self.cheatCaller = None t_end = time() + 10 while self.cheatCaller is None and time() < t_end: pass if self.cheatCaller is not None: self.broadcast(self.cheatCaller.name + " has called Cheat!") self.wait(2) if cheating: self.broadcast( "%s was cheating, and has to pick up the stack! " % self.currentPlayer.name) while not self.discard.isEmpty(): self.currentPlayer.addToHand(self.discard.draw()) self.showGUIHand(self.currentPlayer) else: self.broadcast( "%s wasn't cheating... %s has to pick up the stack..." % (self.currentPlayer.name, self.cheatCaller.name)) while not self.discard.isEmpty(): self.cheatCaller.addToHand(self.discard.draw()) self.showGUIHand(self.cheatCaller) else: self.broadcast("Time's up!") if not self.discard.isEmpty(): self.wait(.5) self.broadcast("The discard pile has %d cards in it." % self.discard.size()) return True def checkForVictory(self): return self.currentPlayer.hand.isEmpty() def endGame(self): self.wait(1) self.broadcast(self.currentPlayer.name + " has emptied their hand, and wins!") self.broadcast("Thanks for playing!")
class MissStudHand: def __init__(self, WinningHands= '',NumberHoleCards=2, NumberCommunityCards=3): self.Deck = Deck() self.Deck.shuffle() self.HoleCards = [self.Deck.draw(), self.Deck.draw()] self.CommunityCards = [] self.NumberHoleCards = NumberHoleCards self.NumberCommunityCards = NumberCommunityCards self.NumberCards = NumberHoleCards + NumberCommunityCards def Cards(self): return itertools.chain(self.HoleCards, self.CommunityCards) def CountsByRank(self): CountsDict = {} for card in self.Cards(): if card.rank in CountsDict: CountsDict[card.rank] += 1 else: CountsDict[card.rank] = 1 # CountsDict[card.rank] += 1 if card.rank in CountsDict else CountsDict[card.rank] = 1 return CountsDict def __repr__(self): return '\n'.join(str(card) for card in self.Cards()) def MaxCardValue(self): return max([c.rank for c in self.Cards()]) def MinCardValue(self): return min([c.aceLow() for c in self.Cards()]) def MaxCardDistance(self): return self.MaxCardValue() - self.MinCardValue() def MaxCard(self): return max([card for card in self.Cards()]) def MinCard(self): if self.MaxCard().rank == 14: return self.MaxCard() else: return min([card for card in self.Cards()]) def SuitedCards(self, suit): return sum([1 for card in self.Cards() if card.suit == suit]) def NumberVisibleCards(self): return len(self.HoleCards) + len(self.CommunityCards) def NumberUnseenCards(self): return self.NumberCards - self.NumberVisibleCards() def IsPair(self): return sum([1 for n in self.CountsByRank().values() if n >=2]) >= 1 def IsTwoPair(self): return sum([1 for n in self.CountsByRank().values() if n >=2]) >= 2 def IsThreeOfaKind(self): return sum([1 for n in self.CountsByRank().values() if n >=3]) >= 1 def IsFourOfaKind(self): return sum([1 for n in self.CountsByRank().values() if n >=4]) >= 1 def IsFullHouse(self): Pair = sum([1 for n in self.CountsByRank().values() if n ==2]) == 1 Trips = sum([1 for n in self.CountsByRank().values() if n ==3]) == 1 return Pair and Trips def CountMatches(self, count): d = self.CountsByRank() return sum([1 for v in d.values() if v == count]) def IsFlush(self): suits = ['Clubs', 'Diamonds', 'Hearts', 'Spades'] return self.NumberVisibleCards() == max([self.SuitedCards(s) for s in suits]) def IsStraight(self): if self.MaxCard().rank == 14: return self.IsStraight_AceLow() else: return self.IsStraight_AceHigh() def IsStraight_AceLow(self): l = [c.rank for c in self.Cards()] l = [1 if rank == 14 else rank for rank in l] l.sort() IsStraight = True for i in range(len(l)-1): if l[i]+1 != l[i+1]: IsStraight = False return IsStraight or self.IsStraight_AceHigh() def IsStraight_AceHigh(self): l = [c.rank for c in self.Cards()] l.sort() IsStraight = True for i in range(len(l)-1): if l[i]+1 != l[i+1]: IsStraight = False return IsStraight def IsPossible_Pair(self): IsEnoughCardsLeft = self.NumberUnseenCards() >= 1 return self.IsPair() or IsEnoughCardsLeft def IsPossible_TwoPair(self): IsEnoughCardsLeft = True if self.IsPair() and self.NumberUnseenCards() >= 1 else self.NumberUnseenCards() >= 2 return self.IsTwoPair() or IsEnoughCardsLeft def IsPossible_Trips(self): IsEnoughCardsLeft = True if self.IsPair() and self.NumberUnseenCards() >= 1 else self.NumberUnseenCards() >= 2 return self.IsThreeOfaKind() or IsEnoughCardsLeft def IsPossible_FullHouse(self): if self.NumberUnseenCards() >= 3: return True elif self.NumberUnseenCards() == 2 and self.IsPair(): return True elif self.NumberUnseenCards() == 1 and self.IsTwoPair() or self.IsThreeOfaKind(): return True else: return False def IsPossible_FourOfaKind(self): if self.NumberUnseenCards() >= 3: return True elif self.NumberUnseenCards() == 2 and self.IsPair(): return True elif self.NumberUnseenCards() == 1 and self.IsThreeOfaKind(): return True elif self.IsFourOfaKind(): return True else: False def IsPossible_Straight(self): if self.IsPair() and self.NumberCards == 5: return False else: return True def IsPossible_Flush(self): return self.IsFlush() def IsPossible_StraightFlush(self): return True def getHandRank(self): if self.IsFlush(): return 'Flush' elif self.IsStraight(): return 'Straight' elif self.IsFullHouse(): return 'Full House' elif self.IsFourOfaKind(): return 'Four Of A Kind' elif self.IsThreeOfaKind(): return 'Three Of A Kind' elif self.IsTwoPair(): return 'Two Pair' elif self.IsPair(): return 'Pair' else: return 'You Suck'