def create_new_deck(paths): if len(paths) < 1: raise ValueError("Unable to create deck: no packs given") deck = Deck(paths) header = None category = None for path in paths: with open(path, 'r') as f: for i, line in enumerate(f): # Anything after a # is considered a comment and discarded. line = line.split('#')[0].strip() if not line: continue # "[-header-]" is the kind of line we're looking for here. if line[0] == '[' and line[-1] == ']': if line[1] == line[-2] == '-': category = 'base' elif line[1] == line[-2] == '^': category = 'subs' else: print("error") return header = line[2:-2] continue # Watch out for formatting errors. elif category is None or header is None: # Found a card without any headers. print("error") return if header not in deck.__dict__[category].keys(): deck.__dict__[category][header] = {} (text, rating) = line.split(':') # TODO: more elegant way of doing this rating = rating.strip() try: r_value = util.rating_value(rating.strip()) except ValueError: print("error") return else: deck.__dict__[category][header][text.strip()] = r_value compile_deck(deck) shuffle_deck(deck) return deck
def setupRound(self): ''' Setup the round by doing these steps: Call getBet to initialize self.bet, initialize self.deck to a new Deck object and shuffle it initialize self.dealerHand and self.playerHand to new Hand objects deal two cards to the playerHand, and one card to the dealerHand finally, print dealerHand and playerHand using displayCards method ''' self.getBet() self.deck = Deck() self.deck.shuffle() self.dealerHand = Hand() self.playerHand = Hand() self.dealerHand.addCard(self.deck.dealCard()) self.playerHand.addCard(self.deck.dealCard()) self.playerHand.addCard(self.deck.dealCard()) Blackjack.displayCards(self, self.dealerHand, "Dealer") Blackjack.displayCards(self, self.playerHand, "Player")
def yes_game(context, data, chat_id, dp): chat_data = dp.chat_data[chat_id] lang = data["lang"] group_settings = data["group_settings"] deck = Deck(*group_settings["deck"].split("_")) chameleon = random.choice(list(data["players"])) random.shuffle(data["players"]) game_id = ''.join(random.choices(string.ascii_lowercase, k=10)) chat_data.update({"chameleon": chameleon, "secret": deck.secret, "players": data["players"], "lang": lang, "starter": data["starter"], "words": deck.words, "game_id": game_id, "fewer": group_settings["fewer"], "tournament": group_settings["tournament"], "more": group_settings["more"], "pin": group_settings["pin"], "restrict": {}, "deck": group_settings["deck"], "tutorial": data["tutorial"], "exclamation": group_settings["exclamation"]}) text = get_string(lang, "game_succeed").format(deck.topic, deck.word_list) button = InlineKeyboardMarkup([[InlineKeyboardButton(get_string(lang, "play_button"), callback_data="word" + game_id)]]) message = context.bot.send_message(chat_id, text, reply_to_message_id=data["message"], reply_markup=button, parse_mode=ParseMode.HTML) chat = None if group_settings["pin"] or group_settings["restrict"]: chat = context.bot.get_chat(chat_id) if group_settings["pin"]: pinned_message = chat.pinned_message if pinned_message: chat_data["pin"] = pinned_message.message_id try: context.bot.pin_chat_message(chat_id, message.message_id, True) except BadRequest as e: if e.message == "Not enough rights to pin a message": chat_data["pin"] = False database.insert_group_pin(chat_id) e.message += "handled in ghelper L48" raise e user = data["players"][0] text = get_string(lang, "first_player_say_word").format(mention_html(user["user_id"], user["first_name"])) if not group_settings["restrict"]: if group_settings["exclamation"]: text += "\n\n" + get_string(lang, "exclamation_activated") else: text += "\n\n" + get_string(lang, "exclamation_deactivated") context.bot.send_message(chat_id, text, reply_to_message_id=message.message_id, parse_mode=ParseMode.HTML) if group_settings["restrict"]: chat_data["restrict"]["initial_permissions"] = chat.permissions try: context.bot.set_chat_permissions(chat_id, ChatPermissions(can_send_messages=False)) if not is_admin(context.bot, user["user_id"], chat): context.bot.promote_chat_member(chat_id, user["user_id"], can_invite_users=True) chat_data["restrict"]["skip"] = False else: chat_data["restrict"]["skip"] = True except BadRequest as e: chat_data["restrict"] = False database.insert_group_restrict(chat_id) e.message += "handled in ghelper L68" raise e chat_data["word_list"] = message.message_id
def main(): print("Cards - Tester") print() #test sorting of the cards testcardsList = [ Card("Spades", "Ace"), Card("Hearts", "Queen"), Card("Clubs", "10"), Card("Diamonds", "3"), Card("Hearts", "Jack"), Card("Spades", "7") ] testcardsList.sort() print("TEST CARDS LIST AFTER SORTING.") for c in testcardsList: print(c) print() # test deck print("DECK") deck = Deck() print("Deck created.") deck.shuffle() print("Deck shuffled.") print("Deck count:", len(deck)) print() # test hand hand = Hand() for i in range(10): hand.addCard(deck.dealCard()) print("SORTED HAND") for c in sorted(hand): print(c) print() print("Hand points:", hand.points) print("Hand count:", len(hand)) print("Deck count:", len(deck))
def find_deck(con, deck_id): sql = """ SELECT * FROM all_decks WHERE id = ? """ try: cur = con.cursor() cur.execute(sql, [deck_id]) res = cur.fetchone() deck = Deck(res[0], res[1], res[2], res[3], res[4], res[5]) return deck except: raise RuntimeWarning("Deck not found")
def game_end(context, text, chat_id, chameleon_id, winner_ids, lang): chat_data = context.chat_data players = chat_data["players"] context.bot.send_message(chat_id, text, parse_mode=ParseMode.HTML, reply_markup=ReplyKeyboardRemove()) context.bot.edit_message_reply_markup(chat_id, chat_data["word_list"], reply_markup=None) player_ids = [] for player in players: player_ids.append(player["user_id"]) if chat_data["tournament"]: tournament = chat_data["tournament"] # first game of tournament if not isinstance(tournament, dict): database.end_game(chat_id, player_ids, chameleon_id, winner_ids, chat_data["starter"]["user_id"]) tournament = {} for player_id in player_ids: tournament[player_id] = 0 else: database.end_game(chat_id, player_ids, chameleon_id, winner_ids) # that means the chameleon won if len(winner_ids) == 1: # that means the chameleon had to guess, but won, so gets a point, no one else does if "guesses" in chat_data: tournament[chameleon_id] += 1 # that means the chameleon escaped undetected, so gets two points else: tournament[chameleon_id] += 2 # that means everyone else won, they get two points else: for user_id in winner_ids: if user_id is not chameleon_id: tournament[user_id] += 2 tournament_winners = [] for user_id in tournament: if tournament[user_id] >= 5: tournament_winners.append(user_id) # that means we have winner(s), the tournament is over if tournament_winners: database.end_tournament(chat_id, player_ids, tournament_winners) if len(tournament_winners) == 1: winner_mention = None contestant_mentions_points = [] for player in players: if player["user_id"] in tournament_winners: winner_mention = mention_html(player["user_id"], player["first_name"]) else: contestant_mentions_points.append( f"{mention_html(player['user_id'], player['first_name'])}: " f"<b>{tournament[player['user_id']]}</b>") text = get_string(lang, "tournament_end_one").format( winner_mention, tournament[tournament_winners[0]], "\n".join(contestant_mentions_points)) else: winner_mention_points = [] contestant_mentions_points = [] for player in players: if player["user_id"] in tournament_winners: winner_mention_points.append( f"{mention_html(player['user_id'], player['first_name'])}: " f"<b>{tournament[player['user_id']]}</b>") else: contestant_mentions_points.append( f"{mention_html(player['user_id'], player['first_name'])}: " f"<b>{tournament[player['user_id']]}</b>") text = get_string(lang, "tournament_end_several").format( "\n".join(winner_mention_points), "\n".join(contestant_mentions_points)) context.bot.send_message(chat_id, text, parse_mode=ParseMode.HTML) if chat_data["pin"]: if not isinstance(chat_data["pin"], bool): try: context.bot.pin_chat_message(chat_id, chat_data["pin"], True) except BadRequest as e: if e.message != "Not enough rights to pin a message": context.bot.unpin_chat_message(chat_id) e.message += "handled in game L363" else: chat_data["pin"] = False e.message += "handled in game L363, 2" raise e else: context.bot.unpin_chat_message(chat_id) chat_data.clear() chat_data["lang"] = lang # that means we dont, lets play another round else: chat_data["tournament"] = tournament for player in chat_data["players"]: player.pop("word", None) player.pop("votes", None) deck = Deck(chat_data["deck"]) chameleon = random.choice(list(chat_data["players"])) chat_data["players"] = chat_data["players"][1:] + [ chat_data["players"][0] ] game_id = ''.join(random.choices(string.ascii_lowercase, k=10)) chat_data.update({ "chameleon": chameleon, "secret": deck.secret, "game_id": game_id, "words": deck.words }) contestant_mentions_points = [] for player in players: contestant_mentions_points.append( f"{mention_html(player['user_id'], player['first_name'])}: " f"<b>{tournament[player['user_id']]}</b>") text = get_string(lang, "tournament_end").format( "\n".join(contestant_mentions_points), deck.topic, deck.word_list) button = InlineKeyboardMarkup([[ InlineKeyboardButton(get_string(lang, "play_button"), callback_data="word" + game_id) ]]) send_message = context.bot.send_message(chat_id, text, reply_markup=button, parse_mode=ParseMode.HTML) if chat_data["pin"]: context.bot.pin_chat_message(chat_id, send_message.message_id, True) user = chat_data["players"][0] text = get_string(lang, "first_player_say_word").format( mention_html(user["user_id"], user["first_name"])) if not chat_data["restrict"]: text += "\n\n" + get_string(lang, "say_word_not_restricted") context.bot.send_message( chat_id, text, reply_to_message_id=send_message.message_id, parse_mode=ParseMode.HTML) if chat_data["restrict"]: context.bot.set_chat_permissions( chat_id, ChatPermissions(can_send_messages=False)) if not is_admin(context.bot, user["user_id"], context.bot.get_chat(chat_id)): context.bot.promote_chat_member(chat_id, user["user_id"], can_invite_users=True) chat_data["restrict"]["skip"] = False else: chat_data["restrict"]["skip"] = True chat_data["word_list"] = send_message.message_id # we dont care if other values exist or not, but this is needed in calculating of our points, so we pop it chat_data.pop("guesses", None) chat_data.pop("voted", None) else: database.end_game(chat_id, player_ids, chameleon_id, winner_ids, chat_data["starter"]["user_id"]) if chat_data["pin"]: if not isinstance(chat_data["pin"], bool): try: context.bot.pin_chat_message(chat_id, chat_data["pin"], True) except BadRequest as e: if e.message != "Not enough rights to pin a message": context.bot.unpin_chat_message(chat_id) e.message += "handled in game L419" else: chat_data["pin"] = False e.message += "handled in game L419, 2" raise e else: context.bot.unpin_chat_message(chat_id) chat_data.clear() chat_data["lang"] = lang
def __init__(self, startingBalance): self.money = startingBalance self.deck = Deck() self.playerHand = Hand() self.dealerHand = Hand() self.bet = 0
class Blackjack: def __init__(self, startingBalance): self.money = startingBalance self.deck = Deck() self.playerHand = Hand() self.dealerHand = Hand() self.bet = 0 def displayCards(self, hand, title): ''' Print the title and display the cards in the given hand in a sorted order''' print(title.upper()) for c in sorted(hand): print(c) print() def handle_winner(self, winner, message): ''' print the player's hand's points print the message Update self.money according to the winner ''' print("Your Points: ", self.playerHand.points) print("Dealer Points: ", self.dealerHand.points) print(message) if winner == "player": print("foo", self.money, self.bet) self.money += self.bet elif winner == "dealer": self.money -= self.bet elif winner == "tie": pass elif winner == "blackjack": self.money += (1.5 * self.bet) def getBet(self): ''' Method to update self.bet by prompting the user for the bet amount, making sure bet is less than self.money. ''' while True: try: bet = int(input("What is your bet: ")) if bet <= self.money and bet > 0: self.bet = bet return False elif bet > self.money: print("You don't have that much money") except ValueError: print("You must enter a positive number!") def setupRound(self): ''' Setup the round by doing these steps: Call getBet to initialize self.bet, initialize self.deck to a new Deck object and shuffle it initialize self.dealerHand and self.playerHand to new Hand objects deal two cards to the playerHand, and one card to the dealerHand finally, print dealerHand and playerHand using displayCards method ''' self.getBet() self.deck = Deck() self.deck.shuffle() self.dealerHand = Hand() self.playerHand = Hand() self.dealerHand.addCard(self.deck.dealCard()) self.playerHand.addCard(self.deck.dealCard()) self.playerHand.addCard(self.deck.dealCard()) Blackjack.displayCards(self, self.dealerHand, "Dealer") Blackjack.displayCards(self, self.playerHand, "Player") def play_playerHand(self): ''' Method to implement player playing his hand by 1. Prompting the user to indicate Hit (h) or Stand (s) 2. If user picks stand, end the player play by returning 3. If user picks hit, deal a card to the playerHand. check if with the latest addition, the hand busts (has > 21 points), if so return otherwise, prompt the player again whether to hit or stand. 4. Print playerHand points ''' while True: pick = input('\nPress "h" to hit or "s" to stand: ') if pick.lower() == "h": self.playerHand.addCard(self.deck.dealCard()) Blackjack.displayCards(self, self.playerHand, "Player Hand") if self.playerHand.points > 21: return False else: continue elif pick.lower() == "s": return False else: print("Not a valid command! Please try again.") def play_dealerHand(self): ''' Method to play the dealer's hand. Continue to deal cards till the points of the dealerHand are less than 17. Print the dealer's hand before returning''' dealerHandValue = self.dealerHand.points while dealerHandValue < 17: self.dealerHand.addCard(self.deck.dealCard()) dealerHandValue = self.dealerHand.points Blackjack.displayCards(self, self.dealerHand, "Dealer") def playOneRound(self): ''' Method implements playing one round of the game 1. Checks if playerHand is a Blackjack, if so handles that case 2. Lets player play his hand if it busts, declares player loser 3. Else lets dealer play his hand. 4. If dealer busts, declares the player to be the winner 5. Otherwise declares the winner based on who has higher points: if Player > dealer, player is the winner else if player < dealer, dealer is the winner else it is a tie ''' playerHandValue = self.playerHand.points if playerHandValue == 21: Blackjack.handle_winner(self, "blackjack", "You got Blackjack!") else: Blackjack.play_playerHand(self) playerHandValue = self.playerHand.points if playerHandValue > 21: Blackjack.handle_winner(self, "dealer", "You went bust!") else: Blackjack.play_dealerHand(self) dealerHandValue = self.dealerHand.points if dealerHandValue > 21: Blackjack.handle_winner(self, "player", "Dealer went bust, you win!") elif playerHandValue > dealerHandValue: Blackjack.handle_winner(self, "player", "You win!") elif playerHandValue < dealerHandValue: Blackjack.handle_winner(self, "dealer", "You lose!") elif playerHandValue == dealerHandValue: Blackjack.handle_winner(self, "tie", "It's a tie!")
def create_deck(con, creator, name, descr): deck = Deck(creator=creator, name=name, descr=descr) deck.id = db_utils.insert_deck(con, deck) return deck
def main(): print("Blackjack\n") print("Blackjack payout is 3:2\n") money = 0.0 start = datetime.now() print("Start time: " + start.strftime("%I:%M:%S %p")) result = lc.setlocale(lc.LC_ALL, "") if result == "C": lc.setlocale(lc.LC_ALL, "en_US") while True: player = 0 dealer = 0 dealerHand = [] playerHand = [] card = Card() deck = Deck(card.getSuits(), card.getRanks()) deck.shuffle() d = deck.getDeck() number = random.randint(0, len(d)) # shows player money, lets them bet and ends if no money money = Money() money = money.getMoney() if money < 5: choice = input("Buy more chips? (y/n): ") if choice == "y": chips = float(input("Enter amount: ")) elif choice == "n": break localeMoney = Decimal(money) localeMoney = localeMoney.quantize(Decimal("1.00")) print("Money: " + lc.currency(localeMoney, grouping=True)) bet = float(input("Bet amount: ")) if bet < 5: print("Bet must be greater than $5") break elif bet > 1000: print("Bet must be less than $1000") break # shows dealer card and adds it to dealerHand print("DEALER'S SHOW CARD:") print(str(d[number][0]) + " of " + d[number][1]) dealer += cardCount(d[number][0]) dealerHand.append(d[number]) d.pop(number) print() # shows player's cards and adds them to playerHand print("YOUR CARDS:") for x in range(2): number = random.randint(0, len(d)) print(str(d[number][0]) + " of " + d[number][1]) player += cardCount(d[number][0]) playerHand.append(d[number]) d.pop(number) print() # determines if blackjack, if not, then player has a chance to hit or stand before dealer if dealer == 21: print("Dealer blackjack!") elif player == 21: print("Player blackjack") elif player < 21: choice = input("Hit or stand? (hit/stand): ") print() while player < 21 and choice == "hit": number = random.randint(0, len(d)) playerHand.append(d[number]) player += cardCount(d[number][0]) d.pop(number) print("YOUR CARDS:") for x in playerHand: print(str(x[0]) + " of " + x[1]) print() if player > 21: break choice = input("Hit or stand? (hit/stand): ") # Makes dealer draw cards until they have 17 points or until dealer has more points while dealer < 17: number = random.randint(0, len(d)) dealerHand.append(d[number]) dealer += cardCount(d[number][0]) while dealer < player: number = random.randint(0, len(d)) dealerHand.append(d[number]) dealer += cardCount(d[number][0]) # displays both hands and results print("DEALER'S CARDS:") for x in dealerHand: print(str(x[0]) + " of " + x[1]) print() print("YOUR POINTS:\t " + str(player)) print("DEALER'S POINTS: " + str(dealer)) print() with open("money.txt", "w", newline="") as file: end = datetime.now() if player > 21: print("Player busted! House always wins!") diff = money - bet ph = money money = round(money - bet, 2) localeMoney = Decimal(money) localeMoney = localeMoney.quantize(Decimal("1.00")) print("Money: " + lc.currency(localeMoney, grouping=True)) file.write(str(money)) elif dealer > 21: print("Dealer busted! Cash out, you're done at my tables") diff = money - bet ph = money money = round((bet * 1.5) + money, 2) localeMoney = Decimal(money) localeMoney = localeMoney.quantize(Decimal("1.00")) print("Money: " + lc.currency(localeMoney, grouping=True)) file.write(str(money)) elif player <= dealer: print("Player lost! Better luck next time, pal!") ph = money diff = money - bet money = round(money - bet, 2) localeMoney = Decimal(money) localeMoney = localeMoney.quantize(Decimal("1.00")) print("Money: " + lc.currency(localeMoney, grouping=True)) file.write(str(money)) print() choice = input("Play again? (y/n): ") if choice == "n": end = datetime.now() print("Stop time: " + end.strftime("%I:%M:%S %p")) hour = end.hour - start.hour minute = end.minute - start.minute second = end.second - start.second print("Elapsed time: " + str(hour) + ":" + str(minute) + ":" + str(second)) break
def main(): start_time = datetime.now() display_title(start_time) # get starting money money = get_starting_money() print("Money:", lc.currency(money, grouping=True)) # start loop while True: # make sure player has enough money for min bet if money < 5: print("You are out of money.") buy_more = input( "Would you like to buy more chips? (y/n): ").lower() if buy_more == "y": money = buy_more_chips(money) print("Money:", lc.currency(money, grouping=True)) db.write_money(money) else: break # get bet amount bet = get_bet(money) print() deck = Deck() deck.shuffle() dealer_hand = Hand() player_hand = Hand() # deal two cards to player and one to the dealer player_hand.addCard(deck.dealCard()) player_hand.addCard(deck.dealCard()) dealer_hand.addCard(deck.dealCard()) # display cards display_cards(dealer_hand, "DEALER'S SHOW CARD: ") display_cards(player_hand, "YOUR CARDS: ") # get player hand player_hand = play(deck, player_hand) # get dealer hand while dealer_hand.points() < 17: dealer_hand.addCard(deck.dealCard()) display_cards(dealer_hand, "DEALER'S CARDS: ") print("YOUR POINTS: " + str(player_hand.points())) print("DEALER'S POINTS: " + str(dealer_hand.points())) print() # check result of hand player_points = player_hand.points() dealer_points = dealer_hand.points() if player_points > 21: print("Sorry. You busted. You lose.") money -= bet elif dealer_points > 21: print("Yay! The dealer busted. You win!") money += bet else: if player_points == 21 and len(player_hand) == 2: if dealer_points == 21 and len(dealer_hand) == 2: print("Dang, dealer has blackjack too. You push.") else: print("Blackjack! You win!") money += bet * 1.5 elif player_points > dealer_points: print("Hooray! You win!") money += bet elif player_points == dealer_points: print("You push.") elif player_points < dealer_points: print("Sorry. You lose.") money -= bet else: print("I am not sure what happened.") # display new money amount money = round(money, 2) print("Money:", lc.currency(money, grouping=True)) print() # write money to file db.write_money(money) again = input("Play again? (y/n): ").lower() print() if again != "y": break # get stop time stop_time = datetime.now() display_end(start_time, stop_time)
game_on = True ######## GAME LOGIC print("LET'S PLAY POKER!") player_chips = Chips() # create chips computer_chips = player_chips while game_on: playing = input("Would you like to play a round of poker? Y/N ").upper() if playing == "Y": while True: # start new round pot = Pot() # start the pot game_deck = Deck() # create deck game_deck.shuffle() # deal player's, computer's and table's cards player = Player() player.add_card(game_deck.deal()) player.add_card(game_deck.deal()) player_bets = 0 computer = Computer() computer.add_card(game_deck.deal()) computer.add_card(game_deck.deal()) table = Table() i = 0 while i != 3: