class TestDeck(unittest.TestCase): def setUp(self): self.deck = Deck() def test52(self): self.assertEqual(len(self.deck), 52) def test_no_dupes(self): seen = set() for card in self.deck: self.assertNotIn(card, seen) seen.add(card) def test_repr_string(self): self.assertIsInstance(repr(self.deck), str) def test_shuffle(self): deck2 = Deck() random.shuffle(deck2) self.assertNotEqual(self.deck.cards, deck2.cards) def test_deal_5(self): hand = self.deck.deal(5) self.assertEqual(len(hand), 5) def test_draw(self): hand = self.deck.deal(5) self.deck.draw(hand) self.assertEqual(len(hand), 6)
def test_deck_length(self): deck = Deck() self.assertEqual(len(deck), 52) deck.deal() self.assertEqual(len(deck), 51) deck.deal(2) self.assertEqual(len(deck), 49)
class Blackjack(object): def __init__(self): self._deck = Deck() self._deck.shuffle() #Pass the player and the dealer two cards each self._player = Player([self._deck.deal(), self._deck.deal()]) self._dealer = Dealer([self._deck.deal(), self._deck.deal()]) '''Returns a list of the player's cards.''' def getPlayerCards(self): return self._player.getCards() '''Returns a list of the dealer's cards.''' def getDealerCards(self): return self._dealer.getCards() '''Deals a card to the player. Returns a tuple of the card and the player's points.''' def hitPlayer(self): card = self._deck.deal() card.turn() self._player.hit(card) return (card, self._player.getPoints()) '''Deals cards to the dealer until an outcome occurs. Returns a string representing the outcome.''' def hitDealer(self): self._dealer.turnFirstCard() playerPoints = self._player.getPoints() if playerPoints > 21: return "You bust and lose!" else: self._dealer.hit(self._deck) dealerPoints = self._dealer.getPoints() if dealerPoints > 21: return "Dealer busts, you win!" elif dealerPoints > playerPoints: return "Dealer wins :(" elif dealerPoints < playerPoints and playerPoints <= 21: return "Congrats! You win!" elif dealerPoints == playerPoints: if self._player.hasBlackjack( ) and not self._dealer.hasBlackjack(): return "Blackjack! You Win!" elif not self._player.hasBlackjack( ) and self._dealer.hasBlackjack(): return "Dealer Blackjack! You lose!" else: return "There is a tie"
def main(): """Creates a deck, deals and prints the cards, then creates a second deck, shuffles, deals and prints.""" deck = Deck() print("NUMBER OF CARDS:", len(deck)) print("THE CARDS IN A NEW DECK:") while not deck.isEmpty(): print(deck.deal()) deck = Deck() deck.shuffle() print("\nTHE CARDS IN A SHUFFLED DECK:") while not deck.isEmpty(): print(deck.deal())
def test_dealing_cards(amount=1): # generator for decks? deck = Deck(shuffle=True) test_hand_one = deck.deal(cards=2) test_hand_two = deck.deal(cards=2) assert len(test_hand_one) == 2 assert test_hand_one != test_hand_two test_hand_three = deck.deal(cards=1384) assert len(test_hand_three) == 1384 test_hand_four = deck.deal(6) assert len(test_hand_four) == 6 deck_two = Deck(shuffle=True) deck_three = Deck(shuffle=True) assert deck_two.cards != deck_three.cards
def test_deck(self): deck = Deck() deck.shuffle() hands = deck.deal(4) self.assertTrue({13}, set(len(h) for h in hands)) self.assertEqual(52, len(set(sum(hands, [])))) hands = deck.deal(3) self.assertTrue({17}, set(len(h) for h in hands)) self.assertEqual(51, len(set(sum(hands, [])))) hands = deck.deal(10, 2) self.assertTrue({2}, set(len(h) for h in hands)) self.assertEqual(20, len(set(sum(hands, []))))
class Deadoralive(object): print("DEADORALIVE") def __init__(self): self._deck = Deck() self._deck.shuffle() self._player = Player([self._deck.deal(), self._deck.deal()]) self._dealer = Dealer([self._deck.deal(), self._deck.deal()]) def getValue(self): """Returns the number of points in the hand.""" count = 0 for card in self._cards: if card.rank > 9: count += 10 elif card.rank == 1: count += 11 else: count += card.rank return count def compare(self,other): """compare the cards and returns message""" """we can compare by using the value function""" playerpoint = self._player.getValue() dealerpoint = other._dealer.getValue() if playerpoint > dealerpoint: print("\nPlayer Won") elif playerpoint < dealerpoint: print("\nDealer Won") def playdead(self): print("Player:\n", self._player) print("Dealer:\n", self._dealer) while True: if len(self._deck._cards) == 0: print("game has ended") break else: _deadoralive.compare(self._player,self._dealer)
def __init__(self, dealer, tricks=None, hands=None, round_state=None, called_trump=None, trump=None, turn=None, maybe_trump=None, going_alone=None): deck = Deck() self.tricks = tricks or [] self.hands = hands or [Hand(deck.deal(5)) for x in range(4)] # Other valid states: "bid2", "play", "end" self.round_state = round_state or "bid" self.called_trump = called_trump or None # Nobody has called trump yet self.trump = trump or None # Initially, there is no trump self.dealer = dealer # Player num self.turn = turn or (dealer + 1) % 4 # Who starts? # The card that might be trump self.maybe_trump = maybe_trump or deck.deal(1)[0] # Is the player who called trump going alone? self.going_alone = going_alone or False
def hit(deck: cards.Deck, hand: cards.Hand): assert type(deck) is cards.Deck assert type(hand) is cards.Hand hand.add_card(deck.deal()) hand.adjust_for_aces() return hand
class GUI_Cards(EasyFrame): def __init__(self): """Creates the dice, and sets up the Images and labels for the two dice to be displayed, the state label, and the two command buttons.""" EasyFrame.__init__(self, title="GUI Cards") self.setSize(220, 200) self.deck = Deck() self.deck.shuffle() card = "" self.cardLabel = self.addLabel("", row=0, column=1, sticky="NSEW") self.stateLabel = self.addLabel("", row=1, column=0, sticky="NSEW", columnspan=2) self.addButton(row=2, column=0, text="Deal", command=self.deal) self.addButton(row=2, column=1, text="Shuffle", command=self.shuffle) self.addButton(row=2, column=2, text="New deck", command=self.newDeck) self.refreshImages(card) def deal(self): """Rools the dice and updates the view with the results.""" card = self.deck.deal() self.stateLabel["text"] = card self.refreshImages(card) def shuffle(self): """Rools the dice and updates the view with the results.""" self.deck.shuffle() self.stateLabel["text"] = "" card = "" self.refreshImages(card) def newDeck(self): """Create a new craps game and updates the view.""" self.deck = Deck() self.deck.shuffle() self.stateLabel["text"] = "" card = "" self.refreshImages(card) def refreshImages(self, card): """Updates the images in the window.""" try: fileName = "DECK/" + str(card.rank) + str( (card.suit[0]).lower()) + ".gif" self.image = PhotoImage(file=fileName) self.cardLabel["image"] = self.image except Exception: fileName = "DECK/b.gif" self.image = PhotoImage(file=fileName) self.cardLabel["image"] = self.image
class DeckGUI(EasyFrame): def __init__(self): EasyFrame.__init__(self, title="Testing a Deck Display") self.setSize(350, 200) self.deck = Deck() self.card = self.deck.deal() self.image = PhotoImage(file=self.card.fileName) self.cardImageLabel = self.addLabel("", row=0, column=0) self.cardImageLabel["image"] = self.image self.cardNameLabel = self.addLabel(row=1, column=0, text=self.card) self.button = self.addButton(row=0, column=1, text="Next Card", command=self.nextCard) self.button = self.addButton(row=1, column=1, text="Shuffle", command=self.shuffleDeck) self.button = self.addButton(row=2, column=1, text="New Deck", command=self.newDeck) def nextCard(self): """Deals a card from the deck and displays it, or displays the back side if empty.""" if len(self.deck) == 0: self.image = PhotoImage(file=Card.BACK_NAME) self.cardNameLabel["text"] = 'Empty' else: self.card = self.deck.deal() self.image = PhotoImage(file=self.card.fileName) self.cardNameLabel["text"] = self.card self.cardImageLabel["image"] = self.image def shuffleDeck(self): """Shuffles the existing deck of cards.""" self.deck.shuffle() def newDeck(self): """Creates a new Deck object, assigns it to the window's deck, and updates the card images appropriately.""" self.deck = Deck()
def hit(deck, hand): card = Deck.deal(deck) Hand.add_cards(hand, card) if hand.value > 21: if hand.aces > 0: hand.adjust_for_ace() else: print('bust') print(hand)
class DeckGUI(EasyFrame): def __init__(self): EasyFrame.__init__(self, title="Testing a Deck Display") self.setSize(300, 150) self.deck = Deck() self.card = self.deck.deal() self.image = PhotoImage(file=self.card.fileName) self.cardImageLabel = self.addLabel("", row=0, column=0, rowspan=3) self.cardImageLabel["image"] = self.image self.cardNameLabel = self.addLabel(row=3, column=0, text=self.card) self.button = self.addButton(row=0, column=1, text="Next Card", command=self.nextCard) self.shuffleButton = self.addButton(row=1, column=1, text="Shuffle", command=self.shuffle) self.newDeck = self.addButton(row=2, column=1, text="New Deck", command=self.new) def nextCard(self): """Deals a card from the deck and displays it, or displays the back side if empty.""" if len(self.deck) == 0: self.image = PhotoImage(file=Card.BACK_NAME) self.cardNameLabel["text"] = 'Empty' else: self.card = self.deck.deal() self.image = PhotoImage(file=self.card.fileName) self.cardNameLabel["text"] = self.card self.cardImageLabel["image"] = self.image def shuffle(self): self.deck.shuffle() def new(self): """Returns the program to its initial state.""" self.deck = Deck() self.cardImageLabel["image"] = self.image self.cardNameLabel["text"] = ""
class Blackjack(object): def __init__(self): self._deck = Deck() self._deck.shuffle() self._player = Player([self._deck.deal(), self._deck.deal()]) self._dealer = Dealer([self._deck.deal(), self._deck.deal()]) def play(self): print("Player:\n", self._player) print("Dealer:\n", self._dealer) while True: choice = input("Do you want a hit? [y/n]: ") if choice in ("Y", "y"): self._player.hit(self._deck.deal()) points = self._player.getPoints() print("Player:\n", self._player) if points >= 21: break else: break playerPoints = self._player.getPoints() if playerPoints > 21: print("You bust and lose") else: self._dealer.hit(self._deck) print("Dealer:\n", self._dealer) dealerPoints = self._dealer.getPoints() if dealerPoints > 21: print("Dealer busts and you win") elif dealerPoints > playerPoints: print("Dealer wins") elif dealerPoints < playerPoints and playerPoints <= 21: print("You win") elif dealerPoints == playerPoints: if self._player.hasBlackjack( ) and not self._dealer.hasBlackjack(): print("You win") elif not self._player.hasBlackjack( ) and self._dealer.hasBlackjack(): print("Dealer wins") else: print("There is a tie")
class DeckGUI(EasyFrame): def __init__(self): EasyFrame.__init__(self, title = "Testing a Deck Display") self.setSize(350, 200) self.deck = Deck() self.card = self.deck.deal() self.image = PhotoImage(file = self.card.fileName) self.cardImageLabel = self.addLabel("", row = 0, column = 0) self.cardImageLabel["image"] = self.image self.cardNameLabel = self.addLabel(row = 1, column = 0, text = self.card) self.button = self.addButton(row = 0, column = 1, text = "Next Card", command = self.nextCard) self.button = self.addButton(row = 1, column = 1, text = "Shuffle", command = self.shuffleDeck) self.button = self.addButton(row = 2, column = 1, text = "New Deck", command = self.newDeck) def nextCard(self): """Deals a card from the deck and displays it, or displays the back side if empty.""" if len(self.deck) == 0: self.image = PhotoImage(file = Card.BACK_NAME) self.cardNameLabel["text"] = 'Empty' else: self.card = self.deck.deal() self.image = PhotoImage(file = self.card.fileName) self.cardNameLabel["text"] = self.card self.cardImageLabel["image"] = self.image def shuffleDeck(self): """Shuffles the existing deck of cards.""" self.deck.shuffle() def newDeck(self): """Creates a new Deck object, assigns it to the window's deck, and updates the card images appropriately.""" self.deck = Deck()
class OichoKabu(object): def __init__(self): self._deck = Deck() self._deck.shuffle() #Pass the player and the dealer two cards each self._player = Player([self._deck.deal(), self._deck.deal()]) self._dealer = Dealer([self._deck.deal(), self._deck.deal()]) '''Returns a list of the player's cards.''' def getPlayerCards(self): return self._player.getCards() '''Returns a list of the dealer's cards.''' def getDealerCards(self): return self._dealer.getCards() '''Deals a card to the player. Returns a tuple of the card and the player's points.''' def hitPlayer(self): card = self._deck.deal() card.turn() self._player.hit(card) return card '''Deals cards to the dealer until an outcome occurs. Returns a string representing the outcome.''' def hitDealer(self): card = self._deck.deal() card.turn() sum = self._dealer._cards[0].rank + self._dealer._cards[1].rank if (sum % 10 < 6): self._dealer.hit(card) self._dealer.turnFirstCard() def whoWins(self, playerCardOne, playerCardTwo, playerCardThree, dealerCardOne, delearCardTwo, dealerCardThree): OK.whoWins(playerCardOne, playerCardTwo, playerCardThree, dealerCardOne, delearCardTwo, dealerCardThree)
class Deadoralive(object): def __init__(self): self._deck=Deck() self._deck.shuffle() self._player1=Player([]) self._player2=Player([]) def play(self): win1=0 win2=0 for i in range(26): ch=input("Press [y] to continue or any other to quit: ") if ch=='Y' or ch=='y': self._player1.hit(self._deck.deal()) self._player2.hit(self._deck.deal()) card1=self._player1.getCard() card1a=card1.rank card2=self._player2.getCard() card2a=card2.rank print("Player 1:\n",card1a) print("Player 2:\n",card2a) if(card1a>card2a): print("Player 1 won") win1+=1 elif(card2a>card1a): print("Player 2 won") win2+=1 else: if card1.suit=="Spades": print("Player 2 won with",card2.suit) win2+=1 elif card1.suit=="Diamonds" and (card2.suit=="Hearts" or card2.suit=="Clubs"): print("Player 2 won with",card2.suit) win2+=1 elif card1.suit=="Hearts" and card2.suit=="Clubs": print("Player 2 won with",card2.suit) win2+=1 elif card1.suit==card2.suit: print("TIE") else: print("Player 1 won with",card1.suit) win1+=1 if i==25: print("\nPlayer 1:",win1,"wins") print("Player 2:",win2,"wins") else: print("Player 1:",win1,"wins") print("Player 2:",win2,"wins") break
class CardDemo(Frame): def __init__(self): """Sets up the window and widgets.""" Frame.__init__(self) self.master.title("Card Demo") self.grid() self._deck = Deck() self._backImage = PhotoImage(file = Card.BACK_NAME) self._cardImage = None self._imageLabel = Label(self, image = self._backImage) self._imageLabel.grid(row = 0, column = 0, rowspan = 3) self._textLabel = Label(self, text = "") self._textLabel.grid(row = 3, column = 0) self._dealButton = Button(self, text = "Deal", command = self._deal) self._dealButton.grid(row = 0, column = 1) self._shuffleButton = Button(self, text = "Shuffle", command = self._shuffle) self._shuffleButton.grid(row = 1, column = 1) self._newButton = Button(self, text = "New Deck", command = self._new) self._newButton.grid(row = 2, column = 1) def _deal(self): """If the deck is not empty, deals and displays the next card. Otherwise, returns the program to its initial state.""" card = self._deck.deal() if card != None: self._cardImage = PhotoImage(file = card.fileName) self._imageLabel["image"] = self._cardImage self._textLabel["text"] = str(card) else: self._new() def _shuffle(self): self._deck.shuffle() def _new(self): """Returns the program to its initial state.""" self._deck = Deck() self._cardImage = None self._imageLabel["image"] = self._backImage self._textLabel["text"] = ""
def __init__(self, rules: RuleSet, pass_info: PassInfo, scores: List[int], deck: Deck = None): self.rules = rules self.pass_info = pass_info self.scores_before_round = scores[:] # Could remove any cards specified in rules.removed_cards if deck is None: deck = Deck() deck.shuffle() hands = deck.deal(rules.num_players) self.players = [Player(hand=h) for h in hands] self.prev_tricks = [] self.current_trick = None
def update(self, mouse_X, mouse_Y, deck, discard_pile, player, dealer, round_over, round_counter): """runs an update check to see if player hit the button and to do the necessary items when hit""" if self.rect.collidepoint(int(mouse_X), int(mouse_Y)) == 1 and round_over == 1: #print("deal button hit successfully") #reset counters round_over = 0 round_counter += 1 #make a new deck and distribute cards deck = Deck.createDeck() deck, discard_pile, player, dealer = Deck.deal(deck, discard_pile) return round_over, round_counter, deck, discard_pile, player, dealer
class CardDemo(Frame): def __init__(self): """Sets up the window and widgets.""" Frame.__init__(self) self.master.title("Card Demo") self.grid() self._deck = Deck() self._backImage = PhotoImage(file=Card.BACK_NAME) self._cardImage = None self._imageLabel = Label(self, image=self._backImage) self._imageLabel.grid(row=0, column=0, rowspan=3) self._textLabel = Label(self, text="") self._textLabel.grid(row=3, column=0) self._dealButton = Button(self, text="Deal", command=self._deal) self._dealButton.grid(row=0, column=1) self._shuffleButton = Button(self, text="Shuffle", command=self._shuffle) self._shuffleButton.grid(row=1, column=1) self._newButton = Button(self, text="New Deck", command=self._new) self._newButton.grid(row=2, column=1) def _deal(self): """If the deck is not empty, deals and displays the next card. Otherwise, returns the program to its initial state.""" card = self._deck.deal() if card != None: self._cardImage = PhotoImage(file=card.fileName) self._imageLabel["image"] = self._cardImage self._textLabel["text"] = str(card) else: self._new() def _shuffle(self): self._deck.shuffle() def _new(self): """Returns the program to its initial state.""" self._deck = Deck() self._cardImage = None self._imageLabel["image"] = self._backImage self._textLabel["text"] = ""
def run_game(): #Initialize pygame screen and font modules pygame.init() pygame.font.init() #variables to determine round and statistics round_over = 0 round_counter = 1 wins = 0 losses = 0 #create the title title = gf.create_text("Blackjack", font_preferences, 42, font_color) author = gf.create_text("By: Cole Lehman", font_preferences, 20, font_color) #create lists to be used later in the game discard_pile = [] deck = [] player = [] dealer = [] #generate card elements and variables, then generate list deck_icon = Deck(screen, (table_settings.table_width // 2), (table_settings.table_height // 2) - 10) deck = Deck.createDeck() deck, discard_pile, player, dealer = Deck.deal(deck, discard_pile) #variable to define printed text and keep active within loop text = None text_placement = textbox_settings.y_pos + 5 # Start the main loop for the game while True: #variables for mouse coordinates mouse_X = 0 mouse_Y = 0 #draw background and base static elements first through each pass screen.fill(ai_settings.bg_color) screen_pieces.draw() screen.blit( title, ((sidebar_settings.x_pos + sidebar_settings.sidebar_quartered) - 20, 20)) screen.blit( author, ((sidebar_settings.x_pos + sidebar_settings.sidebar_quartered) - 20, 70)) deck_icon.blitme() #print current stats to screen gf.print_screen_stats(screen, font_preferences, font_color, round_counter, wins, losses) #draw the cards for the dealer and player Deck.drawCurrentHand(screen, player, dealer, table_offset, table_settings.y_pos, table_settings.table_height, round_over) #print messages to user on status of the game (result of round) gf.textbox_message(screen, round_over, text, font_preferences, textbox_font_size, font_color, space_offset, text_placement, player) #check events for exit signal and mouse button presses message = gf.check_events() #retrieve mouse output (formatted as string since check events cannot return multiple variables) and splice the output to retrieve mouse X & Y coord. if message != None: mouse_X, mouse_Y = message.split('|') #detect and respond if there is blackjack on start of round if len(player) == 2 and len(dealer) == 2 and round_over == 0: text, round_over, wins, losses = gf.blackjack( player, dealer, text, round_over, wins, losses) #responds when user hits the double button deck, discard_pile, player, dealer, round_over, text, wins, losses = doubleButton.update( mouse_X, mouse_Y, deck, discard_pile, player, dealer, round_over, text, wins, losses) #responds when user hits the stand button round_over, text, deck, discard_pile, dealer, player, wins, losses = standButton.update( mouse_X, mouse_Y, round_over, player, dealer, text, deck, discard_pile, wins, losses) #responds when user hits the hit button deck, discard_pile, player, round_over, text, losses = hitButton.update( mouse_X, mouse_Y, deck, discard_pile, player, round_over, text, losses) #responds when user hits the deal button round_over, round_counter, deck, discard_pile, player, dealer = dealButton.update( mouse_X, mouse_Y, deck, discard_pile, player, dealer, round_over, round_counter) #draw start of round buttons to screen if round_over == 0 and len(player) == 2: in_round_buttons_DbAllow.draw(screen) #draw buttons after first hit elif round_over == 0 and len(player) > 2: in_round_buttons_DbDeny.draw(screen) #draw buttons for end of round else: out_of_round_buttons.draw(screen) # Make the most recently drawn screen visible pygame.display.flip()
class CardDemo(EasyFrame): def __init__(self): """Creates the cards and sets up the images and labels for two cards to be displayed, the state label, and two command buttons. """ EasyFrame.__init__(self, title="Card Game") self.setSize(220,200) #create cards/deck self.card1=Deck() self.card="b" #labels self.cardLabel1= self.addLabel("",row=0, column=0, sticky= "NSEW",columnspan=2) self.stateLabel = self.addLabel(self.card, row = 1, column = 0, sticky = "NSEW", columnspan = 2) self.addButton(row = 2, column = 0, text = "Draw", command = self.nextDraw) self.addButton(row = 2, column = 1, text = "New game", command = self.newGame) self.refreshImages() def nextDraw(self): """draws a card and updates view""" self.card=self.card1.deal() self.stateLabel = self.addLabel(self.card, row = 1, column = 0, sticky = "NSEW", columnspan = 2) #call split of rank and suite self.convert() #self.refreshImages() def newGame(self): self.card1=Deck() self.card1.shuffle() self.stateLabel["text"]="" self.card="b" self.refreshImages() def refreshImages(self): """updates the images in the window""" fileName1="DECK/" + str(self.card) + ".gif" self.image1= PhotoImage(file=fileName1) self.cardLabel1["image"]= self.image1 def convert(self): """converts the strin created from .deal and changes it into a format for finding image files. """ rank='' suits='' x=str(self.card) self.newWordList=x.split() print(self.newWordList) #if statements to change word for image path if self.newWordList[0] == 'Ace': rank = '1' elif self.newWordList[0] == 'Jack': rank = '11' elif self.newWordList[0] =='Queen' : rank = '12' elif self.newWordList[0] == 'King': rank = '13' else: rank = self.newWordList[0] if self.newWordList[2] == 'Spades': suits = 's' elif self.newWordList[2] == 'Hearts': suits = 'h' elif self.newWordList[2] =='Diamonds' : suits = 'd' elif self.newWordList[2] == 'Clubs': suits = 'c' name=rank+suits print(name) self.card=rank+suits self.refreshImages()
class Table(object): def __init__(self, name, sb=1, bb=2, ante=0, max_players=6, players=None, min_buyin=None, max_buyin=None): self.id = name self.name = name self.sb = sb self.bb = bb self.ante = ante self.min_buyin = min_buyin or 50*bb self.max_buyin = max_buyin or 200*bb self.players = [None] * max_players if players: for i, p in enumerate(players): self.players[i] = p # http://www.learn-texas-holdem.com/questions/blind-rules-when-players-bust-out.htm self.owes_bb = set() self.owes_sb = set() # individual hand state self.deck = Deck() self.game_state = { "sb_idx": None, "bb_idx": None, "board": [] } self.games = [HandHistory()] def get_bb_idx(self): return self.game_state['bb_idx'] def get_sb_idx(self): return self.game_state['sb_idx'] def get_board(self): return self.game_state['board'] def get_active_players(self, rotate=0): return [p for p in rotate_iter(self.players, rotate) if p is not None and not p.sitting_out] def get_players_still_in(self, rotate=0): return [p for p in self.get_active_players(rotate) if p.last_action != Events.FOLD] def current_pot(self): return sum([player.wagers for player in self.get_active_players()]) def hand_in_progress(self): # TODO: there might be an edge case where this becomes incorrect? return len(self.deck.cards) < 52 def to_json(self, indent=None): out = { "id": self.id, "sb" : self.sb, "bb" : self.bb, "ante" : self.ante, "players" : {i : p.summary_for_json() if p else None for i, p in enumerate(self.players)} } if self.hand_in_progress(): game_state = {k:v for k,v in self.game_state.iteritems()} game_state['board'] = [c.__str__() for c in self.game_state['board']] game_state['pot'] = self.current_pot() out['game_state'] = game_state return json.dumps(out, indent=indent) def sit(self, player, seat_number): if self.players[seat_number]: raise Exception("Seat already taken") else: self.players[seat_number] = player self.owes_bb.add(player.id) def stand(self, player): self.players[self.index(player)] = None def new_hand(self): self.log("===Starting hand {}===".format(len(self.games))) self.games.append(HandHistory()) self.game_state['board'] = [] self.deck = Deck() self.new_street() for player in self.get_active_players(): player.new_hand() def new_street(self): for player in self.get_active_players(): player.last_action = Events.NONE player.uncollected_bets = 0 def is_player(self, x): return x in [p.id for p in self.players if p] def get_player(self, id): for player in self.players: if player.id == id: return player return None def deal(self, n_cards): self.game_state.board.extend([self.deck.deal() for _ in xrange(n_cards)]) def handle_event(self, subj, event, obj): if isinstance(subj, Player): raise Exception("Passed Player instance into handle_event. You probably meant to pass in the ID.") elif isinstance(subj, Table): raise Exception("Passed Table instance into handle_event. You probably meant to pass in the ID.") self.log((subj, event, obj)) if self.is_player(subj): player = self.get_player(subj) if event == Events.NEW_HAND: player.new_hand() elif event in (Events.POST, Events.POST_DEAD): if obj == self.sb and player.id in self.owes_sb: self.owes_sb.remove(player.id) elif obj == self.bb and player.id in self.owes_bb: self.owes_bb.remove(player.id) player.post(obj) elif event == Events.BET: player.bet(obj) elif event == Events.RAISE_TO: player.raise_to(obj) elif event == Events.CALL: player.call(obj) elif event == Events.FOLD: player.fold() elif event == Events.CHECK: player.check() elif event == Events.DEAL: player.deal([self.deck.deal() for _ in xrange(obj)]) elif event == Events.SIT_IN: player.sit_out() elif event == Events.SIT_OUT: player.sit_in() elif event == Events.LOSE: player.lose(obj) elif event == Events.WIN: player.win(obj) elif event == Events.BUY: player.buy(obj) else: raise Exception("Unknown event {} for {} with {}".format(event, subj, obj)) elif subj == self.id: if event == Events.OWE: if obj == self.bb: self.owes_bb.add(subj) elif obj == self.sb: self.owes_sb.add(subj) else: raise Exception("Can't owe a non-blind amt") elif event == Events.SET_GAME_STATE: key, val = obj if not key in self.game_state: raise Exception("Unknown game state parameter") self.game_state[key] = val elif event == Events.DEAL: self.game_state['board'].extend([self.deck.deal() for _ in xrange(obj)]) elif event == Events.NEW_HAND: self.new_hand() elif event == Events.NEW_STREET: self.new_street() elif event == Events.LOG: pass else: raise Exception("Unknown event {} for {} with {}".format(event, subj, obj)) def handle_events(self, events): for event in events: self.handle_event(*event) def log(self, event): print event self.games[-1].log(event)
from cards import Deck, Card from player import Player deck = Deck() deck.shuffle() p1 = Player([deck.deal() for i in range(2)], [deck.deal() for f in range(5)]) print(p1.cards) print(p1.community) print(p1.high_card()) print(p1.build_ranks())
class WarGame(object): """Plays the game of War.""" def __init__(self): """Sets up the two players, the war pile, the deck, and the game state.""" self._player1 = Player() self._player2 = Player() self._warPile = [] self._gameState = "" self._deck = Deck() self._deck.shuffle() def __str__(self): """Returns the game state.""" return self._gameState def deal(self): """Deals 26 cards to each player.""" while not self._deck.isEmpty(): self._player1.addToUnplayedPile(self._deck.deal()) self._player2.addToUnplayedPile(self._deck.deal()) def step(self): """Makes one move in the game, and returns the two cards played.""" card1 = self._player1.getCard() card2 = self._player2.getCard() self._warPile.append(card1) self._warPile.append(card2) self._gameState = "Player 1: " + str(card1) + "\n" +\ "Player 2: " + str(card2) if card1.rank == card2.rank: self._gameState += "\nCards added to War pile\n" elif card1.rank > card2.rank: self._transferCards(self._player1) self._gameState += "\nCards go to Player 1" else: self._transferCards(self._player2) self._gameState += "\nCards go to Player 2" return (card1, card2) def _transferCards(self, player): """Transfers cards from the war pile to the player's winnings pile.""" while len(self._warPile) > 0: player.addToWinningsPile(self._warPile.pop()) def winner(self): """Returns None if there is no winner yet. Otherwise, returns a string indicating the player who won with each player's number of cards, or a tie.""" if self._player1.isDone() or self._player2.isDone(): count1 = self._player1.winningsCount() count2 = self._player2.winningsCount() if count1 > count2: return "Player 1 wins, " + str(count1) + " to " +\ str(count2) +"!" elif count2 > count1: return "Player 2 wins, " + str(count2) + " to " +\ str(count1) +"!" else: return "The game ends in a tie!\n" else: return None
import time from cards import make_hand, Hand, Deck, best_score start = time.clock() h1 = make_hand("Qc, Qs, Td, 5c") h2 = make_hand("Qh, Th, 7s, 2c") base_deck = Deck() for card in h1: base_deck.remove(card) for card in h2: base_deck.remove(card) base_cards = base_deck.cards wins = 0 for i in range(10000): deck = Deck(initial=base_cards) board = Hand( [deck.deal(), deck.deal(), deck.deal(), deck.deal(), deck.deal()]) if (best_score(h1, board) >= best_score(h2, board)): wins += 1 print(wins / 10000.0) end = time.clock() print("Completed in {}".format(end - start))
class FreeCellGame(): #Methods that are used for creating / replaying a game """ The main constructor method for the free cell game """ def __init__(self): #Create lists for the distinct pile objects self._tableaux = list() self._freecells = list() self._homecells = list() #Creates a list for containing potential moves self.potentialMoves = list() #Constructs a new game for the model self.construct() self.newGame() """ Constructs a new game without creating a new model """ def newGame(self): self.reset() """ Allows a player to restart the current game """ def restart(self): self.reset(self._restartDeck) """ A method used to both start a new game and restart an old one """ def reset(self, deck=None): self.clear() self._moveLog = [] if deck == None: self._deck = Deck() self._deck.shuffle() else: self._deck = deck self.deal() self.getPotentialMoves() """ Constructor class for the free cell game """ def construct(self): for x in range(4): self._freecells.append(FreeCell()) self._homecells.append(HomePile()) self._tableaux.append(Tableau()) for x in range(4): self._tableaux.append(Tableau()) """ Deals the cards to set a game """ def deal(self): self._restartDeck = Deck(self._deck) for x in range(7): for y in range(4): self._tableaux[y].add(self._deck.deal()) for x in range(6): for y in range(4, 8): self._tableaux[y].add(self._deck.deal()) """ Clears the cards from all of the cells """ def clear(self): for x in range(4): self._freecells[x].clear() self._homecells[x].clear() self._tableaux[x].clear() for x in range(4, 8): self._tableaux[x].clear() #Methods for getting move counts """ Returns the number of moves performed by a player using the move log """ def getMoveCount(self): return len(self._moveLog) """ Returns the number of potential moves in a game at any given point """ def getPotentialMoveCount(self): return len(self.potentialMoves) #Methods dealing with moving cards between piles """ The moves neccessary for a tableaux """ def moveTableau(self, gPile, cardPosition, rPile, card, rpos): if gPile.isMovable(cardPosition) and type(rPile) == Tableau: if rPile.isLegal(card): self._moveLog.append(Move(gPile, cardPosition, rPile, rpos)) rPile.addPile(gPile, cardPosition) self.getPotentialMoves() return True else: return False else: return False """ The moves neccessary for a free cell """ def moveSingleCard(self, gPile, cardPosition, rPile, card, rpos): if rPile.isLegal(card): self._moveLog.append(Move(gPile, cardPosition, rPile, rpos)) rPile.add(card) gPile.pop() self.getPotentialMoves() return True else: return False """ Combines move methods to step through the game """ def step(self, move): (gPile, gpos, rPile, rpos) = move.returnValues() card = gPile.getCardAt(gpos) if type(gPile) == Tableau and gpos != gPile.len() - 1: return self.moveTableau(gPile, gpos, rPile, card, rpos) else: if type(gPile) != HomePile: return self.moveSingleCard(gPile, gpos, rPile, card, rpos) #Methods used to convert text into a move for a terminal application of the game """ Converts text provided by the terminal application of the game into a move and then runs the move """ def textToMove(self, givingPile, cardPosition, recievingPile): if not self.validInput(givingPile, cardPosition, recievingPile): return False move = self.converter(givingPile, cardPosition, recievingPile) return self.step(move) """ Used to convert incoming text into usable data """ def converter(self, givingPile, gpos, recievingPile): gPile = self.convertStringToPileValues(givingPile) rPile = self.convertStringToPileValues(recievingPile) gpos = int(gpos) rpos = rPile.len() move = Move(gPile, gpos, rPile, rpos) return move """ Checks the incoming input to determine if it is valid """ def validInput(self, givingPile, gpos, recievingPile): gPile = self.convertStringToPileValues(givingPile) rPile = self.convertStringToPileValues(recievingPile) if gPile != None and rPile != None: if isInt(gpos): if int(gpos) < gPile.len(): return True return False """ Converts strings into pile values if possible """ def convertStringToPileValues(self, string): string = string.lower() if string in ["t1","t2","t3","t4","t5","t6","t7","t8", \ "h1","h2","h3","h4","f1","f2","f3","f4"]: pileNumber = int(string[1]) if string[0] == "t": return self._tableaux[pileNumber - 1] elif string[0] == "h": return self._homecells[pileNumber - 1] else: return self._freecells[pileNumber - 1] return None #Methods dealing with winning and losing conditions """ Determines if the game has a winner """ def isWinner(self): if self._homecells[0].maxSize() and \ self._homecells[1].maxSize() and \ self._homecells[2].maxSize() and \ self._homecells[3].maxSize(): return True else: return False """ Determines if there are still moves on the board """ def areMoves(self): if self.getPotentialMoveCount() == 0: return False elif self.getPotentialMoveCount( ) == 1 and self._moveLog[-2] == self.potentialMoves[0]: return False else: return True #Additional Methods """ Allows a user to take back a move """ def undo(self): if self.getMoveCount() > 0: move = self._moveLog.pop() (gPile, gpos, rPile, rpos) = move.returnValues() card = rPile._lyst[rpos] #Deals with the case of a tableau stack if rpos != rPile.len() - 1: gPile.addPile(rPile, rpos) #Deals with the other cases involving single cards else: gPile.add(card) rPile.pop() self.getPotentialMoves() """ An auto-pilot feature that allows the user to make the "best possible" move (Essentially a Hint) Works well when coupled with the undo method """ def autoMove(self): self.step(self.getHint()) """ Returns a hint for the human player """ def getHint(self): self.potentialMoves.sort() self.potentialMoves.reverse() return self.potentialMoves[0] """ Runs through the current model of the game and determines how many moves are possible """ def getPotentialMoves(self): #check the legality of moving each card at the end of a tableau and freecell self.potentialMoves = [] #Runs through all the tableaux in the game for tableau in self._tableaux: if not tableau.isEmpty(): gpos = tableau.len() - 1 card = tableau.getCardAt(gpos) #Checks if cards can be moved to homecells for cell in self._homecells: if cell.isLegal(card): self.potentialMoves.append(Move(tableau, gpos, cell)) #Checks if cards can be moved to freecells for cell in self._freecells: if cell.isLegal(card): self.potentialMoves.append(Move(tableau, gpos, cell)) #Checks if cards can be moved between tableaux self.getPotentialTableauMoves(tableau) #Runs through all the freecells in the game for freecell in self._freecells: if not freecell.isEmpty(): gpos = 0 card = freecell.getCardAt(0) #Checks if cards can be moved to homecells for cell in self._homecells: if cell.isLegal(card): self.potentialMoves.append(Move(freecell, gpos, cell)) #Checks if cards can be moved to tableaux for cell in self._tableaux: if cell.isLegal(card): self.potentialMoves.append(Move(freecell, gpos, cell)) """ Runs through a given tableau and determines the position from which it is movable """ def movableTableau(self, tableau): pos = tableau.len() - 1 card = tableau.getCardAt(pos) while pos >= 0: newCard = tableau.getCardAt(pos - 1) if newCard.rank == card.rank + 1 and newCard.color != card.color: card = newCard pos -= 1 else: return pos """ Runs through the movable stack within a tableau and determines possible moves """ def getPotentialTableauMoves(self, tableau): pos = self.movableTableau(tableau) length = tableau.len() while pos < length: card = tableau.getCardAt(pos) for cell in self._tableaux: if cell.isLegal(card): self.potentialMoves.append(Move(tableau, pos, cell)) pos += 1 """ String representation of a free cell game """ def __str__(self): tempstr = "Home Cells:\n" for x in range(4): tempstr += str("h" + str(x + 1) + ": " + str(self._homecells[x]) + "\n") tempstr += "\nFree Cells:\n" for x in range(4): tempstr += str("f" + str(x + 1) + ": " + str(self._freecells[x]) + "\n") tempstr += "\nTableaux:\n" for x in range(8): tempstr += str("t" + str(x + 1) + ": " + str(self._tableaux[x]) + "\n") tempstr += "\nMove Count: " + str(self.getMoveCount()) + "\n" tempstr += "\nPotential Moves: " + str( self.getPotentialMoveCount()) + "\n" return tempstr
print("\n") #create a new deck New_Deck = Deck() print("I am shuffling the deck") print("\n") #shuffles the deck New_Deck.shuffle() #deal a card print("Here's your card: ") Dealthis = New_Deck.deal() print(Dealthis) print("\n") print("Is the next card higher or lower?") print("Please type in 'lower', 'higher', 'Lower', or 'Higher'") user_input = input() print("\n") Dealthisagain = New_Deck.deal() print("Your Card: ") print(Dealthisagain) if user_input.lower() == "lower" and Dealthis > Dealthisagain:
from cards import Card, Deck from hand import Hand from hit_stand import hit, hit_or_stand, show_some_cards, show_all_cards playing = True player_chips = chips() while True: print('WELCOME TO BLACKJACK') deck = Deck() deck.shuffle() player = Hand() player.add_cards(deck.deal()) player.add_cards(deck.deal()) dealer = Hand() dealer.add_cards(deck.deal()) dealer.add_cards(deck.deal()) #bet(player_chips) show_some_cards(player, dealer) while playing: hit_or_stand(deck, player) bet(player_chips)
def take_bet(chips, player, dealer, deck): """ :param chips: :param player: :param dealer: :param deck: :return: """ bj_settings = Settings() if chips < 5: gf.game_over() bets_placed = False pygame.display.set_caption("Blackjack Place your Bet") bj_settings.screen.fill(bj_settings.GREEN) # text setting font_obj = pygame.font.Font('freesansbold.ttf', 40) text_surface_obj = font_obj.render("Place your bet", True, bj_settings.BLACK, bj_settings.GREEN) text_rect_obj = text_surface_obj.get_rect() text_rect_obj.center = (int(bj_settings.screen_width * .5), int(bj_settings.screen_height * .050)) # text setting font_obj1 = pygame.font.Font('freesansbold.ttf', 32) text_surface_obj1 = font_obj1.render("CHIPS " + str(chips), True, bj_settings.BLACK, bj_settings.GREEN) text_rect_obj1 = text_surface_obj1.get_rect() text_rect_obj1.center = (int(bj_settings.screen_width * .5), int(bj_settings.screen_height * .150)) # draw text to screen bj_settings.screen.blit(text_surface_obj, text_rect_obj) bj_settings.screen.blit(text_surface_obj1, text_rect_obj1) # bet 5 button bet_5_pos = (100, 300) bet_5 = pygame.image.load('images/5.png') bet_5_rect = bet_5.get_rect() bet_5_rect.topleft = bet_5_pos # bet 10 button bet_10_pos = (300, 150) bet_10 = pygame.image.load('images/10.png') bet_10_rect = bet_10.get_rect() bet_10_rect.topleft = bet_10_pos # bet 25 button bet_25_pos = (500, 300) bet_25 = pygame.image.load('images/25.png') bet_25_rect = bet_25.get_rect() bet_25_rect.topleft = bet_25_pos # bet 50 button bet_50_pos = (700, 150) bet_50 = pygame.image.load('images/50.png') bet_50_rect = bet_50.get_rect() bet_50_rect.topleft = bet_50_pos # bet 100 button bet_100_pos = (900, 300) bet_100 = pygame.image.load('images/100.png') bet_100_rect = bet_100.get_rect() bet_100_rect.topleft = bet_100_pos # draw chip buttons on screen bj_settings.screen.blit(bet_5, bet_5_rect) bj_settings.screen.blit(bet_10, bet_10_rect) bj_settings.screen.blit(bet_25, bet_25_rect) bj_settings.screen.blit(bet_50, bet_50_rect) bj_settings.screen.blit(bet_100, bet_100_rect) pygame.display.update() # get events while not bets_placed: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: if bet_5_rect.collidepoint(event.pos): if chips >= 5: bet = 5 bets_placed = True if bet_10_rect.collidepoint(event.pos): if chips >= 10: bet = 10 bets_placed = True if bet_25_rect.collidepoint(event.pos): if chips >= 25: bet = 25 bets_placed = True if bet_50_rect.collidepoint(event.pos): if chips >= 50: bet = 50 bets_placed = True if bet_100_rect.collidepoint(event.pos): if chips >= 100: bet = 100 bets_placed = True while bets_placed is True: deck = Deck() deck.shuffle() player.add_card(deck.deal()) player.add_card(deck.deal()) dealer.add_card(deck.deal()) dealer.add_card(deck.deal()) award = ph.play_hand(bet, chips, player, dealer, deck) chips += award pygame.display.update() take_bet(chips, player, dealer, deck)
def blackjackGame(player_name): deck = Deck() deck.shuffle() player = BlackjackHand(player_name) dealer = BlackjackHand('Dealer') deck.deal(dealer, 2) deck.deal(player, 2) print print status(dealer) status(player) if player.isaBlackjack() == True or player.isaBust() == True: choice = 0 if player.isaBust() == False: out = player.getLabel() + ", type 1 for a hit and 0 to stay >> " choice = raw_input(out) while choice != '1' and choice != '0': out = player.getLabel() + ", type 1 for a hit and 0 to stay >> " choice = raw_input(out) choice = int(choice) while dealer.isaBust() == False and player.isaBust() == False \ and (choice == 1 or dealer.total() < 17): while choice == 1: deck.deal(player, 1) print player.getLabel(), " hand: (", player.total(), "): ", player if player.isaBlackjack(): print "That's Blackjack!" choice = 0 elif player.isaBust(): print "That is a Bust!" choice = 0 else: choice = raw_input(out) while choice != '1' and choice != '0': choice = raw_input(out) choice = int(choice) print print player.getLabel(), " total is ", player.total(), " and ", \ dealer.getLabel(), " total is ", dealer.total(), ". " if player.isaBust(): print player.getLabel(), " went bust and loses the hand." print print dealer.getLabel(), "'s turn. Type any key to continue. " key = raw_input() if dealer.total() >= 17: print dealer.getLabel(), " stays with ", dealer.total() else: print dealer.getLabel(), " takes a hit. " deck.deal(dealer, 1) status(dealer) key = raw_input() while dealer.total() < 17: print dealer.getLabel(), " takes a hit. " deck.deal(dealer, 1) status(dealer) key = raw_input() print print player.getLabel(), " total is ", player.total(), " and ", \ dealer.getLabel(), " total is ", dealer.total(), ". " if dealer.isaBust(): print dealer.getLabel(), " went bust and loses the hand." print print player.getLabel(), "'s turn. Type any key to continue. " key = raw_input() if player.isaBust() == True and dealer.isaBust() == True: out = player.getLabel() + ", press any key to continue. " elif player.isaBlackjack() == False and player.isaBust() == False: out = player.getLabel() + ", type 1 for a hit and 0 to stay >> " choice = raw_input(out) while choice != '1' and choice != '0': out = player.getLabel() + ", type 1 for a hit and 0 to stay >> " choice = raw_input(out) choice = int(choice) print print print " ~~ Game Over! ~~ " print print player.getLabel(), " has ", player.total(), ". " print dealer.getLabel(), " has ", dealer.total(), ". " print if player.isaBust(): print player.getLabel(), " went bust. " print dealer.getLabel(), " wins this hand! " elif dealer.isaBust(): print dealer.getLabel(), " went bust. " print player.getLabel(), " wins this hand! " else: if dealer > player: print dealer.getLabel(), " wins this hand! " elif dealer < player: print player.getLabel(), " wins this hand! " else: print "It's a draw! "
if owner.isaBlackjack(): print "That's Blackjack!" elif owner.isaBust(): print "That is a Bust!" print "\t\t\t Caesar - Todor's Palace" print "\t\t\t ***********************" deck = Deck() deck.shuffle() dealer = BlackjackHand('Dealer') player_name = raw_input(" Please enter your name: ") player = BlackjackHand(player_name) deck.deal(dealer, 2) deck.deal(player, 2) print print status(dealer) status(player) if player.isaBlackjack() == True or player.isaBust() == True: choice = 0 if player.isaBust() == False: out = player.getLabel() + ", type 1 for a hit and 0 to stay >> " choice = input(out) while dealer.isaBust() == False and player.isaBust() == False \ and (choice == 1 or dealer.total() < 17):
class Game(object): """ Handler for the game progress. """ # Messages __str_cards = "Tableau:\n%s\n\nDiscards: %4s %4s %4s %4s\n" __str_option_draw = "d - draw a card" __str_option_simple = "s - simple calculation" __str_option_advanced = "a - advanced calculation" __str_option_quit = "q - quit" __str_choose = "Choose an option" __str_options_all = "%s: %s, %s, %s, %s: " % (__str_choose, __str_option_draw, __str_option_simple, __str_option_advanced, __str_option_quit) __str_options_short = "%s: %s, %s, %s: " % (__str_choose, __str_option_simple, __str_option_advanced, __str_option_quit) __str_calc_simple = "The total score (simple algorithm) is: %2s" __str_calc_advanced = "The total score (advanced algorithm) is: %2s" __str_card_dealt = "Card dealt: %4s" __str_choose_loc = "Choose location (1 - 20) to place the new card: " # Error messages __str_err_nint = "Error: input is not an integer" __str_err_oor = "Error: input is out of range" __str_err_pos_full = "Error: a card was already placed in this spot" __str_err_invalid_choice = "Error: an invalid choice was made" # Options for the player __option_quit = "Qq" __option_deal = "Dd" __option_calc_simple = "Ss" __option_calc_advanced = "Aa" def __init__(self): """ Initializes the game """ self._deck = Deck() self._deck.shuffle() self._tableau = Tableau() def play(self): """ Starts the game """ self._print_cards() while True: # Ask user what to do if self._tableau.is_full(): inp = raw_input(self.__str_options_short) else: inp = raw_input(self.__str_options_all) if len(inp) == 0: print self.__str_err_invalid_choice elif inp in self.__option_quit: break elif inp in self.__option_deal: self._play_step() print self._print_cards() elif inp in self.__option_calc_simple: print self.__str_calc_simple % \ self._tableau.calc_score_simple() elif inp in self.__option_calc_advanced: print self.__str_calc_advanced % \ self._tableau.calc_score_advanced() else: print self.__str_err_invalid_choice def _print_cards(self): """ Prints the game board and discards """ discards = tuple(self._tableau[self._tableau.board_end + 1: self._tableau.end + 1]) print self.__str_cards % ((self._tableau,) + discards) def _play_step(self): """ One step of the game - deal card and place it """ card = self._deck.deal() print self.__str_card_dealt % card pos = self._get_pos_from_user() self._tableau[pos] = card def _get_pos_from_user(self): """ Get a (valid) board position from the user """ while True: # Iterate until value is valid inp = raw_input(self.__str_choose_loc) try: pos = int(inp) except ValueError: print self.__str_err_nint continue if pos < self._tableau.start or pos > self._tableau.end: print self.__str_err_oor continue if self._tableau.pos_full(pos): print self.__str_err_pos_full continue return pos
#runs script of modified version of highlow game from cards import Deck from cards import Card deck = Deck() deck.shuffle() print("Here is your card:") first =deck.deal() print(str(first)) print("Will the next card be higher or lower?") last = deck.deal() guess = input(">" ) if guess.lower() == "higher": if first > last: print("You guessed wrong.") else: print("Ding Ding Ding") if guess.lower() == "lower": if first > last: print("You guessed right") else: print("wrong answer bud") print("the final card was " + str(last))
from cards import Card, Deck, Hand, Chips from game_functions import * while True: # Print an opening statement print( 'Welcome to BlackJack! Get as close to 21 as you can without going over!\n\ Dealer hits until she reaches 17. Aces count as 1 or 11.') deck = Deck() deck.shuffle() player_hand = Hand() player_hand.add_cards(deck.deal()) player_hand.add_cards(deck.deal()) dealer_hand = Hand() dealer_hand.add_cards(deck.deal()) dealer_hand.add_cards(deck.deal()) # set up players ships player_chips = Chips() take_bet(player_chips) show_some(player_hand, dealer_hand) hit_or_stand(deck, player_hand) show_some(player_hand, dealer_hand)
num_player = 1 dealer = Player(name='dealer') players = [Player(name=f'p{i}') for i in range(num_player)] # Game session # each player place bet player_bets = [10] # shuffle deck deck = Deck(is_shuffle=True) # deal 1 card each player including dealer hands = 2 for i in range(hands): for p in players: deck.deal(p.hand, 1) deck.deal(dealer.hand, 1) # check for player and dealer pokdeng # session end if dealer pokdeng # ask whether player will add one more card # dealer decide to take one more cards # check all cards and play bet # %% # %%
def run_game(): #Initialize pygame screen and font modules pygame.init() pygame.font.init() #variables to determine round and statistics round_over = 0 round_counter = 1 wins = 0 losses = 0 #ratio = wins // losses #create the title title = gf.create_text("Blackjack", font_preferences, 42, font_color) #create lists to be used later in the game discard_pile = [] deck = [] player = [] dealer = [] #generate card elements and variables, then generate list deck_icon = Deck(screen, (table_settings.table_width // 2), (table_settings.table_height // 2) - 10) deck = Deck.createDeck() deck, discard_pile, player, dealer = Deck.deal(deck, discard_pile) #variable to define printed text and keep active within loop text = None text_placement = textbox_settings.y_pos + 5 # Start the main loop for the game while True: #variables for mouse coordinates mouse_X = 0 mouse_Y = 0 #redraw the screen with elements during each pass through the loop screen.fill(ai_settings.bg_color) screen_pieces.draw() screen.blit( title, ((sidebar_settings.x_pos + sidebar_settings.sidebar_quartered) - 20, 20)) deck_icon.blitme() #generate statistic text round = gf.create_text("Round: " + str(round_counter), font_preferences, 28, font_color) screen.blit( round, ((sidebar_settings.x_pos + sidebar_settings.sidebar_quartered) - 20, 80)) stats = gf.create_text( "Wins: " + str(wins) + " | " + "Losses: " + str(losses), font_preferences, 24, font_color) screen.blit( stats, ((sidebar_settings.x_pos + sidebar_settings.sidebar_quartered) - 20, 120)) if round_counter != 1 and losses != 0: ratio = 100 * float(wins) / float(losses) stats = gf.create_text( "W/L Ratio: " + str("{0:.2f}".format(ratio)) + " %", font_preferences, 24, font_color) screen.blit(stats, ( (sidebar_settings.x_pos + sidebar_settings.sidebar_quartered) - 20, 150)) #draw the cards for the dealer and player Deck.drawCurrentHand(screen, player, dealer, table_offset, table_settings.y_pos, table_settings.table_height, round_over) #print message to user on current status gf.textbox_message(screen, round_over, text, font_preferences, textbox_font_size, font_color, space_offset, text_placement, player) #check events for exit signal message = gf.check_events() #retrieve and keep text on screen of last event if message != None: #set click to 1 (used in next elif) and grabs the x and y coordinates pressed click = 1 mouse_X, mouse_Y = message.split('|') #detect and respond if there is blackjack on start of round if len(player) == 2 and len(dealer) == 2 and round_over == 0: text, round_over, wins, losses = gf.blackjack( player, dealer, text, round_over, wins, losses) #responds when user hits the double button deck, discard_pile, player, dealer, round_over, text, wins, losses = doubleButton.update( mouse_X, mouse_Y, deck, discard_pile, player, dealer, round_over, text, wins, losses) #responds when user hits the stand button round_over, text, deck, discard_pile, dealer, player, wins, losses = standButton.update( mouse_X, mouse_Y, round_over, player, dealer, text, deck, discard_pile, wins, losses) #responds when user hits the hit button deck, discard_pile, player, round_over, text, losses = hitButton.update( mouse_X, mouse_Y, deck, discard_pile, player, round_over, text, losses) #responds when user hits the deal button round_over, round_counter, deck, discard_pile, player, dealer = dealButton.update( mouse_X, mouse_Y, deck, discard_pile, player, dealer, round_over, round_counter) #draw start of round buttons to screen if round_over == 0 and len(player) == 2: in_round_buttons_DbAllow.draw(screen) #draw buttons after first hit elif round_over == 0 and len(player) > 2: in_round_buttons_DbDeny.draw(screen) #draw buttons for end of round else: out_of_round_buttons.draw(screen) # Make the most recently drawn screen visible pygame.display.flip()