def createFourCard20PointHand(self): hand = Hand(1) hand.addCard(Card(1, 1)) hand.addCard(Card(1, 2)) hand.addCard(Card(1, 3)) hand.addCard(Card(1, 4)) return hand
def __init__(self,name,tyyppi): self.__name=name self.__cottages=0 self.__points=0 self.__hand = Hand() self.__type = tyyppi self.__stack = Hand()
def test_find_straight(self): cards = '2_Sw, 3_Pa, 4_Pa, 5_Pa, 6_Pa, 5_Ja, 5_St' hand = Hand(cards_string=cards) combination = hand.find_lowest_combination(5, 'STRAIGHT') print(combination) self.assertIsNotNone(combination)
def testIsCalling(self): """test calling hands""" for idx, ruleset in enumerate(RULESETS): for content, completingTiles in [('s1s1s1s1 b5b6b7 RB8B8C2C2C6C7C8 mwe Lb5', ('b8c2', '')), ('s1s1s1s1 b5b6b7 RB7B8C2C2C6C7C8 mwe Lb5', ('b6b9', '')), ('RS2B2C2S4B4C4S6B6C6S7B7C7S8 mee LS8', ('', 'b8c8')), ('RS2B2C2S4B4C4S6B6C6B7C7S8C8 mee LC7', ('', 'b8s7')), ('RS2B2S3B3S4B4S5B5S6B6S7B7S9 Mwn LB7', ('s9', 'b9')), ('RDbDgDrWeWsWwWnWnB1B9C1S1S9 mwe LWn', ('c9', 'c9')), ('RDbDgDrWsWwWnWnB1B9C1S1S9C9 mwe LDg', ('we', 'we')), ('RC4C4C5C6C5C7C8 dgdgdg s6s6s6 mnn', ('c4c5', 'c4c5')), ('RS1S4C5C6C5C7C8 dgdgdg s6s6s6 mnn', ('', '')), ('RB1B2B3B4B5B5B6B6B7B7B8B8B8 mwe LB1', ('b1b3b4b6b7b9', '')), ('RDbDgDrWsWwWeWnB1B9C1S1S9C9 mwe LWe', ('b1b9c1c9dbdgdrs1s9wewnwsww', 'b1b9c1c9dbdgdrs1s9wewnwsww'))]: hand = Hand(ruleset, content) completedHands = hand.callingHands(99) testSays = ''.join(sorted(set(x.lastTile for x in completedHands))).lower() if idx >= len(completingTiles): idx %= len(RULESETS) / 2 completingTiles = completingTiles[idx] self.assert_(testSays == completingTiles, '%s: %s is completed by %s but test says %s' % ( ruleset.name, content, completingTiles, testSays)) for content in ['s1s1s1s1 b5b6b7 B1B8C2C2C6C7C8 mwe Lb5', 'Dg Dg Dr We Ws Ww Wn Wn B1B9C1S1S9 mwe LWe', 'Db Dg Dr We Ws Ww Wn B7 B1B9C1S1S9 mwe LWe']: hand = Hand(ruleset, content) self.assert_(not hand.callingHands(), content)
def _cards_changed(self): """Override superclass function and evaluate hand.""" Hand._cards_changed(self) if len(self._cards) == 5: self._evaluate()
def test_find_squarebomb(self): cards = 'Phoenix, 2_Pa, 3_Pa, 4_Pa, 5_Pa, 5_Sw, 5_Ja, 5_St' hand = Hand(cards_string=cards) combination = hand.find_lowest_combination(4, 'SQUAREBOMB') print(combination) self.assertIsNotNone(combination)
def startMatch(self,cards,withholecard=True): '''Deals initial cards to the dealer''' if withholecard: self._hand=Hand(cards[0]) self._holecard=cards[1] else: self._hand=Hand(cards)
def test_steps_with_phoenix_not_need(self): cards = '5_Sw, 5_Pa, 6_Sw, Phoenix, 7_Sw, 7_Pa, 8_Sw, 8_Pa' hand = Hand(cards_string=cards) combination = hand.find_lowest_combination(2, 'STEPS') print(combination) self.assertEqual(combination.type, 'STEPS')
def test_find_steps(self): cards = '2_Sw, 2_Pa, 3_Sw,3_Pa' hand = Hand(cards_string=cards) combination = hand.find_lowest_combination(2, 'STEPS') print(combination) self.assertEqual(combination.type, 'STEPS')
def test_find_long_steps_with_phoenix(self): cards = '5_Sw, 5_Pa, 6_Sw, 6_Pa, 7_Sw, Phoenix' hand = Hand(cards_string=cards) combination = hand.find_lowest_combination(2, 'STEPS', length=3) print(combination) self.assertEqual(combination.type, 'STEPS')
def test_find_trio(self): cards = 'Phoenix, 2_Pa, 3_Pa, 4_Pa, 5_Pa, 5_Sw, 5_Ja, 5_St' hand = Hand(cards_string=cards) combination = hand.find_lowest_combination(4, 'TRIO') print(combination) self.assertIsNotNone(combination)
def test_find_low_pair(self): cards = 'Phoenix, 2_Pa, 3_Pa, 4_Pa, 5_Pa, 5_Sw, 5_Ja, 5_St' hand = Hand(cards_string=cards) combination = hand.find_lowest_combination(1, 'PAIR') print(combination) self.assertFalse(combination.phoenix_flag)
def test_find_low_pair_with_phoenix(self): cards = 'Phoenix, 2_Pa, 3_Pa, 4_Pa, 5_Pa' hand = Hand(cards_string=cards) combination = hand.find_lowest_combination(1, 'PAIR') print(combination) self.assertTrue(combination.phoenix_flag)
class Player(): def __init__(self, name, bankroll): self.hand = Hand() self.bankroll = bankroll self.name = name self.bet = 0 def play_hand(self, dealer_card): while True: recommend = basic_strategy(self.hand.value(), dealer_card.value(), self.hand.is_soft()) if len(self.hand.cards) == 2: move = raw_input("%s: %s - hit/stand/double? (we recommend %s) " % (self.name, self.hand, recommend)).lower() else: # for simplicity. This is not true for soft 18. if recommend == 'double': recommend = 'hit' move = raw_input("%s: %s - hit/stand? (we recommend %s) " % (self.name, self.hand, recommend)).lower() if move.startswith('h'): return 'hit' elif move.startswith('s'): return 'stand' elif move.startswith('d'): return 'double' print "Invalid move" def __str__(self): return '(%s, $%s)' % (self.name, self.bankroll) def is_bust(self): return self.hand.value() > 21
def test_find_straight_with_phoenix(self): cards = '2_Sw, 3_Pa, Phoenix, 5_Pa, 6_Pa' hand = Hand(cards_string=cards) combination = hand.find_lowest_combination(5, 'STRAIGHT') print(combination) self.assertIsNotNone(combination)
def test_find_straight_with_card_discard(self): cards = ' 4_Sw, 6_Pa, 7_Sw, 8_Pa, 9_Sw, 10_Pa' hand = Hand(cards_string=cards) combination = hand.find_lowest_combination(3, 'STRAIGHT') print(combination) self.assertIsNotNone(combination)
def dealers_logic(self): print("-" * 40) print("Dealer showing both now: ", self.dealers_hand) if self.players_hand.value_the_cards() > 21: self.bet = -10 print("Dealer wins.") elif self.dealers_hand.value_the_cards() > self.players_hand.value_the_cards(): self.bet = -10 print("Dealer wins with {}.".format(self.dealers_hand.value_the_cards())) else: while self.dealers_hand.value_the_cards() < 17: Hand.draw_a_card(self.dealers_hand) print("Dealer takes a card: ", self.dealers_hand) if self.dealers_hand.value_the_cards() > 21: print("Dealer's hand busted at {}. Player wins.".format(self.dealers_hand.value_the_cards())) elif self.dealers_hand.value_the_cards() == self.players_hand.value_the_cards(): self.bet = -10 print("Dealer: {}. Player: {}. Dealer wins ties.".format(self.dealers_hand.value_the_cards(), self.players_hand.value_the_cards())) elif self.dealers_hand.value_the_cards() < self.players_hand.value_the_cards() < 22: print("Dealer's tally: {}. Player wins.".format(self.dealers_hand.value_the_cards())) else: self.bet = -10 print("Dealer wins with {}.".format(self.dealers_hand.value_the_cards())) return self.dealers_hand.value_the_cards()
def test_4CardHand(self): hand = Hand(0) hand.addCard(Card(1, 6)) hand.addCard(Card(1, 4)) hand.addCard(Card(1, 2)) hand.addCard(Card(1, 0)) dealer = DealerAgent() self.assertEqual(Actions.HIT, dealer.getNextAction(None, hand))
def test_find_steps_no_solution_with_pairs(self): cards = '6_Sw, 6_Pa' hand = Hand(cards_string=cards) combination = hand.find_lowest_combination(2, 'STEPS') print(combination) self.assertIsNone(combination)
def test_play_on_dragon(self): cards = 'Phoenix' hand = Hand(cards_string=cards) print('DRAGON') combination = hand.find_lowest_combination(Dragon().power, 'SINGLE') print('DRAGON', combination) self.assertIsNotNone(combination)
def opening(self): Hand.initial_deal(self.players_hand) Hand.initial_deal(self.dealers_hand) print("-" * 40) print("\nThe hand opens: \n") print("Dealer showing one: {}".format(self.dealers_hand.cards_in_hand[0])) print("Player showing: ", self.players_hand) print("Player's cards tally: ", self.players_hand.value_the_cards())
def test_less_than_5_cards_should_raise_exception(self): with self.assertRaises(Exception) as cm: Hand.from_string('4D 4D') self.assertEquals(cm.exception.message, '2 cards in the hand, must be 5') with self.assertRaises(Exception) as cm: Hand.from_string('4D 4D 4D 4D 4D 4D 4D 4D') self.assertEquals(cm.exception.message, '8 cards in the hand, must be 5')
def read_single_hand(self, file_in, active_player): """Reads the components of a PokerStars hand in a PoserStars text file and returns them in a Hand object. The current position of the file must me that the next file_in.readline() will return the first line of the hand to read. The active_player provided must be the one that the hole cards are shown in the file, or the function will return an error. Args: file_in (File) : The PokerStars hand text file we are working on, already opened by the master function. active_player (Player) : The active player in the file (the one we know the hole cards) Returns: (Hand) : A complete Hand object containing the information gathered. """ stack = -1 # Temporary variable used to get the active player chips from the txt file current_hand = Hand(0, 0, [Card(0, "c"), Card(0, "c")], 0) try: [ current_hand.handNumber, current_hand.tournamentNumber, current_hand.timeStarted, ] = self.read_hand_starting_line(file_in.readline()) # TODO: Change the function so it reads the number of seats at the table, and not always 9 seats while True: file_position = file_in.tell() stack = self.read_hand_seat_line(file_in.readline(), active_player) if stack == -1: # Done reading hand seat lines file_in.seek(file_position) break while True: loss = self.read_blind_line(file_in.readline(), active_player) if loss == None: break current_hand.loss += loss current_hand.hole_cards = self.read_hole_cards_line(file_in.readline(), active_player) while True: value = self.read_bet_line(file_in.readline(), active_player) if value == 0: break elif value == None: continue elif value < 0: current_hand.loss += -value else: current_hand.gain += value active_player.stack = stack return current_hand finally: a = 0
class NormalPlayer(Player): '''This class corresponds to normal players in the table''' def __init__(self, hand=None, money=0, name = "Stranger"): Player.__init__(self, hand, money, name) self._issplit=False def startMatch(self,cards): self._hand=Hand(cards) def hasEnoughToBet(self,bet=0): '''Check whether a player has enough to bet''' return self.money()>=bet def isSplit(self): '''Check whether the player has split.''' return self._issplit def extraChips(self,dollar): ''' extraChips(int) -> None -- Receive dollar worth of money''' assert(dollar >= 0) self._money += dollar def updateAfterDouble(self,card,bet=0): '''Updates player's instance after doubling and makes sure player has enough''' try: if self.hasEnoughToBet(int(bet)): self._money-=bet self._hand.receive(card) else: print("Not enough money to double") except ValueError: print ("Bet is not an integer") def updateAfterSplit(self,bet=0): '''Updates player after he split his pair. Creates an alternative hand''' try: if self.hasEnoughToBet(int(bet)): self._money-=bet self._secondhand = self._hand.split() self._issplit=True else: print("Not enough money to double") except ValueError: print ("Bet is not an integer") def updateAfterSecondHit(self): pass def updateAfterBet(self,bet=0): '''Updates player's money after betting and makes sure player has enough''' try: if self.hasEnoughToBet(int(bet)): self.money-=bet else: print("Not enough money to bet") except ValueError: print ("Bet is not an integer")
def initHand(self): """directly before starting""" Hand.clearCache(self) self.dangerousTiles = list() self.discardedTiles.clear() assert self.visibleTiles.count() == 0 if Internal.field: Internal.field.prepareHand() self.__setHandSeed()
def test_find_long_steps(self): cards = '5_Sw, 5_Pa, 6_Sw,6_Pa, 7_Sw, 7_Pa' hand = Hand(cards_string=cards) straight = hand.find_straight(hand, 2, 3) print(straight) combination = hand.find_lowest_combination(2, 'STEPS', 3) print(combination) self.assertEqual(combination.type, 'STEPS')
def test_when_hands_are_equals_numbers_should_tie(self): hand1 = Hand.from_string('4D 4D 4C 5D 5D') hand2 = Hand.from_string('4D 4D 4C 5D 5D') self.assertTrue(hand1 == hand2) hand1 = Hand.from_string('TD TD TC TC KS') hand2 = Hand.from_string('TS TS TH TH KS') self.assertTrue(hand1 == hand2)
def getReward(self, state, action, transitionState): isDone, isFirst, isDoubleDown, hasAce, hardCount, dealerSoftCount = transitionState multiplier = 2 if isDoubleDown else 1 if hardCount > 21: return -2 * multiplier softCount = hardCount + 10 if hasAce and hardCount <= 11 else hardCount if isDone: if isFirst and softCount == 21: return multiplier # Simulate the dealer's actions dealerAgent = DealerAgent() dealerCardValue = dealerSoftCount - 1 if dealerSoftCount != 11 else 0 card = Card(0, dealerCardValue) dealerHand = Hand(1) dealerHand.addCard(card) deck = Deck(1, 4, 13) dealerHand.addCard(deck.take()) while dealerAgent.getNextAction(None, dealerHand) == Actions.HIT: dealerHand.addCard(deck.take()) return ( multiplier if softCount > dealerHand.getSoftCount() else (0 if softCount == dealerHand.getSoftCount() else -multiplier) ) else: return 0
def test_find_straight_going_up(self): cards = ' 4_Sw, Phoenix, 5_Pa, 6_Pa, 7_Sw, 8_Pa' hand = Hand(cards_string=cards) combination = hand.find_lowest_combination(5, 'STRAIGHT') print(combination) self.assertIsNotNone(combination) combination = hand.find_lowest_combination(5, 'STRAIGHT', length=6) print(combination) self.assertIsNotNone(combination)
def test_hit(self): hand = Hand(1) hand.addCard(Card(0, 1)) hand.addCard(Card(1, 1)) deck = HandTest.FakeDeck() self.assertTrue(hand.canHit()) hand.hit(deck) self.assertTrue(hand.canHit()) hand.hit(deck)
PYPATH = os.path.join(ROOT, 'python') sys.path.append(ROOT) sys.path.append(PYPATH) sys.path.insert(0, 'python') print(sys.path) import cv2 import model import util from hand import Hand from body import Body import matplotlib.pyplot as plt import copy import numpy as np body_estimation = Body(os.path.join(ROOT, 'model/body_pose_model.pth')) hand_estimation = Hand(os.path.join(ROOT, 'model/hand_pose_model.pth')) cap = cv2.VideoCapture(0) cap.set(3, 640) cap.set(4, 480) while True: ret, oriImg = cap.read() candidate, subset = body_estimation(oriImg) canvas = copy.deepcopy(oriImg) canvas = util.draw_bodypose(canvas, candidate, subset) cv2.imshow('demo', canvas) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release()
def __init__(self, hand=None): '''Optional hand parameter gives a player hole cards.''' self.hand = Hand(hand) self.money = 100 return
class RockPaperScissorsGame(QWidget): def __init__(self): super().__init__() # Display Layout displayLayout = QGridLayout() self.pcName = QLabel('PC') self.fontSize(self.pcName, 7) self.pcName.setAlignment(Qt.AlignCenter) displayLayout.addWidget(self.pcName, 0, 0, 1, 2) self.userName = QLabel('YOU') self.fontSize(self.userName, 7) self.userName.setAlignment(Qt.AlignCenter) displayLayout.addWidget(self.userName, 0, 3, 1, 2) self.displayPc = QLabel() self.displayPc.setFixedSize(300, 300) self.displayPc.setAlignment(Qt.AlignCenter) displayLayout.addWidget(self.displayPc, 1, 0, 1, 2) self.vsIcon = QLabel('VS') self.fontSize(self.vsIcon, 6) displayLayout.addWidget(self.vsIcon, 1, 2) self.displayUser = QLabel() self.displayUser.setFixedSize(300, 300) self.displayUser.setAlignment(Qt.AlignCenter) displayLayout.addWidget(self.displayUser, 1, 3, 1, 2) # Button Layout buttonLayout = QGridLayout() self.rockButton = QPushButton() self.rockButton.setIconSize(QSize(100, 100)) self.rockButton.setIcon(QIcon(QPixmap('image/rock.png'))) self.rockButton.clicked.connect(lambda: self.buttonClicked('rock')) buttonLayout.addWidget(self.rockButton, 0, 0) self.paperButton = QPushButton() self.paperButton.setIconSize(QSize(100, 100)) self.paperButton.setIcon(QIcon(QPixmap('image/paper.png'))) self.paperButton.clicked.connect(lambda: self.buttonClicked('paper')) buttonLayout.addWidget(self.paperButton, 0, 1) self.scissorsButton = QPushButton() self.scissorsButton.setIconSize(QSize(100, 100)) self.scissorsButton.setIcon(QIcon(QPixmap('image/scissors.png'))) self.scissorsButton.clicked.connect(lambda: self.buttonClicked('scissors')) buttonLayout.addWidget(self.scissorsButton, 0, 2) # Status Layout statusLayout = QGridLayout() self.matchLine = QLineEdit() self.matchLine.setReadOnly(True) self.matchLine.setFixedHeight(30) statusLayout.addWidget(QLabel('Match: '), 0, 0) statusLayout.addWidget(self.matchLine, 0, 1) self.displayTimer = QLineEdit() self.displayTimer.setReadOnly(True) self.displayTimer.setFixedHeight(30) statusLayout.addWidget(QLabel('Time: '), 1, 0) statusLayout.addWidget(self.displayTimer, 1, 1) self.scoreLine = QLineEdit() self.scoreLine.setReadOnly(True) self.scoreLine.setFixedHeight(30) self.scoreLine.setAlignment(Qt.AlignCenter) statusLayout.addWidget(QLabel('Score: '), 2, 0) statusLayout.addWidget(self.scoreLine, 2, 1) self.messageLine = QLineEdit() self.messageLine.setReadOnly(True) self.messageLine.setFixedHeight(40) self.fontSize(self.messageLine, 8) self.messageLine.setAlignment(Qt.AlignCenter) statusLayout.addWidget(self.messageLine, 3, 0, 1, 2) self.bestOfMatchs = {'Best Of 3 Match' : 2, 'Best Of 5 Match' : 3, 'Best Of 7 Match' : 4} self.bestOfMatch = QComboBox() self.bestOfMatch.addItems(self.bestOfMatchs) statusLayout.addWidget(self.bestOfMatch, 5, 0, 1, 2) self.newGameButton = QPushButton() self.newGameButton.setText('New Game') self.newGameButton.clicked.connect(self.newGame) self.newGameButton.setFixedSize(220, 50) statusLayout.addWidget(self.newGameButton, 6, 0, 1, 2) # Main Layout mainLayout = QGridLayout() mainLayout.addLayout(displayLayout, 0, 0) mainLayout.addLayout(buttonLayout, 1, 0) mainLayout.addLayout(statusLayout, 0, 1, 2, 1) mainLayout.setSizeConstraint(QLayout.SetFixedSize) self.setLayout(mainLayout) self.setWindowTitle('Rock Paper Scissors!') self.startGame() def startGame(self): self.messageLine.setText('R.P.S!') self.rockButton.setDisabled(True) self.paperButton.setDisabled(True) self.scissorsButton.setDisabled(True) def newGame(self): self.hand = Hand() self.score = Score() self.result = Result() self.targetScore = self.bestOfMatchs[self.bestOfMatch.currentText()] self.currentUserHand = '' self.match = 1 self.displayPc.clear() self.displayUser.clear() self.messageLine.clear() self.scoreLine.setText(str(self.score.pcScore) + ' : ' + str(self.score.userScore)) self.rockButton.setDisabled(False) self.paperButton.setDisabled(False) self.scissorsButton.setDisabled(False) self.loop() def loop(self): self.matchLine.setText('No.' + str(self.match)) self.timeRemaning = 5 self.repeater = QTimer() self.repeater.setInterval(1000) self.repeater.timeout.connect(self.timer) self.repeater.start() def timer(self): if self.timeRemaning == 0: self.repeater.stop() return self.main() else: self.displayTimer.setText(str(self.timeRemaning)) self.timeRemaning -= 1 def main(self): self.displayTimer.clear() currentPcHand = self.hand.randomPcHand() if self.currentUserHand == '': self.message = 'Choose your hand!' else: self.message = self.result.result(currentPcHand, self.currentUserHand) if self.message == 'WIN': self.score.increaseUserScore() elif self.message == 'LOSE': self.score.increasePcScore() self.displayPc.setPixmap(self.hand.getPcHand(currentPcHand)) self.match += 1 self.scoreLine.setText(str(self.score.pcScore) + ' : ' + str(self.score.userScore)) self.messageLine.setText(self.message) self.currentUserHand = '' return self.gameEnd() if self.score.pcScore == self.targetScore or self.score.userScore == self.targetScore else self.delay() def buttonClicked(self, hand): self.currentUserHand = hand self.displayUser.setPixmap(self.hand.getUserHand(hand)) def delay(self): delayTime = QTimer() delayTime.singleShot(1500, self.nextMatch) def nextMatch(self): self.displayPc.clear() self.displayUser.clear() self.messageLine.clear() return self.loop() def gameEnd(self): self.rockButton.setDisabled(True) self.paperButton.setDisabled(True) self.scissorsButton.setDisabled(True) return self.messageLine.setText('YOU WIN!') if self.score.userScore > self.score.pcScore else self.messageLine.setText('YOU LOSE') def fontSize(self, text, size): font = text.font() font.setPointSize(font.pointSize() + size) text.setFont(font)
import numpy as np from hand import Hand iterations = 250000 starting_size = 8 #inclusive mullto = 7 #inclusive hand = Hand("decklists/affinity.txt") hand_types = ["t1 2-drop", "t1 3-drop"] hand_counts = np.zeros(((starting_size + 1) - mullto, len(hand_types))) totals = np.zeros(((starting_size + 1) - mullto, 1)) zero_creatures = ["Memnite", "Ornithopter"] zero_others = "Welding Jar" ones = ["Signal Pest", "Vault Skirge"] twos = ["Arcbound Ravager", "Cranial Plating", "Steel Overseer"] threes = ["Etched Champion", "Master of Etherium"] lands = [ "Darksteel Citadel", "Spire of Industry", "Glimmervoid", "Inkmoth Nexus", "Blinkmoth Nexus", "Island" ] for i in range(iterations): for j in range(0, (starting_size + 1) - mullto): hand.new_hand(starting_size - j) count_opal = hand.count_of("Mox Opal") count_lands = hand.count_of(lands) has_drum = hand.contains("Springleaf Drum") count_zero_creatures = hand.count_of(zero_creatures) count_zeros = count_zero_creatures + hand.count_of( zero_others) + hand.contains("Darksteel Citadel")
class Game: # poker game __POINTS = { '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 'J': 11, 'Q': 12, 'K': 13, 'A': 14 } __RANKING = { 'straightflush': 9, 'quads': 8, 'fullhouse': 7, 'flush': 6, 'straight': 5, 'trips': 4, 'twopair': 3, 'pair': 2, 'highcard': 1 } def __init__(self, playerlimit=8, blindinterval=600): self.ID = None self.__deck = Deck() self.__players = [] self.__hands = [] self.__inprogress = False self.__playerlimit = playerlimit - 1 self.__blindtimer = BlindTimer(blindinterval) self.__hand = None self.__blinds = (0, 0) self.__rules = Rules() self.__allowedactions = () self.__rotate = False def __rotatedealer(self): big_blind_only = False if self.__players[0].isbigblind(): # big blind must now be small blind if self.__players[0].getchips() <= 0: big_blind_only = True else: if self.__players[1].getchips() <= 0: big_blind_only = True player = self.__players.pop(0) self.__players.append(player) return big_blind_only def addplayer(self, player): # limit to 8 players if self.__inprogress == True: raise GameException('Cannot add players, game in progress') if len(self.__players) > self.__playerlimit: raise GameException('Cannot add players, game is full') for p in self.__players: if p.name() == player.name(): raise GameException( 'Cannot add player, already a player with that name') if p.getid() == player.getid(): raise GameException( 'Cannot add player, you are already registered') self.__players.append(player) def players(self): return self.__players def player(self, name): player = None for p in self.__players: if p.name() == name: player = p break return player def newhand(self): if self.__rotate: big_blind_only = self.__rotatedealer() else: self.__rotate = True big_blind_only = False # remove players from the game when they are out for i, player in enumerate(self.__players): if player.getchips() <= 0: del (self.__players[i]) # reset remaining players, shuffle deck, check blinds and start a new hand for player in self.__players: player.reset() self.__deck.reset() self.__deck.shuffle() self.__inprogress = True self.__blinds = self.__blindtimer.getblinds() self.__hand = Hand(self.__deck, self.__players, self.__blindtimer, self.__rules, big_blind_only) self.__allowedactions = () return self.__hand def gethand(self): return self.__hand def getblinds(self): return self.__blinds def getbigblind(self): return self.__blinds[1] def getsmallblind(self): return self.__blinds[0] def getcurrentbet(self): return self.__hand.currentbet() def numberofplayers(self): return len(self.__players) def summarise(self): summary = { 'in_progress': self.__inprogress, 'big_blind': self.getbigblind(), 'small_blind': self.getsmallblind(), 'blind_remaining': int(round(self.__blindtimer.gettimeremaining(), 0)) } summary['players'] = [{ 'name': player.name() } for player in self.__players if player.getchips() > 0] if len(summary['players']) == 1: summary['winner'] = summary['players'][0]['name'] if self.__hand: summary['current_hand'] = {'round': self.__hand.getstatetext()} summary['current_hand']['current_player'] = {} (cp, options) = self.__hand.nexttobet() if cp: fp = self.__hand.getfirsttoact() if fp: summary['current_hand']['first_player'] = fp.name() else: summary['current_hand']['first_player'] = '' lp = self.__hand.getlasttoact() if lp: summary['current_hand']['last_player'] = lp.name() else: summary['current_hand']['last_player'] = '' summary['current_hand']['current_player']['name'] = cp.name() summary['current_hand']['current_player']['options'] = options summary['current_hand']['done'] = "N" else: summary['current_hand']['done'] = 'Y' if self.__hand.getwinners(): summary['current_hand']['winninghands'] = [] for winner in self.__hand.getwinners(): summary['current_hand']['winninghands'].append({ winner.name(): Rules.RANKING_TEXT[winner.getplayerhand().getranking()] }) summary['current_hand']['payout'] = [] for pot in self.__hand.getpots(): summary['current_hand']['payout'].append(pot.getpayouts()) if self.__hand.playersinhand( ) > 1: # don't show hands if everyone has folded! summary['current_hand']['showdown'] = [] for player in self.__hand.getplayers(): if player.isactive() == False: continue playerhand = player.getplayerhand() hand = [] for card in playerhand.gethand(): hand.append(card.asdict()) summary['current_hand']['showdown'].append( {player.name(): hand}) return summary
class HumanPlayer(Player): coins = 0 actions = [] states = [] fg_values_matrix = {} temp_state_action = [] def __init__(self, game, coins): self.game = game self.hand = Hand() self.coins = coins #the actions are continue or stand. Split and bet more coins will be developed later self.actions = ['continue', 'stand', 'double bet', 'split'] """ The human player can take decisions only between 1 and 20. The '1' case is the lowest initial hand that the human can receive (two Aces, and make split). And the '20' case is the highest value that human can obtain without winning or loosing that round. """ for i in range(1, 21): #The lowest value card that the dealer can receive is 1 (an Ace) and the highest is 11 (Soft Ace) #In this initial implementation the Ace will have one unique value: 1. Later it can be 1 or 11. (in progress) for j in range(1, 12): player_status = str(i) + 's' self.states.append((player_status, j)) player_status = str(i) + 'h' self.states.append((player_status, j)) #Initialize fg_values_matrix with 0.0 probability each one. I use a dictionary to do this. # The key is: (the state,action). And the value will be the fg_value for x in range(0, len(self.states)): for y in range(0, len(self.actions)): current_state = self.states[x] current_action = self.actions[y] self.fg_values_matrix[current_state, current_action] = 0.0 #Initialize the Ace possible values. It can be 1 or 11 #The initial value is 0.5 for both Ace possibility def bet(self, training_flag): #This must get the player's bet from the command line #Returns the bet if not training_flag: self.coins -= 1 return 1 #The automated player only bets 1 coin def double_bet(self): self.game.current_player_bet *= 2 def calculate_value(self): return self.hand.calculate_value() def get_prize(self, prize): #This gives the player the prize if won a hand self.coins += prize def print_victories(self): print 'Player won ' + str(self.victories) + ' times' def has_two_equal_ranked_cards(self): return self.hand.has_two_equal_ranked_cards() def have_an_ace(self): return self.hand.have_an_ace() def have_more_than_1_ace(self): return self.hand.have_more_than_1_ace() #Obviously, this method MUST be refactored. def take_decision(self, dealer_original_value, training_flag): #If I'm training, my decisions are random if training_flag: random_number = randint(0, 9) # double bet, only at the first decision if random_number < 2 and len(self.hand.cards) == 2: if (self.calculate_value() <= 20): self.temp_state_action.append( ((self.hand.calculate_status(), dealer_original_value), 'double bet')) self.double_bet() return 'double bet' elif random_number >= 5 and self.can_split(): if (self.calculate_value() <= 20): self.temp_state_action.append( ((self.hand.calculate_status(), dealer_original_value), 'split')) return 'split' else: # continue if 0 <= random_number < 5: if (self.calculate_value() <= 20): self.temp_state_action.append( ((self.hand.calculate_status(), dealer_original_value), 'continue')) return 'continue' # stand else: if self.calculate_value() <= 20: self.temp_state_action.append( ((self.hand.calculate_status(), dealer_original_value), 'stand')) return 'stand' # when it is not training elif self.calculate_value() <= 20: # compare the values, if stand_value is higher than continue_value, the next action will be stand values = {} stand_value = self.fg_values_matrix[(self.hand.calculate_status(), dealer_original_value), 'stand'] values[stand_value] = 'stand' continue_value = self.fg_values_matrix[( self.hand.calculate_status(), dealer_original_value), 'continue'] values[continue_value] = 'continue' double_bet_value = self.fg_values_matrix[( self.hand.calculate_status(), dealer_original_value), 'double bet'] values[double_bet_value] = 'double bet' if (self.can_split()): split_value = self.fg_values_matrix[( self.hand.calculate_status(), dealer_original_value), 'split'] values[split_value] = 'split' max = self.calculate_maximum_from_vector(values) return values[max] #Typically, this last return line will only be reached #if you are over 20, so you insta-win or insta-lose return 'stand' # Returns true if the player chooses to stand # Returns false if the player chooses to get another card def make_move(self, dealer_original_value, training_flag): decision = '' while not (decision == 'stand'): decision = self.take_decision(dealer_original_value, training_flag) if (decision == 'continue'): print 'Action: Asks for a card' new_card = self.game.get_deck().give_a_card() self.get_card(new_card) print str(new_card.rank) + ' of ' + str(new_card.suit) elif (decision == 'stand'): print 'Action: Stand' elif (decision == 'split'): #You go back to the BlackjackGame and the split-hand begins return 'split' elif (decision == 'double bet'): print 'Player doubles the bet\n' print 'Action: Asks for a card' new_card = self.game.get_deck().give_a_card() self.get_card(new_card) print str(new_card.rank) + ' of ' + str(new_card.suit) if (self.calculate_value() <= 20): self.temp_state_action.append( ((self.hand.calculate_status(), dealer_original_value), 'stand')) #This means, if you double-betted, then you MUST ask stand after getting one more card! decision = 'stand' return '' #the fg_values that are updated, are those that take you to directly win or lose. The previous values do not get updated def update_fg_values(self, result): alpha = 0.8 # it can be modified gamma = 0.5 # it can be modified, but between 0 and 1 reward = 0.0 if result == 'win': reward = 0.2 * self.game.current_player_bet elif result == 'lose': reward = -0.2 * self.game.current_player_bet terminal_s_a = self.temp_state_action[len(self.temp_state_action) - 1] q_s_a = self.fg_values_matrix[self.temp_state_action[ len(self.temp_state_action) - 1]] # max Q(s', a') is 0, because is a terminal state self.fg_values_matrix[terminal_s_a] = (1 - alpha) * q_s_a + alpha * ( reward + gamma * 0) # if is not a terminal state-action, the reward is 0 reward = 0.0 if (len(self.temp_state_action) - 2) >= 0: for x in range((len(self.temp_state_action) - 2), -1, -1): s_a = self.temp_state_action[x] s_a_prime = self.temp_state_action[x + 1] q_s_a_x = self.fg_values_matrix[s_a] # CALCULATE THE MAX Q(s',a') q_stand_value_prime = self.fg_values_matrix[s_a_prime] q_continue_value_prime = self.fg_values_matrix[s_a_prime] q_double_bet_value_prime = self.fg_values_matrix[s_a_prime] q_values_prime = [ q_stand_value_prime, q_continue_value_prime, q_double_bet_value_prime ] self.fg_values_matrix[s_a] = (1 - alpha) * q_s_a_x + alpha * ( reward + gamma * max(q_values_prime)) def restart_temp_state_action(self): self.temp_state_action = [] def can_split(self): if len(self.hand.cards) > 1: #You can only split if you have two and only two cards valued the same if (self.has_two_equal_ranked_cards() and len(self.hand.cards) == 2): return True else: return False def print_hand(self): print str(self.hand.cards[0].rank) + ' of ' + str( self.hand.cards[0].suit) print str(self.hand.cards[1].rank) + ' of ' + str( self.hand.cards[1].suit) + '\n' def calculate_maximum_from_vector(self, vector): max = -9999999 for key in vector: if key > max: max = key return max
class Game: def __init__(self): # Set up a clock for managing the frame rate. self.clock = pygame.time.Clock() self.deck = Deck() self.playerHand = Hand() self.robotHand = Hand() self.deck.deal([self.playerHand, self.robotHand]) # How many cards in our line self.cardsLength = 10 # Called to save the state of the game to the Journal. def write_file(self, file_path): pass # Called to load the state of the game from the Journal. def read_file(self, file_path): pass # The main game loop. def run(self): self.running = True screen = pygame.display.get_surface() width = screen.get_width() height = screen.get_height() screen.fill(Colors["LIGHT_GREY"]) pygame.display.update() drawn = self.deck.draw() # msg = "You drew " + str(drawn) + " from the deck." msg = _("You drew %i from the deck.") % drawn waitingForClick = True robotTurn = False timeStartedRobotTurn = None waitingForDiscardChoice = False playerDrew = False robotChoseDiscard = False while self.running: width, height = pygame.display.get_surface().get_size() mousePos = pygame.mouse.get_pos() if len(self.deck.deck) <= 2: msg = _("You have %i points, robot has %i points") % ( self.playerHand.countPoints(), self.robotHand.countPoints()) waitingForClick = False waitingForDiscardChoice = False playerDrew = False robotChoseDiscard = False dirty = [] for i in range(self.cardsLength): test = Card(Colors["DARK_GREY"], width // self.cardsLength // 2, (height // 100) + (height // self.cardsLength) * i, int((height // self.cardsLength) * 0.9), str(self.playerHand.hand[i])) test.draw(screen) dirty.append(test.getRect()) if robotTurn: if (pygame.time.get_ticks() - timeStartedRobotTurn < 1500): msg = _("It\'s the robot\'s turn.") elif (pygame.time.get_ticks() - timeStartedRobotTurn < 3000): print("running") if not robotChoseDiscard: old_card = self.robotHand.place(drawn) if old_card == drawn and not self.deck.empty(): msg = _("The robot draws a card.") drawn = self.deck.draw() drawn = self.robotHand.place(drawn) else: msg = _("The robot picked up %i from the pile." ) % drawn drawn = old_card robotChoseDiscard = True elif (pygame.time.get_ticks() - timeStartedRobotTurn < 4500): msg = "The robot discards %i" % drawn else: if self.deck.empty(): pass elif not playerDrew: msg = "You drew %i from discard pile. Use?" % drawn playerDrew = True robotTurn = False waitingForDiscardChoice = True font = pygame.font.SysFont('arial', width // 20) text = font.render(msg, 1, (0, 0, 0)) textX = (width // self.cardsLength // 2) + width // 10 textY = height // 10 bottomRightX = textX + text.get_rect()[2] bottomRightY = textY + text.get_rect()[3] pygame.draw.rect(screen, Colors["LIGHT_GREY"], (textX, textY, width, bottomRightY)) screen.blit(text, ((textX, textY))) dirty.append((textX, textY, width, bottomRightY)) yesButton = None noButton = None if waitingForDiscardChoice: yesButton = Card(Colors["GREEN"], textX, bottomRightY + textY, width // 8, _("Yes")) yesButton.draw(screen) noButton = Card(Colors["RED"], textX + abs(bottomRightX - textX) // 4 * 2, bottomRightY + textY, width // 8, _("No")) noButton.draw(screen) dirty.append(yesButton.getRect()) dirty.append(noButton.getRect()) # Pump GTK messages. while Gtk.events_pending(): Gtk.main_iteration() if not self.running: break # Pump PyGame messages. for event in pygame.event.get(): if event.type == pygame.QUIT: return elif event.type == pygame.VIDEORESIZE: screen.fill(Colors["LIGHT_GREY"]) pygame.display.update() elif event.type == pygame.MOUSEBUTTONDOWN: for i in range(self.cardsLength): card = Card(Colors["DARK_GREY"], width // self.cardsLength // 2, (height // 100) + (height // self.cardsLength) * i, int((height // self.cardsLength) * 0.9), str(self.playerHand.hand[i])) if (card.isOver(mousePos)): if (waitingForClick): print("clicked on card " + str(i)) self.playerHand.hand[ i], drawn = drawn, self.playerHand.hand[i] robotTurn = True robotChoseDiscard = False playerDrew = False waitingForClick = False timeStartedRobotTurn = pygame.time.get_ticks() if (waitingForDiscardChoice): print("mouse down while waiting for discard choice") if (yesButton.isOver(mousePos)): waitingForDiscardChoice = False waitingForClick = True pygame.draw.rect(screen, Colors["LIGHT_GREY"], yesButton.getRect()) pygame.draw.rect(screen, Colors["LIGHT_GREY"], noButton.getRect()) msg = _("Pick card to replace.") elif noButton.isOver(mousePos): print("clicked no button") waitingForClick = True waitingForDiscardChoice = False drawn = self.deck.draw() msg = _("You drew %i from the deck.") % drawn pygame.draw.rect(screen, Colors["LIGHT_GREY"], yesButton.getRect()) pygame.draw.rect(screen, Colors["LIGHT_GREY"], noButton.getRect()) # Try to stay at 30 FPS self.clock.tick(30) pygame.display.update(dirty) pygame.event.clear() ee = pygame.event.Event(24) try_post = 1 # the pygame.event.post raises an exception if the event # queue is full. so wait a little bit, and try again. while try_post: try: pygame.event.post(ee) try_post = 0 except: pygame.time.wait(1) try_post = 1
def main(): # start video stream vid = cv2.VideoCapture(0) hands = [Hand(), Hand()] game = Pong() SCALE = GAME_HEIGHT / (MAX_REACH - MIN_REACH) # variables used to figure out the static background for background subtraction aggregation_counter = 0 background = np.zeros((CAMERA_HEIGHT, CAMERA_WIDTH)) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() ret, frame = vid.read() grey_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # aggregate background for some frames if aggregation_counter < CALIBRATION_LIMIT: background += grey_frame aggregation_counter += 1 elif aggregation_counter == CALIBRATION_LIMIT: background = np.divide(background, CALIBRATION_LIMIT) aggregation_counter += 1 print("Calibrated") else: # compute the absolute difference between our static background frame and our current frame delta_frame = cv2.absdiff(background.astype("uint8"), grey_frame) ret, df = cv2.threshold(delta_frame, 105, 255, cv2.THRESH_BINARY) # median blur for smoothness smooth_mask = cv2.medianBlur(df, 5) frame_partitions = np.hsplit(smooth_mask, 2) # split into 2 contour_info = [] for index, partition in enumerate(frame_partitions): # finding contours for each player contours, hierarchy = cv2.findContours(partition, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) area = 0 max_con = None for contour in contours: if cv2.contourArea(contour) > area: max_con = contour area = cv2.contourArea(contour) # find the convex hull of the largest contour if max_con is not None: hull = cv2.convexHull(max_con) # fetch new position and draw line in frame new_pos = compute_center(hull) #transform the second parition for drawing purposes if index == 1: new_pos[0] += int(CAMERA_WIDTH / 2) new_pos[1] = math.floor((new_pos[1] - MIN_REACH) * SCALE) game.paddles[index].set_position(new_pos) contour_info.append({ "previous": tuple(hands[index].center_pos), "new": tuple(new_pos), "max": max_con, "hull": hull }) hands[index].set_hull(hull) hands[index].set_frame(partition) hands[index].set_center(new_pos) for info in contour_info: cv2.line(frame, info["previous"], info["new"], (0, 255, 0), 5) cv2.drawContours(frame, info["max"], 0, color=(0, 0, 255)) cv2.drawContours(frame, info["hull"], 0, color=(255, 0, 0)) cv2.line(frame, (320, 0), (320, 480), (0, 155, 155)) cv2.imshow("Regular Frame", frame) game.update() if cv2.waitKey(1) == ord("r"): break vid.release() vid.destroyAllWindows()
def pegging(self): # Copy the pegging hands so we can discard cards from them without affecting the actual hands before the count pegging_hands = [copy.copy(player.hand) for player in self.players] player_up = self.pone # Set variables so the UI will start rendering the pegging interface self.pegging_count = 0 # List of lists of cards, can't use the Hand class because it sorts the cards in its __str__(), but we want to track sequential order self.pegging_cards = [[]] # Track whether either player has said 'go' so far this round go = [False, False] # Update the rounds counter and add another list for the pegging UI rounds_played = 0 # Keep pegging as long as at least 1 player has cards while any([len(hand.cards) > 0 for hand in pegging_hands]): # Make sure the current player hasn't said go already and that they have cards if not go[player_up] and len(pegging_hands[player_up].cards) > 0: # Get pegging input from either a human or AI player # Passing it the set_message callback, available cards, the pegging count, the 'go' status of the opponent, and cards played so far peg_input = self.players[player_up].get_peg_play( self.set_message, pegging_hands[player_up], self.pegging_count, go[1 - player_up], self.pegging_cards) print(peg_input) # If the player has said go, skip their turn else: go[player_up] = True player_up = 1 - player_up continue # Player objects will return -1 for a go if peg_input == -1: already_said = go[player_up] go[player_up] = True # If both players have said go, then the last one to say it scores a point if all(go): self.players[player_up].add_points(1) self.set_message('Player ' + str(player_up + 1) + ' scores 1 point for a go.') elif not already_said: self.set_message('Player ' + str(player_up + 1) + ' says \'go\'!') # If it's not a go, it's the numerical rank of the card to play. Suit doesn't matter for this phase else: # Remove the played card from the temporary pegging hand and append it to the played pegging cards list peg_card = pegging_hands[player_up].discard(peg_input) self.pegging_cards[rounds_played].append(peg_card) self.set_message('Player ' + str(player_up + 1) + ' plays ' + str(peg_card)) # Update the pegging count self.pegging_count += peg_card.value # Check for scores scores = [] score = 0 # Check for a run if len(self.pegging_cards[rounds_played]) >= 3: # Count the last N cards for an N card run, but don't allow card 0 along with cards 2 and 3 to make a run for i in range(len(self.pegging_cards[rounds_played]), 2, -1): candidate_run = Hand(self.pegging_cards[rounds_played] [-i:]).count_runs() # Check if a run was found and that its score matches what we're looking for if len(candidate_run ) > 0 and candidate_run[0].points == i: scores.append('Player ' + str(player_up + 1) + ' scores ' + str(i) + ' points for a ' + str(i) + '-card run' + '!' * (i - 2)) score += i # If one was, break, since we only want one break # Check for 2, 3, or 4 of a kind if len(self.pegging_cards[rounds_played]) >= 2: # Start with the largest possible pair and work down. Don't allow duplicates, so break if we find something for i in range( min(len(self.pegging_cards[rounds_played]), 4), 1, -1): candidate_pair = Hand(self.pegging_cards[rounds_played] [-i:]).count_pairs(i) if len(candidate_pair) > 0: pair = candidate_pair[0] msg = 'Player ' + \ str(player_up + 1) + ' scores ' + \ str(pair.points) + \ ' points for a ' if i == 2: msg += 'pair.' elif i == 3: msg += 'pair royal!!!' elif i == 4: msg += 'pair double royal!!!!!!' scores.append(msg) score += pair.points break # A count equal to 15 is worth 2 points if self.pegging_count == 15: score += 2 scores.append('Player ' + str(player_up + 1) + ' scores 2 points for 15.') # 31 scores 2 points and starts a new round without a go if self.pegging_count == 31: score += 2 scores.append('Player ' + str(player_up + 1) + ' scores 2 points for 31.') # Last card scores 1 point if it's not 31 elif not any([len(hand.cards) > 0 for hand in pegging_hands]): score += 1 scores.append('Player ' + str(player_up + 1) + ' scores 1 point for last card.') # If the player played their last card and the opponent will have to say go, give them a go elif len(pegging_hands[player_up].cards) == 0 and \ not any([card.value + self.pegging_count <= 31 for card in pegging_hands[1 - player_up].cards]): score += 1 scores.append('Player ' + str(player_up + 1) + ' scores 1 point for a go.') go = [True, True] # Print scores for the play and add points if there were any if len(scores) > 0: self.players[player_up].add_points(score) self.set_message(*scores, append_msg=True) self.set_message('Press enter to continue.', append_msg=True) input() # Reset for the next round if both players either have an empty hand or have said go, or if the count is 31 if all([ len(hand.cards) == 0 or go[i] for i, hand in enumerate(pegging_hands) ]) or self.pegging_count == 31: self.pegging_cards.append([]) self.pegging_count = 0 rounds_played += 1 # If a player has no cards, make sure their go status is True, otherwise reset go = [len(hand.cards) == 0 for hand in pegging_hands] # Next player is up player_up = 1 - player_up # Reset the pegging count UI state self.pegging_count = -1 self.pegging_cards = []
def split_hand(self, hand: Hand) -> Hand: second_hand = Hand(self.get_money(hand.bet)) second_hand.add_card(hand.cards.pop()) self.hands.append(second_hand) return second_hand
print("This BlackJack Game has been created by David Garcia Morillo") # Initialize `DECK` and `DEALER_HAND` while True: try: n_of_decks = int( input("How many decks do you want to use (4-8)\n> ")) except ValueError: print("Please, use only numbers.\n") else: if not 3 < n_of_decks <= 8: print("The number of decks must be between 4 and 8\n") else: break DECK = Deck(n_of_decks) DEALER_HAND = Hand(DECK) start_game() while True: print("###### Game Started ######\n") print(f"The first card of the dealer is {DEALER_HAND.cards[0]}") for player in PLAYERS: player_turn(player) dealer_turn() end_game() if not next_game(): break
def split(self): n_hands = self.get_num_hands() card = self.player.hands.pop() bet_value = self.player.hands[0].bet self.hands = [Hand(card, bet=bet_value) for _ in range(n_hands + 1)]
def deal_hand_to_players(self) -> None: for player in self.players: player.hand = Hand(self.deck.draw_cards(self.hand_size)) player.hand.attach(player)
def __init__(self, name="John Doe", hand=Hand()): self.hand = hand self.name = name
def dealer_wins(player, dealer, chips): print('Dealer wins!') chips.lose_bet() def push(player, dealer): print('Player and Dealer tied. PUSH!') while True: print('Welcome to the game of BlackJack!') deck = Deck() deck.shuffle() player_hand = Hand() player_hand.add_card(deck.deal()) player_hand.add_card(deck.deal()) dealer_hand = Hand() dealer_hand.add_card(deck.deal()) dealer_hand.add_card(deck.deal()) player_chips = Chips() take_bet(player_chips) show_some(player_hand, dealer_hand) while playing:
def __init__(self, shoe_size=6): self.deck = Deck(shoe_size) self.players = self.setup_players() self.dealer = Hand('Dealer')
- Takes input - determine winner - pay out pot - deals new hand ''' #create the game and the table to seat the Players g = Game() table = [] gameloop = True #load the players #-- load the "hero" or person playing against CPU playerName = input('Enter name: ') print(g.getBlinds()) buyIn = input('How much to buy in (MAX Buy In is: ' + str(g.MAX_BUYIN) + '): ') hero = Player(playerName, stackSize=buyIn, hand=Hand(g.MAX_HAND_SIZE)) #print('hero stack size: '+ str(hero.getStackSize())) #-- load hardcoded CPU robot = Player('CPU1', stackSize=g.MAX_BUYIN, hand=Hand(g.MAX_HAND_SIZE)) #print('robot stack size: '+ str(robot.getStackSize())) #-- seat the players so the game can pick who is dealer #--- seat the players at the table table.append(hero) table.append(robot) #--- associate the table to the game g.seatPlayers(table) #pick the dealer and then print out the table statistics
from hand import Hand class Input(enumerate): NULL = 0 HIT = 1 STAND = 2 DOUBLE = 3 SPLIT = 4 SURRENDER = 5 deck = Deck() print("1v1 Blackjack") hand = Hand(deck.draw(2), False) dealer_hand = Hand(deck.draw(2), True) print("Hand1:", hand.print_hand(True), hand.score(True)) print("Dealer:", dealer_hand.print_hand(True), dealer_hand.score(True)) input_mode = True def get_input(): r = random.randint(0, 99) if r < 50: return Input.HIT else: return Input.STAND
def test_hand_score(): hand = Hand() hand.receive_card(Card("hearts", "9")) hand.receive_card(Card("hearts", "ace")) hand.receive_card(Card("spades", "ace")) print(hand.score())
def __init__(self): self.BLACKJACK = 21 self.dealer = Dealer() self.player_hand = Hand()
class BlackJack: def __init__(self, shoe_size=6): self.deck = Deck(shoe_size) self.players = self.setup_players() self.dealer = Hand('Dealer') def setup_players(self): plrs = [] while True: try: q = int(input('How many players are going to play?: ')) break except ValueError: print('Please enter a base 10 number.') for i in range(q): player_name = input('What is the name of player {}?: '.format(i + 1)) plrs.append(Hand(player_name)) return plrs def deal_round(self): for i in range(2): for p in self.players: p.take(self.deck.deal_card()) self.dealer.take(self.deck.deal_card()) def play_round(self): self.deal_round() for p in self.players: while p.score() <= 21: p.display_hand() q = input('Would you like to (H)it or (S)tay?: ').lower() if q == 'h': p.take(self.deck.deal_card()) elif q == 's': break else: if p.score() > 21: p.display_hand() else: self.dealer.display_hand() d_score = self.dealer.score() while d_score < 17: self.dealer.take(self.deck.deal_card()) self.dealer.display_hand() d_score = self.dealer.score() time.sleep(1) def clear_hands(self): for p in self.players: p.clear() self.dealer.clear() def score_game(self): winner = self.dealer score = self.dealer.score() if self.dealer.score() <= 21 else 0 for p in self.players: if 22 > p.score() > score: score = p.score() winner = p return winner def game(self): while True: self.play_round() print('{} wins!'.format(self.score_game().name)) self.clear_hands() q = input("Would you like to play again?: ").lower() if 'n' in q: quit()
def __init__(self, hand=None, money=None): '''Optional money parameter defines staring money.''' self.hand = Hand(hand) self.money = money return
def playerEvent(): global dealerShow global money global bet global currentHand #bust if hands[currentHand].bust == True: currentEvent = "Bust!" textWrite(currentEvent, 60, (255, 255, 255), 150, 70) pygame.display.update() sleep(2) money = money - bet if currentHand == -1 or hands[0].hasSplit == False: if currentHand == -1: hands[0].hasSplit = False currentHand = 0 makeBet() resetDeck(4) startHand() else: currentHand = -1 hands[currentHand].bust = False #stand/win if hands[currentHand].stand == True: if hands[currentHand].hasSplit == True: currentHand = -1 hands[0].stand = False currentEvent = "Stand!" textWrite(currentEvent, 60, (255, 255, 255), 150, 70) pygame.display.update() sleep(2) elif hands[0].hasSplit == False or currentHand == -1: dealerShow = True currentEvent = "Dealer's Turn!" textWrite(currentEvent, 60, (255, 255, 255), 150, 70) pygame.display.update() sleep(2) if hands[2].multipleHits(harmonLimit) == True: hands[2].addCard(deck[0]) deck.pop(0) elif hands[3].multipleHits(maxwellLimit) == True: hands[3].addCard(deck[0]) deck.pop(0) elif hands[1].multipleHits(dealerLimit) == True: hands[1].addCard(deck[0]) deck.pop(0) else: if hands[0].hasSplit == False: #win if hands[currentHand].getHandValue() > hands[ 1].getHandValue() or hands[1].getHandValue() > 21: currentEvent = "You Win!" textWrite(currentEvent, 60, (255, 255, 255), 150, 100) money = money + bet #lose elif hands[currentHand].getHandValue() < hands[ 1].getHandValue() and hands[1].getHandValue() < 22: currentEvent = "You Lose!" textWrite(currentEvent, 60, (255, 255, 255), 150, 100) money = money - bet #tie else: currentEvent = "Tie!" textWrite(currentEvent, 60, (255, 255, 255), 150, 100) #calculates winnings if the player has split with both hands standing else: splitTie = True #win x 2 if hands[0].getHandValue() > hands[1].getHandValue( ) or hands[1].getHandValue() > 21: if hands[currentHand].getHandValue( ) > hands[1].getHandValue() or hands[1].getHandValue( ) > 21: currentEvent = "You Win!" textWrite(currentEvent, 60, (255, 255, 255), 150, 100) money = money + bet * 2 splitTie = False #lose x 2 elif hands[0].getHandValue() < hands[1].getHandValue( ) and hands[1].getHandValue() < 22: if hands[currentHand].getHandValue( ) < hands[1].getHandValue() and hands[1].getHandValue( ) < 22: currentEvent = "You Lose!" textWrite(currentEvent, 60, (255, 255, 255), 150, 100) money = money - bet * 2 splitTie = False #win x 1 if hands[0].getHandValue() > hands[1].getHandValue( ) and hands[currentHand].getHandValue( ) == hands[1].getHandValue(): currentEvent = "You Win!" textWrite(currentEvent, 60, (255, 255, 255), 150, 100) money = money + bet #win x 1 elif hands[currentHand].getHandValue( ) > hands[1].getHandValue() and hands[0].getHandValue( ) == hands[1].getHandValue(): currentEvent = "You Win!" textWrite(currentEvent, 60, (255, 255, 255), 150, 100) money = money + bet #lose x 1 elif hands[0].getHandValue() < hands[1].getHandValue( ) and hands[currentHand].getHandValue( ) == hands[1].getHandValue(): currentEvent = "You Lose!" textWrite(currentEvent, 60, (255, 255, 255), 150, 100) money = money - bet #lose x 1 elif hands[currentHand].getHandValue( ) < hands[1].getHandValue() and hands[0].getHandValue( ) == hands[1].getHandValue(): currentEvent = "You Lose!" textWrite(currentEvent, 60, (255, 255, 255), 150, 100) money = money - bet #tie - tie - one wine one lose elif splitTie == True: currentEvent = "Tie!" textWrite(currentEvent, 60, (255, 255, 255), 150, 100) pygame.display.update() hands[currentHand].stand = False currentHand = 0 sleep(2) makeBet() resetDeck(4) startHand() dealerShow = False hands[currentHand].stand = False #forfeit if hands[currentHand].forfeit == True: currentEvent = "Forfeit!" textWrite(currentEvent, 60, (255, 255, 255), 150, 70) money = money - bet / 2 pygame.display.update() sleep(2) hands[currentHand].forfeit = False if currentHand == 0 and hands[0].hasSplit == True: currentHand = -1 else: currentHand = 0 resetDeck(4) startHand() makeBet() #double if hands[currentHand].double == True: currentEvent = "Double!" textWrite(currentEvent, 60, (255, 255, 255), 150, 70) bet = bet * 2 hands[currentHand].addCard(deck[0]) deck.pop(0) pygame.display.update() sleep(2) hands[currentHand].checkStand() hands[currentHand].double = False pygame.display.update() #split if hands[0].hasSplit == False: if hands[0].split == True: currentEvent = "Split!" textWrite(currentEvent, 60, (255, 255, 255), 150, 70) pygame.display.update() sleep(2) hands.append(Hand()) hands[-1].cards.append(hands[0].cards[1]) del hands[0].cards[1] hands[0].hasSplit = True hands[0].split = False
def new_game(): # создаем колоду d = Deck() # задаем "руки" для игрока и дилера player_hand = Hand("Player") dealer_hand = Hand("Dealer") # сдаем две карты игроку player_hand.add_card(d.deal_card()) player_hand.add_card(d.deal_card()) # сдаем одну карту дилеру dealer_hand.add_card(d.deal_card()) print(dealer_hand) print("=" * 20) print(player_hand) # Флаг проверки необходимости продолжать игру in_game = True # набирать карты игроку имеет смысл только если у него на руке меньше 21 очка while player_hand.get_value() < 21: ans = input("Hit or stand? (h/s) ") if ans == "h": player_hand.add_card(d.deal_card()) print(player_hand) # Если у игрока перебор - дилеру нет смысла набирать карты if player_hand.get_value() > 21: print("You lose") in_game = False else: print("You stand!") break print("=" * 20) if in_game: # По правилам дилер обязан набирать карты пока его счет меньше 17 while dealer_hand.get_value() < 17: dealer_hand.add_card(d.deal_card()) print(dealer_hand) # Если у дилера перебор играть дальше нет смысла - игрок выиграл if dealer_hand.get_value() > 21: print("Dealer bust") in_game = False if in_game: # Ни у кого не было перебора - сравниваем количество очков у игрока и дилера. # В нашей версии если у дилера и игрока равное количество очков - выигрывает казино if player_hand.get_value() > dealer_hand.get_value(): print("You win") else: print("Dealer win")
def __init__(self, game): self.game = game self.hand = Hand()
import sys import os sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from hand import Hand testHand = Hand() ## Royal Flush testHand.add_card(14,0) testHand.add_card(10,0) testHand.add_card(12,0) testHand.add_card(11,0) testHand.add_card(13,0) testHand.clear() ## Straight Flush testHand.add_card(9,3) testHand.add_card(10,3) testHand.add_card(12,3) testHand.add_card(11,3) testHand.add_card(13,3) testHand.clear() ## Straight testHand.add_card(9,1) testHand.add_card(10,2) testHand.add_card(12,0) testHand.add_card(11,3) testHand.add_card(13,2) testHand.clear()
def __init__(self): self.money = 1E999 self.name = "Dealer" self.hand = Hand()
def make_hand(black_jack_deck): cards = [black_jack_deck.draw_top() for i in range(2)] return Hand(cards)
class Blackjack(object): def __init__(self, money): self.player_money = money self.player_bet = 0 self.player_hand = Hand("Player") self.dealer_hand = Hand("Dealer") self.player_choice = "None" # Query player choice until player chooses either hit or stand def query_player(self): decision = raw_input( "What would you like to do? Enter (h)it or (s)tand: ") while (decision != "s" and decision != "h"): decision = raw_input( "What would you like to do? Enter (h)it or (s)tand: ") if (decision == "h"): self.player_choice = "HIT" else: self.player_choice = "STAND" return self.player_choice # Ask player if they want to double down on their hand def double_down(self): down = raw_input( "Would you like to double down? Enter (y)es or (n)o: ") while (down != "y" and down != "n"): down = raw_input( "Would you like to double down? Enter (y)es or (n)o: ") # If selected, player gets additional card, doubles bet, and stands if (down == "y"): self.player_bet = self.player_bet * 2 self.player_hand.add_card() self.player_hand.print_hand() self.player_choice = "STAND" if (down == "n"): self.player_choice = self.query_player() # Implements game logic def play(self, bet): # Set initial bet self.player_bet = bet # Deal dealer's hand self.dealer_hand.add_card() self.dealer_hand.add_card() self.dealer_hand.print_first_card() # Deal player's hand self.player_hand.add_card() self.player_hand.add_card() self.player_hand.print_hand() # If player has Blackjack if (self.player_hand == 21): # If dealer has Blackjack if (self.dealer_hand == 21): self.dealer_hand.print_hand() print "\nTie!\nPlayer has %d dollars." % self.player_money return self.player_money # If only player has Blackjack elif (self.dealer_hand < self.player_hand): self.player_money = self.player_monet + self.player_bet self.dealer_hand.print_hand() print "\nPlayer wins!\nPlayer has %d dollars." % self.player_money return self.player_money # After first hand is played, ask player for double down self.double_down() # If player is bust after double down if (self.player_hand > 21): self.player_money = self.player_money - self.player_bet if (self.player_money < 0): self.player_money = 0 print "\nPlayer's hand is bust.\nPlayer has %d dollars." % self.player_money return self.player_money # If player chooses otherwise and chooses to hit while (self.player_choice == "HIT"): self.player_hand.add_card() self.player_hand.print_hand() # If player goes bust if (self.player_hand > 21): self.player_money = self.player_money - self.player_bet if (self.player_money < 0): self.player_money = 0 print "\nPlayer's hand is bust.\nPlayer has %d dollars." % self.player_money return self.player_money # If player has Blackjack if (self.player_hand == 21): break self.query_player() # Once player chooses to stand, dealer will hit, then hands will be compared if (self.dealer_hand > 17): self.dealer_hand.print_hand() # Dealer begins to hit if hand is < 17 while (self.dealer_hand < 17): self.dealer_hand.add_card() self.dealer_hand.print_hand() # If dealer goes bust if (self.dealer_hand > 21): self.player_money = self.player_money + self.player_bet print "\nDealer's hand is bust. Player wins!\nPlayer has %d dollars." % self.player_money return self.player_money # If dealer wins elif (self.dealer_hand > self.player_hand): self.player_money = self.player_money - self.player_bet if (self.player_money < 0): self.player_money = 0 self.dealer_hand.print_hand() print "\nDealer wins.\nPlayer has %d dollars." % self.player_money return self.player_money # If player wins elif (self.dealer_hand < self.player_hand): self.player_money = self.player_money + self.player_bet print "\nPlayer wins!\nPlayer has %d dollars." % self.player_money return self.player_money # If it is a tie elif (self.dealer_hand == self.player_hand): print "\nTie!\nPlayer has %d dollars." % self.player_money return self.player_money
def __init__(self, money): self.player_money = money self.player_bet = 0 self.player_hand = Hand("Player") self.dealer_hand = Hand("Dealer") self.player_choice = "None"