def read_xml_file(fname): """ Reads in .xml/.cod file to Deck object. Assumes Cockatrice export formatting Args: fname (str): filename containing deck information. Unlike other functions, cannot be Path object as minidom has difficulty reading in Returns: (Deck) """ p = Path(fname) xmldoc = minidom.parse(fname) card_xml = xmldoc.getElementsByTagName("card") # build Deck object card_list = [] errors = [] for c in card_xml: card_name = c.attributes["name"].value card_count = int(c.attributes["number"].value) try: cclass = fetch_card_data(card_name, card_count) card_list.append(cclass) except KeyError: # if any cards don't exist, save in errors errors.append(card_name) return Deck(p.stem, card_list)
def play_game(): # Create and shuffle the Draw deck deck = Deck() deck.shuffle() # Create the play stacks stack1 = Stack("ascending") stack2 = Stack("ascending") stack3 = Stack("descending") stack4 = Stack("descending") stacks = [stack1, stack2, stack3, stack4] # Create the starting hands hand1 = Hand() hand1.draw(deck) # While there are still cards in the deck and hand... while deck.cards or hand1.cards: # Get a list of stack states with directions print("The stacks are:") states = [] for stack in stacks: print(str(stack.state) + " " + stack.direction) # Determine how many cards MUST be played if deck.cards: requirement = 2 else: requirement = 1 plays = hand1.play(stacks, requirement) print(f"I was able to play {plays} cards") if plays < requirement: break hand1.draw(deck) print("I have the following cards in hand: " + ", ".join(hand1.cards_as_str())) # The game is over (didn't have enough plays) print("Done") cards_remaining = deck.size() + hand1.size() print(f"The Game ended with {cards_remaining} cards remaining.") if cards_remaining == 0: print("You have won The Game!!") elif cards_remaining < 11: print("You didn't win, but you did really good!") else: print("Sorry, you lost The Game. Better luck next time.") return cards_remaining
def main(): print("Running main.py") d = Deck() hole_cards = d.draw(2) # board = d.draw(5) board = [ Card.from_int(1), Card.from_int(2), Card.from_int(15), Card.from_int(28), Card.from_int(5) ] print(utils.best_hand(hole_cards[0], hole_cards[1], board)) print("Finished main.py")
def split_cards(card, deck): if deck.split is False: deck.cards.remove(card[0]) deck.points = subtract_points(card_value(card[0]), deck.points) new_deck = Deck() new_deck.cards.append(card[0]) new_deck.player = deck.player new_deck.points = card_value(card[0]) new_deck.status = False print("This deck of {0} has split as following: {1}".format( deck.player, deck.cards)) deck.split = True return new_deck return None
def set_up_game(): players = [] amount_of_players = ask_for_amount_of_players() for _ in range(0, amount_of_players): player_name = ask_player_for_name() player = Player(player_name) players.append(player) global deck if amount_of_players > 3: amount_of_decks = int(amount_of_players / 3) # max 3 players per deck deck = Deck(amount_of_decks) bank = Player('The bank') start_round(players, bank)
def __init__(self): self.cells = [] for _ in xrange(4): self.cells.append(Cell()) self.foundations = [] for _ in xrange(4): self.foundations.append(Foundation()) self.cascades = [] for _ in xrange(8): self.cascades.append(Cascade()) # TODO fill cascades with cards deck = Deck() deck.shuffle() for chunk in chunks(deck, 8): for cascade, card in izip(self.cascades, chunk): cascade.append(card)
def __init__(self, natural=False, deck_num=1): self.action_space = spaces.Discrete(3) self.side_space = spaces.Discrete(2) self.observation_space = spaces.Tuple( (spaces.Discrete(32), spaces.Discrete(11), spaces.Discrete(2))) self.seed(0) # Flag to payout 1.5 on a "natural" blackjack win, like casino rules # Ref: http://www.bicyclecards.com/how-to-play/blackjack/ self.natural = natural self.deck = Deck() self.deck.count = 0 # Start the first game self.reset()
def db_to_deck(path): """ Converts sqlite table to Deck object if none previously exists used when loading new deck from table Args: path (Path): path to database file """ p = Path(path) db = sqlite3.connect(p) query_df = pd.read_sql(f"""SELECT name, count FROM {p.stem}""", db) names, counts = list(query_df["name"]), list(query_df["count"]) cards = [] for name, count in zip(names, counts): c = fetch_card_data(name, count) cards.append(c) return Deck(p.stem, cards)
def read_text_file(fname): """ Reads in common text file formats (.txt, .csv, .tsv), to Deck Parsing assumes formatting from tappedout export function Args: fname (str): filename containing deck information Returns: (Deck) """ p = Path(fname) # read fname into df, handle formatting. txt requires preprocessing if (p.suffix == ".txt") or (p.suffix == ".dek"): df = pad_txt_file(p) # read csv/tsv into df, no preprocessing required elif p.suffix == ".csv": df = pd.read_csv(fname) elif p.suffix == ".tsv": df = pd.read_csv(fname, sep="\t") else: sys.exit("Invalid file format") df = df.dropna(subset=["Qty", "Name"]) # get name & qty from df card_names = df["Name"].values.tolist() qty = df["Qty"].values.tolist() # build deck object card_list = [] errors = [] # currently not doing anything with this, may use in future for c, q in zip(card_names, qty): try: card_list.append(fetch_card_data(c, q)) except KeyError: # if any cards don't exist, save in errors errors.append(c) return Deck(p.stem, card_list)
def main(): '''Play game of 2 player blackjack on console.''' p1 = Player() p2 = Player() deck = Deck() p1_turn = True deck.shuffle() p1.hand.cards.append(deck.deal_card()) p2.hand.cards.append(deck.deal_card()) p1.hand.cards.append(deck.deal_card()) p2.hand.cards.append(deck.deal_card()) while not game_over(p1, p2): if p1_turn: if not p1.stay and not p1.blackjack and not p1.bust: print "\n\nPlayer One's Turn!" player_turn(p1, deck) p1_turn = False else: if not p2.stay and not p2.blackjack and not p2.bust: print "\n\nPlayer Two's Turn!" player_turn(p2, deck) p1_turn = True winner = get_winner(p1, p2) if winner is None: print "\nBoth players busted. Tie game!" elif winner == p1: print "\nPlayer One wins!" elif winner == p2: print "\nPlayer Two wins!" else: print "\nIt's a tie!" print "Game Over!"
def query_db(path, query, output="text"): """ Query existing table, save Deck corresponding to new query if id included in query, populate Deck object Args: path (Path|str): path to database file query (str): SQL query to be run output (str): how to output query results - 'text' or 'images' Returns: (Deck): corresponding to query results """ p = Path(path) db = sqlite3.connect(p) query_df = pd.read_sql(query, db) # get Deck object corresponding to query if id in query cards = [] cursor = db.cursor() if "id" in query_df.columns: all_ids = tuple(query_df["id"]) cursor.execute(f"""SELECT name FROM {p.stem} WHERE id IN {all_ids}""") for row in cursor: cards.append(fetch_card_data(row[0], 1)) deck = Deck(query, cards) # handle how to output results of query if output == "text": query_df.to_csv(query + ".csv", sep=" ", index=False) elif output == "images": deck.store_images(query) else: pass return deck
async def deal(self, ctx): target_deck = 1 deck_one = [] deck_two = [] deck = Deck() random.shuffle(deck.contents) for x in deck.contents: if target_deck == 1: deck_one.append(x) target_deck = 2 else: deck_two.append(x) target_deck = 1 else: deck_one_output = "" deck_one.sort(key=lambda y: (y.rank, y.suit)) for i in deck_one: deck_one_output += f"{str(i)}\n" else: await ctx.send(f"Deck 1:\n{deck_one_output}") return [deck_one, deck_two]
def __init__(self, players, small_blind=1, big_blind=2, dealer_seat=0, debug_level=0): self.debug_level = debug_level self.players = players self.deck = Deck() self.small_blind = small_blind self.big_blind = big_blind self.pot = 0 self.curr_raise = 0 self.num_players_in_hand = len(self.players) self.num_active_players_in_hand = self.num_players_in_hand self.communal_cards = [] self.initiate_round(dealer_seat) utils.out('---------------------------------------', self.debug_level) utils.out( '%s(%d) is dealer.' % (self.players[dealer_seat].name, self.players[dealer_seat].chips), self.debug_level)
# -*- coding: utf-8 -*- """ Created on Tue Dec 29 18:21:16 2020 @author: Samuel """ from classes import Card from classes import Player from classes import Deck player1 = Player(input("Type your name, player1: ")) player2 = Player(input("Type your name, player2: ")) decker = Deck() decker.shuffle() for cd in range(26): player1.increase(decker.deal()) player2.increase(decker.deal()) game_on = True round = 0 while game_on: round += 1 print("Round", round) if (len(player2.allcards) > len(player1.allcards)) and round >= 10000: print("Rounds up!", player1.name, "loses and", player2.name, "wins") game_on = False break
from classes import Player, Card, Deck player_one = Player("One") player_two = Player("Two") new_deck = Deck() new_deck.shuffle_deck() for x in range(26): player_one.add_cards(new_deck.deal_one()) player_two.add_cards(new_deck.deal_one()) game_on = True at_war = False round_num = 0 while game_on: round_num += 1 if len(player_one.all_cards) == 0: print("Player One, out of cards! Player Two Wins!") game_on = False break if len(player_two.all_cards) == 0: print("Player Two, out of cards! Player One Wins!") game_on = False break player_one_cards = []
def create_tables(num_of_tables, num): tables = [] i = 0 while i+1 <= num_of_tables: table = Table() bank = Bank() if i + 1 is num_of_tables: if num%3 == 0: for m in range(3): print("Insert the name of player {}".format(i*3 + m + 1)) name = input() player = Player() player.name = name deck = Deck() player.decks.append(deck) table.players.append(player) table.hand = shuffle_cards() table.id = i + 1 bank.name = "Bank" bank.status = False table.bank = bank tables.append(table) if (i*3 + m + 1) == num: break if (num-i*3)%2 == 0 and (num-i*3)//2 == 1: for m in range(2): print("Insert the name of player {}".format(i*3 + m + 1)) name = input() player = Player() player.name = name deck = Deck() player.decks.append(deck) table.players.append(player) table.hand = shuffle_cards() table.id = i + 1 bank.name = "Bank" bank.status = False table.bank = bank tables.append(table) if i*3 + m + 1 == num: break if ((num-3*i)//1) == 1: for m in range(1): print("Insert the name of player {}".format(i*3 + m + 1)) name = input() player = Player() player.name = name deck = Deck() player.decks.append(deck) table.players.append(player) table.hand = shuffle_cards() table.id = i + 1 bank.name = "Bank" bank.status = False table.bank = bank tables.append(table) if (i*3 + m + 1) == num: break else: for m in range(3): print("Insert the name of player {}".format(i*3 + m + 1)) name = input() player = Player() player.name = name deck = Deck() player.decks.append(deck) table.players.append(player) table.hand = shuffle_cards() table.id = i + 1 bank.name = "Bank" bank.status = False table.bank = bank tables.append(table) i = i + 1 return tables
#!/usr/bin/env python3 from __future__ import annotations import random from classes import Card, Player, Dealer, GameState, Deck NUM_DECKS_IN_GAME = 6 STARTING_CASH = 200 MIN_BET = 5 MAX_SPLITS = 4 deck = Deck(NUM_DECKS_IN_GAME) discard_pile = Deck(0) player1 = Player(STARTING_CASH) dealer = Dealer() state = GameState.DEAL_CARDS players = [player1]
for later analysis """ from datetime import datetime from classes import DAO, Player, Deck MONGO_URI = "mongodb://localhost" # MongoDB connection string SAMPLES = 1000 # number of games to play THRESHOLD = 15 # score under which Player will draw 1 card NB_DECKS = 4 # number of decks to use. Decks are reshuffled when half the cards have been drawn START_TIME = datetime.now() mongo = DAO(MONGO_URI) p_human = Player() p_casino = Player() c_deck = Deck(NB_DECKS) for i in range(SAMPLES): p_human.draw_card(c_deck) p_casino.draw_card(c_deck) p_human.draw_card(c_deck) p_casino.draw_card(c_deck) if p_human.blackjack: if p_casino.blackjack: p_human.gain = 0 # Casino and Player both have a blackjack, it's a deuce else: p_human.gain = 2 # Player alone has a Blackjack, double win else: while p_human.score < THRESHOLD: # Player will draw cards until reaching THRESHOLD score p_human.draw_card(c_deck)
def test_deck_is_complete(self): test_deck = Deck() self.assertEqual(len(test_deck.cards), 56)
async def card(self, ctx): deck = Deck() await ctx.send(random.choice(deck.contents))
from classes import Deck, Player, Game eggbert = Player("Eggbert", Deck()) cpu = Player("Cpu", Deck()) game = Game(eggbert, cpu) game.start()
def test_draw_card(self): test_deck = Deck() test_deck.deal_card() self.assertEqual(len(test_deck.cards), 55)
suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs') ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace') values = { 'Two': 2, 'Three': 3, 'Four': 4, 'Five': 5, 'Six': 6, 'Seven': 7, 'Eight': 8, 'Nine': 9, 'Ten': 10, 'Jack': 10, 'Queen': 10, 'King': 10, 'Ace': 11 } deck = Deck() ''' deal card to dealer and two cards for human''' dealer = Hand() player = Hand() p_chips = Chips('player', 100) d_chips = Chips('delaer', 100) take_bet(p_chips) ''' hit_or_stand(deck,player) show_some(player,dealer) '''
def __init__(self, bot): self.bot = bot self.deck = Deck()