def __init__(self, num_players=1, difficulty=3, debug=False): # Initialize colorama to enable styled terminal output on Windows init() # 2-person games and 2-AI games are only for testing right now self.players = [] if num_players == 0: self.players.append( AIPlayer(self.player_victory, 0, difficulty=difficulty, verbose=debug)) self.players.append( AIPlayer(self.player_victory, 1, difficulty=difficulty, verbose=debug)) elif num_players == 1: self.players.append(HumanPlayer(self.player_victory, 0)) self.players.append( AIPlayer(self.player_victory, 1, difficulty=difficulty, verbose=debug)) elif num_players == 2: self.players.append(HumanPlayer(self.player_victory, 0)) self.players.append(HumanPlayer(self.player_victory, 1)) self.difficulty = difficulty self.messages = [Message()] self.debug = debug self.deck = Deck() self.crib = Hand() self.upcard = Card() self.pegging_cards = [] self.pegging_count = -1 self.dealer = -1 self.pone = -1
def test_complete(self): """ Test the deck is complete. And stress test it. """ # Make all legal cards full_deck = [] for suite in Suites: for i in range(1, 14): full_deck.append(Card(i, suite)) self.assertTrue(len(full_deck) == N_CARDS) # Check that a deck contains all legal cards only deck = Deck() visited_deck = [] for card in deck: self.assertTrue(card in full_deck) self.assertFalse(card in visited_deck) visited_deck.append(card) self.assertTrue(len(full_deck) == len(visited_deck)) # Check that there are no more cards left self.assertTrue(deck.pop() is None) self.assertTrue(deck.pop() is None) self.assertTrue(deck.pop() is None) # Stress test for _ in range(1000): deck.shuffle() visited_deck = [] for _ in range(N_CARDS): c = deck.pop() self.assertTrue(c in full_deck) self.assertFalse(c in visited_deck) visited_deck.append(c) self.assertTrue(len(visited_deck) == N_CARDS) self.assertTrue(deck.pop() is None)
def next(self, input_, data, war_state): num_players = len(war_state['players']) if input_ == WarAction.add_player and num_players >= self.req_players: return War.lobby if input_ == WarAction.add_player: if 'pid' in data and data['pid'] not in war_state['players']: war_state['players'][data['pid']] = Player(data['pid']) return War.lobby if input_ == WarAction.start_game and num_players < self.req_players: return War.lobby if input_ == WarAction.start_game: deck = Deck() # Throw away every player's deck. Needed if restarting the game. for pid, player in war_state['players'].iteritems(): player.deck.discard_deck() # Deal the cards to the players cur_player = 0 player_list = [ player for pid, player in war_state['players'].iteritems() ] while True: card = deck.draw_card() if card is None: break player_list[cur_player].deck.add_card_to_bottom(card) cur_player += 1 cur_player %= num_players war_state['drawn_cards'] = {} war_state['continue_game'] = set() war_state['pot'] = [] return War.preparation return State.next(self, input_, data, war_state)
def __init__(self): # create and shuffle deck self.gameDeck = Deck() self.gameDeck.createDeck() self.gameDeck.shuffleDeck() # initialize piles self.handPile = Pile("h", self.gameDeck.cards[:]) self.wastePile = Pile("w", []) self.foundationsPiles = [ Pile("f", []), Pile("f", []), Pile("f", []), Pile("f", []) ] self.tableauPiles = [ Pile("t", []), Pile("t", []), Pile("t", []), Pile("t", []), Pile("t", []), Pile("t", []), Pile("t", []) ]
def get_peg_play(self, set_message, available_cards, pegging_count, opponent_go, played_cards): # Get remaining cards in the deck. All cards played or seen so far are excluded excluded_cards = list(chain(list(chain(*played_cards)), self.known_cards, self.hand.cards, [self.hand.upcard])) deck = Deck() remaining_cards = {i: 0 for i in range(1, 14)} # Suit doesn't matter, so convert the list of cards to a frequency distribution for easier processing for card in deck.cards: if card not in excluded_cards: remaining_cards[card.num_rank] += 1 # A card is considered playable if its counting value plus the current count doesn't exceed 31 playable_cards = [card for card in available_cards.cards if card.value + pegging_count <= 31] opponent_hand_size = 8 - len(list(chain(*played_cards))) - len(available_cards.cards) self.print_message('playable', ' '.join(str(card) for card in playable_cards)) self.print_message('played so far this round', ' '.join(str(card) for card in played_cards[-1]), '\n--------\n') self.print_message('remaining', remaining_cards) # If no cards are playable, return -1 for a go if len(playable_cards) == 0: return -1 # If only one card is playable then there's no sense analyzing it elif len(playable_cards) == 1: return playable_cards[0].num_rank # Assign a weight to each playable card based on various factors if more than one is playable else: play_weights = self.get_pegging_weights(playable_cards, played_cards, remaining_cards, pegging_count, opponent_hand_size) # Make the best play on hard difficulty if self.difficulty == 3: return_index = 0 # Make a decent play on medium difficulty elif self.difficulty == 2: # This is safe because we never have list of play weights with a length less than 2 return_index = random.randint(0, 1) # Play whatever feels groovy on easy difficulty else: return_index = random.randrange(0, len(play_weights)) return play_weights[return_index].num_rank
def main(): try: print("Granny Poker", flush=True) # Deal cards, peek at 2 cards deck = Deck(values={"K": 0}) hands = deck.deal(2, 4) computer = GrannyPokerPlayer(hands[0], comp=True) human = GrannyPokerPlayer(hands[1]) human.peek() # Start game computer, human = play(computer, human, deck) div() msg = "Your hand:\n" for i in range(4): msg += f"- {human.get_card(i)}\n" human_score = human.sum() msg += f"score: {human_score}\n\n" msg += "The computer:\n" for i in range(4): msg += f"- {computer.get_card(i)}\n" computer_score = computer.sum() msg += f"score: {computer_score}\n\n" print(msg, flush=True) if human_score < computer_score: print("Congratulations! You won!", flush=True) elif human_score == computer_score: print("So close, you tied!", flush=True) else: print("Shame! You lost!", flush=True) except KeyboardInterrupt: print("\n\nOh, you got scared, huh?\n\n", flush=True) pass
def test_sort_cards_stress(): """ Tests sort as defined in #3 in take home prompt.\ Tests all possible permutations, with many cards """ n_cards = 5000 deck = Deck(color_values={'red':3, 'yellow':2, 'green':1, 'blue':4,\ 'purple':5, 'orange': 6}, deck_sz=n_cards) def check_sort(card_deck, key): seen_colors = [] last_number_seen = 0 for card in card_deck: if card.color not in seen_colors: seen_colors.append(card.color) assert last_number_seen < card.number assert seen_colors == list(key) for color_order in permutations(deck._color_values.keys()): deck.sort_cards(color_order) check_sort(deck.card_deck, color_order)
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 cookbook_run(turn_played=2, draw_p=1): power = read_exported_list('decklists/ghp_haunted.txt') deck = Deck(power) deck.draw_7() damage_taken = 0 damage_across_turns = [] for i in range(turn_played - 1): deck.draw() damage_across_turns.append(damage_taken) while len(deck.deck) > 0: card = deck.draw() while card == 'firebomb': damage_taken += 5 card = deck.draw() if np.random.random() < draw_p: deck.add_card('firebomb') card = deck.draw() while card == 'firebomb': damage_taken += 5 card = deck.draw() damage_across_turns.append(damage_taken) return damage_across_turns
def start_game(): clear_console() print("Welcome to the Black Jack table!") deck = Deck() deck.shuffle() player_bankroll = Bankroll() player_bankroll.deposit(get_deposit_amount()) while True: bet = get_bet(player_bankroll) player_wins = play_round(deck, bet) if player_wins: player_bankroll.deposit(2 * bet) if not play_another_round(player_bankroll): break print( f"You decided to leave the table with a bankroll of {player_bankroll.balance}." ) print("Thank you for playing!")
def play_game() -> None: """ Start the game. This is the main event loop. """ config = read_config(CONFIG_FILE) setup_logging(config) logger.info('Game starting') say(None, 'Welcome to Blackjack!') deck: Deck = Deck() # start with a single deck deck.shuffle() players: list = get_players() dealer: Player = Player('Dealer', is_dealer=True) dealer.wallet.add_money(1000) while True: deal_cards(deck, dealer, 2) ask_player_position(deck, players, dealer) say(None, 'Play again? (y/N)') answer = get_input() if answer.lower() not in ('y', 'yes'): break else: dealer.remove_all_cards() for player in players: player.remove_all_cards()
def test_cards(self): cards = ['hi', 'there'] deck = Deck(cards) self.assertEqual(deck.cards, cards)
def __init__(self, players): self.deck = Deck() self.players = players
RoundOut = input( """Does anyone want to fold? \n (Note: Type their position #, one at a time:) If No-one folds, type NO: """ ) if RoundOut == str(NO): pass elif RoundOut == str(1): Found = GAME.pop(0) LST.insert(Found) elif RoundOut == str(2): Found = GAME.pop(1) LST.insert(Found) elif RoundOut == str(3): Found = GAME.pop(2) LST.insert(Found) elif RoundOut == str(4): Found = GAME.pop(3) LST.insert(Found) i += 1 Ajani = Player("Ajani", 100, "Ajani's.txt") Jim = Player("Jim", 100, "Jim's.txt") Bob = Player("Bob", 100, "Bob's.txt") Joe = Player("Joe", 100, "Joe's.txt") Tam = Dealer("Tam") Disney = Deck("Disney", Joker=True) Tam.EquipDeck(Disney) Classic = Dealers_Table("Classic", Tam, Ajani, Jim, Bob, Joe) Classic.RoundOrder() eval
def setUp(self): self.deck = Deck()
def deck(): return Deck()
def test_deck_reset(deck): other_deck = Deck() other_deck.reset() assert(deck == other_deck)
def test_init_deck(self): deck = Deck() self.assertEqual(len(deck.cards), 52)
import sys from deck import Deck from UI.ui import Application if __name__ == '__main__': source = sys.argv[1] table = sys.argv[2] flash_cards = [] # Create deck deck = Deck(source, table) # Fetch deck.fetch() # Start quizzing deck.shuffle() app = Application() app.deck = deck exit_status = app.run(sys.argv) sys.exit(exit_status) print(""" Type \"exit\" or \"quit\" to exit, type \"hint\" for a hint, or type \"skip\" to skip a question.\n""") while len(deck) > 0: print("Remaining flash cards:", len(deck), "\n") card = deck.draw()
from deck import Deck from deck import Card from game import Play # It is a slightly different variation of the 'WAR' card game. Users can select which card to throw unless # they are in a WAR situation, which all the cards will be from the top. if __name__ == "__main__": deck = Deck() player_pc = [] player_real = [] for i in range(len(deck.get_deck())): if i % 2 == 0: player_pc.append(deck.get_deck()[i]) else: player_real.append(deck.get_deck()[i]) game = Play(player_pc, player_real) # game = Play([Card('S', '2', False), Card('D', '2', False), Card('H', '2', False), Card('C', '2', False)], # [Card('S', 'A', False), Card('D', 'A', False), Card('H', 'A', False), Card('C', 'A', False)]) game.play()
play_again() ### Main Function Starts Here # Prints the Welcome Message print() print("***** Welcome to Cascais Casino *****") player_name = input("What is your name? ") print("Good luck " + player_name + "\n") # Main Application Initializes the Player and Dealer and names the Player player1 = Player() player1.name = player_name dealer1 = Dealer() # Get the initial amount to bet starting_bet = input("How much money do you want to put in the pot? ") player1.money = int(starting_bet) player1.initial_bet = int(starting_bet) # Initialize the deck and shuffle the cards cards = Deck() cards.shuffle_cards() # Starts the game play_blackjack() # Things to add later on # 1) Add Doule Down # 2) Add Card Splits # 3) Try adding Multiple Players
def __init__(self): self.location = 0 self.doubles = 0 self.decks = {} self.decks['CH'] = Deck(cards['CH']) self.decks['CC'] = Deck(cards['CC'])
p = Player(1, 100) p.show_chips() p.update_chips(200) p.show_chips() p.update_chips(-350) p.show_chips() p.update_chips(71) p.show_chips() p.show_hand() d = Deck() d.show() p.add_card(d.deal_card()) p.add_card(d.deal_card()) p.show_hand() p.add_card(d.deal_card()) p.show_hand() p.add_card(d.deal_card()) p.show_hand()
from guizero import App, Picture from deck import Deck import random my_deck = Deck() def deal_hand(size): hand = [] for i in range(size): new_card = random.choice(my_deck.cards) hand.append(new_card) return hand card_width = 86 card_height = 132 my_hand = deal_hand(5) app = App(title="game") for card in my_hand: Picture(app, image=card.pic, width=card_width, height=card_height, align='left') ''' for i in range(5): Picture(app, image=my_deck.cards[i].pic, width=card_width,height=card_height, align='left')
def test_get_cards(self): deck = Deck() self.assertEqual(len(deck.get_cards(10)), 10) self.assertEqual(len(deck.cards), 42)
def __init__(self, n_seats, max_limit=20000, debug=False): n_suits = 4 # s,h,d,c n_ranks = 13 # 2,3,4,5,6,7,8,9,T,J,Q,K,A n_community_cards = 5 # flop, turn, river n_pocket_cards = 2 n_stud = 5 self.n_seats = n_seats self._deck = Deck() self._evaluator = Evaluator() self._debug = debug self.init() # fill seats with dummy players self._seats = [ Player(i, stack=0, emptyplayer=True) for i in range(n_seats) ] self.emptyseats = n_seats self._player_dict = {} self.observation_space = spaces.Tuple([ spaces.Tuple([ # # **players info** spaces.MultiDiscrete([ 1, # (boolean) is_emptyplayer n_seats - 1, # (numbers) number of seat max_limit, # (numbers) stack 1, # (boolean) is_playing_hand max_limit, # (numbers) handrank, need_error_msg? (0 could be no rank, no error_msg needed 1, # (boolean) is_playedthisround max_limit, # (numbers) is_betting 1, # (boolean) isallin max_limit, # (numbers) last side pot ]), spaces.Tuple([ spaces.MultiDiscrete([ # # **players hand** 1, # (boolean) is_avalible n_suits, # (catagory) suit, n_ranks, # (catagory) rank. ]) ] * n_pocket_cards) ] * n_seats), spaces.Tuple([ spaces.Discrete(n_seats - 1), # big blind location spaces.Discrete(max_limit), # small blind spaces.Discrete(max_limit), # big blind spaces.Discrete(max_limit * n_seats), # pot amount spaces.Discrete(max_limit), # last raise spaces.Discrete(max_limit), # minimum amount to raise spaces.Discrete( max_limit), # how much needed to call by current player. spaces.Discrete(n_seats - 1), # current player seat location. spaces.MultiDiscrete([ # community cards 1, # (boolean) is_avalible n_suits, # (catagory) suit n_ranks, # (catagory) rank 1, # (boolean) is_flopped ]), ] * n_stud), ]) self.action_space = spaces.Tuple([ spaces.MultiDiscrete([ 3, # action_id max_limit, # raise_amount ]), ] * n_seats) self.logger = logging.getLogger('TexasHoldemEnv') #self.logger.setLevel(logging.DEBUG) ch = logging.StreamHandler() # create formatter formatter = logging.Formatter('%(asctime)s: %(message)s') # add formatter to ch ch.setFormatter(formatter) # add ch to logger self.logger.addHandler(ch)
def test_deck_shuffle(deck): other_deck = Deck() other_deck.shuffle() assert (deck != other_deck)
def __init__(self): self.deck = Deck().build_deck() self.single_card = []
def __init__(self): self.player = self.create_player("Player") self.dealer = Player("Dealer") self.deck = Deck()
def main(): # Sentinel Values playAgain = True numOfPlayers = 0 playerAccounts = [] playerNames = [] # Get preparatory information for the game. That's what I've cleverly named the game. Kudos to me. makeDivision() print("Welcome to Fake Jack Black's Fake Blackjack Attack!") makeDivision() while numOfPlayers not in range(1, 6): numOfPlayers = int(input("Please enter the number of players, 1-5: ")) for i in range(numOfPlayers): playerAccounts.append(100) for i in range(numOfPlayers): playerNames.append("Player #" + str(i + 1)) # Start the game! while playAgain: # First thing we need to do is call the class and define all variables that will be used later in the loop. deck = Deck() deck.shuffle() playerHands = [] dealerPosition = -1 playerScoreList = [] playerBets = [] hold = False bustValue = 21 minBet = 5 playerBet = 0 # Construct the lists. The dealer is the last list in each list for i in range(numOfPlayers + 1): playerHands.append([]) for j in range(2): playerHands[i].append(deck.draw()) playerScoreList = getPlayerScores(playerHands) for i in range(len(playerAccounts)): if playerAccounts[i] <= minBet: print(playerNames[i], " you have less than $", minBet, " so you're betting everything (", playerAccounts[i], ").") playerBet = playerAccounts[i] playerBets.append(playerBet) else: playerBet = float( input(playerNames[i] + " you have $" + format(playerAccounts[i], ".2f") + ", what is your bet? ")) if playerBet > playerAccounts[i]: print( playerNames[i], " you can't bet more than you have, so you're betting everything." ) playerBets.append(playerAccounts[i]) elif playerBet < minBet: print(playerNames[i], " you can't bet less than $", format(minBet, ".2f"), ", so that's your bet.") playerBets.append(minBet) else: playerBets.append(playerBet) print("The dealer's second card was ", playerHands[dealerPosition][1]) # Here we program the hit/hold dynamic as well as the dealer's actions. for i in range(len(playerHands) - 1): makeDivision() print(playerNames[i], ", you have a score of", playerScoreList[i], "and your hand contains") for j in range(len(playerHands[i])): print(" ", playerHands[i][j]) while not hold: action = int( input( playerNames[i] + ", would you like to hit or hold? Enter 1 for hit, 2 for hold: " )) if action == 1: newCard = deck.draw() print("You drew a(n)", newCard) playerHands[i].append(newCard) playerScoreList = getPlayerScores(playerHands) if playerScoreList[i] <= bustValue: print(playerNames[i], ", you have a score of", playerScoreList[i], "and your hand consists of ") for j in range(len(playerHands[i])): print(" ", playerHands[i][j]) else: print(playerNames[i], ", you went bust! Your score was", playerScoreList[i]) break elif action == 2: break makeDivision() print("The dealer's score is ", playerScoreList[dealerPosition], "and his hand contains") for j in range(len(playerHands[dealerPosition])): print(" ", playerHands[dealerPosition][j]) while not hold: if playerScoreList[dealerPosition] < 17: time.sleep(1) newCard = deck.draw() print("The dealer drew a(n)", newCard) playerHands[dealerPosition].append(newCard) playerScoreList = getPlayerScores(playerHands) print("The dealer's score is ", playerScoreList[dealerPosition], "and his hand contains") for j in range(len(playerHands[dealerPosition])): print(" ", playerHands[dealerPosition][j]) elif playerScoreList[dealerPosition] in range(17, 22): time.sleep(1) print("The dealer holds.") break else: time.sleep(1) print("The dealer went bust with a score of", playerScoreList[dealerPosition]) break makeDivision() # Calculate and display the payouts if playerScoreList[dealerPosition] > 21: for i in range(len(playerAccounts)): if playerScoreList[i] <= 21: playerAccounts[i] += playerBets[i] else: playerAccounts[i] -= playerBets[i] else: for i in range(len(playerAccounts)): if playerScoreList[i] in range( playerScoreList[dealerPosition] + 1, 22): playerAccounts[i] += playerBets[i] elif playerScoreList[i] == playerScoreList[dealerPosition]: playerAccounts[ i] += 0 # Strictly speaking, this is unnecessary, I'm just putting it there for my benefit elif playerScoreList[i] < playerScoreList[dealerPosition]: playerAccounts[i] -= playerBets[i] else: playerAccounts[i] -= playerBets[i] for i in range(len(playerAccounts)): print(playerNames[i], ", you bet $", format(playerBets[i], ".2f"), " so you now have $", format(playerAccounts[i], ".2f"), " in your account.") # Exit the loop or play again! while playAgain != "y" and playAgain != "n": makeDivision() playAgain = input("Would you like to play again? Y/N: ").lower() makeDivision() if all(i == 0 for i in playerAccounts): print( "Actually, no one has any money, so it doesn't matter what you want!" ) playAgain = "n" if playAgain == "y": deletionList = [] for i in range(len(playerAccounts)): if playerAccounts[i] <= 0: deletionList.append(i) for i in range(len(deletionList) - 1, -1, -1): print("Remember, the house always wins. Goodbye ", playerNames[deletionList[i]]) del playerAccounts[deletionList[i]] del playerBets[deletionList[i]] del playerNames[deletionList[i]] del playerHands[deletionList[i]] del playerScoreList[deletionList[i]] if i == 0: makeDivision() del playerHands[dealerPosition] del playerScoreList[dealerPosition] print("Very well remaining players, let's begin.") makeDivision() numOfPlayers = len(playerHands) playAgain = True break elif playAgain == "n": playerSort(playerAccounts, playerNames) for i in range(len(playerNames)): print(playerNames[i], " you're walking away with $", format(playerAccounts[i], ".2f")) print( "Everyone else (if any), you should have already left with nothing. If you haven't, LEAVE." ) playAgain = False break makeDivision() print( "Thanks for playing! Hopefully you've learned not to gamble, you heathen (though for SOME reason I sincerely doubt it...)." ) makeDivision()