def test_pull_card(self): deck = Deck() card = deck.pull_card(2, '♥') value, suit = card.get_card() self.assertEqual(value, 2) self.assertEqual(suit, '♥') self.assertEqual(len(deck.get_deck()), 51)
def test_deck(self): '''test deck''' deck = Deck(52) deck.shuffle() for index in range(52): card = deck.deal() print('{}. {}'.format(index + 1, card.__str__())) no_of_cards = len(deck) self.assertEqual(no_of_cards, 0)
def __init__(self): ''' game init ''' #print(Deck()) print('BlackJack pays {}'.format(self.bj_pays)) self.deck = Deck() self.player = Player() self.dealer = Dealer() self.deck.shuffle()
def __init__(self, users: List[str]): self.users: List[str] = users self.n_of_players: int = len(users) self.players: List[Player] = self.init_players(users) self.deck = Deck() self.board: Board = Board(self.n_of_players) self.minister: Player = choice(self.players) self.director: Player = None self.last_minister: Player = None self.last_director: Player = None self.phase: GamePhase = GamePhase.PROPOSE_DIRECTOR self.cards: List[Card] = self.deck.take_3_cards() self.votes: Dict[str, Vote] = dict() self.last_update = datetime.now() self.casted_imperius_by: Player = None self.chaos_counter: int = 0 self.investigated_players: List[Player] = list() self.casted_expelliarmus: bool = False
def round (player): from classes.deck import Deck from classes.card import Card from classes.hand import Hand #Initiate new deck and hands deck = Deck() deck.shuffleCards() playerhand = Hand() dealerhand = Hand() #InitialRound dealerhand.add_card(deck.dealOneCard()) dealerhand.add_card(deck.dealOneCard()) playerhand.add_card(deck.dealOneCard()) playerhand.add_card(deck.dealOneCard()) playerhand.show_all(player.name) dealerhand.show_some('Dealer') #Player plays playing = play_on (playerhand) while playing: playerhand.add_card(deck.dealOneCard()) playerhand.show_all(player.name) if playerhand.value > 21: player_busts(player) break playing = play_on (playerhand) #Dealer plays if playerhand.value <= 21: dealerhand.show_all('Dealer') while dealerhand.value < playerhand.value: print('\nDealer draws') dealerhand.add_card (deck.dealOneCard()) dealerhand.show_all('Dealer') print (f'Dealer has {dealerhand.value}.') if dealerhand.value <= 21: dealer_wins(player) else: dealer_busts(player)
def __init__(self, gui): self.rounds = [] # create deck deck = Deck() # popup window to ask for name, create player objects name = simpledialog.askstring(title="Name", prompt="What's your name?") while not name: name = simpledialog.askstring(title="Name", prompt="Please insert a name") players = [] user = Player(name) dealer = Player("Dealer") players.append(user) players.append(dealer) # show player info gui.name_label["text"] = "Name: " + user.name gui.chips_label["text"] = "Total chips: " + str(user.chips) # start new round as long as user has enough chips while user.chips >= 1: user.cards.clear() dealer.cards.clear() current_round = Round(user, dealer, deck, gui) self.rounds.append(current_round) new_round = messagebox.askquestion("New game?") if new_round == "no": gui.root.destroy() # empty options for widget in gui.player_options_frame.winfo_children(): widget.destroy() # empty user cards user.cards.clear() dealer.cards.clear() messagebox.showinfo("GAME OVER", "OUT OF CHIPS!")
class TestDeck: c = Cards d = Deck() def test_create(self): deck = self.d.create_deck(self.c) assert len(deck) == 52 for card in self.c.matrix: count = 0 for other_card in deck: if card == other_card: count += 1 else: pass assert count == 4 def test_shuffle_deck(self): deck = self.d.create_deck(self.c) shuffled_deck = self.d.shuffle_deck(deck) assert len(shuffled_deck) == 52 assert deck != shuffled_deck for card in self.c.matrix: count = 0 for other_card in deck: if card == other_card: count += 1 else: pass assert count == 4
class Game: """This is a class for controlling the operations of the blackjack game. Attributes: winnings (int) -- the amount of money the player has. """ def __init__(self): """The constructor for the Game class.""" self.winnings = 100 def play(self): """The main controller for playing the game of Blackjack.""" play_again = True while play_again: self.deck = Deck() self.deck.shuffle() # Initialize player and dealer's hands self.player_hand = Hand() self.dealer_hand = Hand(isDealer = True) self.display_empty_game() self.player_hand.prompt_for_wager(self.winnings) self.winnings -= self.player_hand.wager # remove wager from current winnings self.deal_cards() self.dealer_hand.cards[first_card].flip_face_down() # flip dealer's first card face down self.display_state_of_game(self.player_hand) choice = 'n' # holder value for choice variable # player must have enough money to wager and cards in equal rank to split his or her hand if (self.winnings > self.player_hand.wager) and (self.player_hand.cards[first_card].rank == self.player_hand.cards[second_card].rank): choice = util.get_valid_input('\nWould you like to split? (Y)es or (N)o?: ', ['y','n'], 'Not a valid response') if choice == 'y': self.split_hand() self.play_split_hand() if choice != 'y': # player did not choose to split or did not have ability to self.player_turn(self.player_hand) # dealer only needs to play if player has not gone over 21 and does not have blackjack if self.player_hand.get_over_21_status(): self.dealer_hand.cards[first_card].flip_face_up() elif self.player_hand.has_blackjack(): self.dealer_hand.cards[first_card].flip_face_up() else: self.dealer_turn(self.player_hand) self.resolve_wager(self.player_hand) self.display_state_of_game(self.player_hand) if self.player_hand.is_split: # print outcome of both hands print('\nThe dealer finished with a score of',self.dealer_hand.sum_of_cards) print('Your first hand finished with a score of', self.player_hand.sum_of_cards) self.display_final_outcome(self.player_hand) print('\nThe dealer finished with a score of',self.dealer_hand.sum_of_cards) print('You second hand finished with a score of', self.player_second_hand.sum_of_cards) self.display_final_outcome(self.player_second_hand) else: print('\nThe dealer finished with a score of',self.dealer_hand.sum_of_cards) print('You finished with a score of', self.player_hand.sum_of_cards) self.display_final_outcome(self.player_hand) response = util.get_valid_input('Would you like to play again? (Y)es or (N)o: ', ['y','n'], 'Not a valid response') if self.winnings == 0: print('Sorry, you ran out of money. Goodbye.') elif response == 'n': print('Thanks for playing. Goodbye.') break def deal_cards(self): """Deal two cards to each the player and the dealer.""" for i in range(2): # deal cards back and forth like a real game self.player_hand.add_card(self.deck.deal_card()) self.dealer_hand.add_card(self.deck.deal_card()) def player_turn(self, hand): """Execute the user/player's turn while recommending the best strategy for beating the dealer. Keyword Arguments: hand (Hand) -- the player's hand playing the current turn. """ again = True while again and not hand.get_over_21_status(): if hand.has_blackjack(): # stop turn of player has blackjack break self.display_state_of_game(hand) self.recommend_strategy(hand) if hand.wager > self.winnings: # If the user does not have enough funds. Don't allow him or her to double down choice = util.get_valid_input('\n(H)it or (S)tand?: ', ['h', 's'], 'Invalid choice. Please choose "H" to hit or "S" to stand') else: choice = util.get_valid_input('\n(H)it, (S)tand, or (D)ouble Down?: ', ['h', 's', 'd'], 'Invalid choice. Please choose "H" to hit or "S" to stand') if choice == 'h': hand.add_card(self.deck.deal_card()) elif choice == 'd': # double wager self.winnings -= hand.wager hand.wager += hand.wager # add only one card to hand. Player may not hit again hand.add_card(self.deck.deal_card()) again = False elif choice == 's': again = False self.display_state_of_game(hand) def recommend_strategy(self, player_hand): """Inform the user of the statistically best move to make based on his or her hand sum, and the dealer's single visible card. Keyword Arguments: player_hand (Hand) -- the player's hand playing the current turn. """ Ace = 'A' if (player_hand.cards[first_card].rank == player_hand.cards[second_card].rank) and len(player_hand.cards) < 3: # player has a pair on the first turn strategy = bs.make_pair_recommendation(player_hand.cards[first_card].rank, self.dealer_hand.cards[second_card].rank) # always check the dealer's face-up card (second card) elif player_hand.cards[first_card].rank != Ace and player_hand.cards[second_card].rank != Ace: # user does not have an ace strategy = bs.make_hard_total_recommendation(player_hand.sum_of_cards, self.dealer_hand.cards[second_card].rank) elif player_hand.cards[first_card].rank != Ace and player_hand.cards[second_card].rank == Ace and len(player_hand.cards) < 3: # user has an ace and a non-ace in the first hand strategy = bs.make_soft_total_recommendation(player_hand.cards[first_card].rank, self.dealer_hand.cards[second_card].rank) elif player_hand.cards[first_card].rank == Ace and player_hand.cards[second_card].rank != Ace and len(player_hand.cards) < 3: # user has an ace and a non-ace in the first hand strategy = bs.make_soft_total_recommendation(player_hand.cards[second_card].rank, self.dealer_hand.cards[second_card].rank) else: strategy = bs.make_hard_total_recommendation(player_hand.sum_of_cards, self.dealer_hand.cards[second_card].rank) print('\nThe recommended strategy is to:', strategy) def dealer_turn(self, player_hand): """Execute the dealer/computer player's turn. A dealer must always hit on a hand value less than 17. Keyword Arguments: player_hand (Hand) -- the player's hand playing the current turn. """ self.dealer_hand.cards[first_card].flip_face_up() self.display_state_of_game(player_hand) again = True while again: if self.dealer_hand.sum_of_cards < 17: # dealer must hit when under 17 self.dealer_hand.add_card(self.deck.deal_card()) else: again = False time.sleep(.50) self.display_state_of_game(player_hand) def display_final_outcome(self, player_hand): """Determine the final outcome of the hand against the dealer's hand to display the appropriate message to the user. Keyword Arguments: player_hand (Hand) -- the player's hand playing the current turn. """ if player_hand.has_blackjack(): print('\nCongratualtions! You got Blackjack. You WIN!\n') elif player_hand.get_over_21_status(): print('\nYou went over 21. You LOSE!\n') elif self.dealer_hand.get_over_21_status(): print('\nThe dealer went over 21. You WIN!\n') elif self.dealer_hand.sum_of_cards < player_hand.sum_of_cards: print('\nYou WIN!\n') elif player_hand.sum_of_cards < self.dealer_hand.sum_of_cards: print('\nYou LOSE!\n') else: print('\nTie! The game results in a PUSH.\n') def resolve_wager(self, player_hand): """Calculate the amount the player won or lost, and adjust his or her winnings appropriately. Keyword Arguments: player_hand (Hand) -- the player's hand playing the current turn. """ if player_hand.has_blackjack(): self.winnings += player_hand.wager * 3 player_hand.reset_wager() elif player_hand.get_over_21_status(): # player lost player_hand.reset_wager() elif self.dealer_hand.get_over_21_status(): # player won self.winnings += player_hand.wager * 2 player_hand.reset_wager() elif player_hand.sum_of_cards < self.dealer_hand.sum_of_cards: # player lost player_hand.reset_wager() elif self.dealer_hand.sum_of_cards < player_hand.sum_of_cards: # player won self.winnings += player_hand.wager * 2 player_hand.reset_wager() else: # game ended in a push self.winnings += player_hand.wager player_hand.reset_wager() def display_empty_game(self): """Print two empty cards for both the dealer and the player, as will as the player's current funds and bet.""" util.clear_window() lines = [''] * max_card_height for i in range(2): # display 2 cards lines[0] += '┌─────────┐' lines[1] += '│ │' lines[2] += '│ │' lines[3] += '│ │' lines[4] += '│ │' lines[5] += '│ │' lines[6] += '│ │' lines[7] += '│ │' lines[8] += '└─────────┘' for line in lines: print(line) for line in lines: print(line) print('\n Funds: ${} | Bet: ${}'.format(self.winnings, 0)) # display wager def display_state_of_game(self, player_hand): """Print the dealer's hand, player's hand, current funds, and current bet amount to the console. Keyword Arguments: player_hand (Hand) -- the player's hand playing the current turn. """ time.sleep(.20) util.clear_window() self.dealer_hand.display_hand() player_hand.display_hand() print('\n Funds: ${} | Bet: ${}'.format(self.winnings, player_hand.wager)) # display wager # Methods used for gameplay when user splits his or her hand def play_split_hand(self): """Play the rest of the game using two hands for the player rather than one.""" self.player_turn(self.player_hand) self.player_turn(self.player_second_hand) self.dealer_turn(self.player_second_hand) self.resolve_wager(self.player_hand) self.resolve_wager(self.player_second_hand) self.display_state_of_game(self.player_second_hand) # show the updated winnings and null bet amount after completed def split_hand(self): """ Create a second hand with a wager equal to that of the first hand so the user can play using both hands.""" self.player_second_hand = Hand() self.player_second_hand.add_card(self.player_hand.remove_last_card()) # remove card from hand one and give it to hand two self.player_hand.indicate_hand_is_split() self.player_second_hand.indicate_hand_is_split() # deal a card to each hand self.player_hand.add_card(self.deck.deal_card()) self.player_second_hand.add_card(self.deck.deal_card()) # double wager self.winnings -= self.player_hand.wager self.player_second_hand.wager += self.player_hand.wager
def place_bet(total): os.system('cls' if os.name == 'nt' else 'clear') print(f'You have {total}$') while True: bet = get_bet() if bet > total: input('Insufficient funds!') else: return bet player_money = 100 deck = Deck() full_deck_size = 52 while player_money > 0: player_hand = [Hand()] dealer_hand = [Hand()] bets = [] bid = place_bet(player_money) bets.append(bid) player_money -= bets[0] if len(deck) / full_deck_size < 0.3: # if deck is running low on cards del deck # delete old deck deck = Deck() # open a new one input('Deck reshuffled')
def play(self): """The main controller for playing the game of Blackjack.""" play_again = True while play_again: self.deck = Deck() self.deck.shuffle() # Initialize player and dealer's hands self.player_hand = Hand() self.dealer_hand = Hand(isDealer = True) self.display_empty_game() self.player_hand.prompt_for_wager(self.winnings) self.winnings -= self.player_hand.wager # remove wager from current winnings self.deal_cards() self.dealer_hand.cards[first_card].flip_face_down() # flip dealer's first card face down self.display_state_of_game(self.player_hand) choice = 'n' # holder value for choice variable # player must have enough money to wager and cards in equal rank to split his or her hand if (self.winnings > self.player_hand.wager) and (self.player_hand.cards[first_card].rank == self.player_hand.cards[second_card].rank): choice = util.get_valid_input('\nWould you like to split? (Y)es or (N)o?: ', ['y','n'], 'Not a valid response') if choice == 'y': self.split_hand() self.play_split_hand() if choice != 'y': # player did not choose to split or did not have ability to self.player_turn(self.player_hand) # dealer only needs to play if player has not gone over 21 and does not have blackjack if self.player_hand.get_over_21_status(): self.dealer_hand.cards[first_card].flip_face_up() elif self.player_hand.has_blackjack(): self.dealer_hand.cards[first_card].flip_face_up() else: self.dealer_turn(self.player_hand) self.resolve_wager(self.player_hand) self.display_state_of_game(self.player_hand) if self.player_hand.is_split: # print outcome of both hands print('\nThe dealer finished with a score of',self.dealer_hand.sum_of_cards) print('Your first hand finished with a score of', self.player_hand.sum_of_cards) self.display_final_outcome(self.player_hand) print('\nThe dealer finished with a score of',self.dealer_hand.sum_of_cards) print('You second hand finished with a score of', self.player_second_hand.sum_of_cards) self.display_final_outcome(self.player_second_hand) else: print('\nThe dealer finished with a score of',self.dealer_hand.sum_of_cards) print('You finished with a score of', self.player_hand.sum_of_cards) self.display_final_outcome(self.player_hand) response = util.get_valid_input('Would you like to play again? (Y)es or (N)o: ', ['y','n'], 'Not a valid response') if self.winnings == 0: print('Sorry, you ran out of money. Goodbye.') elif response == 'n': print('Thanks for playing. Goodbye.') break
class Game: '''game class''' # pylint: disable=too-many-instance-attributes bust = False bj_pays = 3/2 bj_player = False bj_dealer = False total_p = 0 total_d = 0 def __init__(self): ''' game init ''' #print(Deck()) print('BlackJack pays {}'.format(self.bj_pays)) self.deck = Deck() self.player = Player() self.dealer = Dealer() self.deck.shuffle() def deal_two_foreach(self): ''' deal 2 cards for each player ''' #one for the player card = self.deck.deal() self.player.hit(card) #one for the dealer, hidden card = self.deck.deal(message=False) card.hide()# one card of the dealer is hidden self.dealer.hit(card) #one for the player card = self.deck.deal(message=False) self.player.hit(card) #one for the dealer card = self.deck.deal(message=False) self.dealer.hit(card) #show table self.deck.draw_table(self.player.cards, self.dealer.cards) def check_hand(self, cards): ''' counts the number of aces calculates hand total checks if busted @param cards @return total ''' total = 0 has_ace = 0 for card in cards: #count aces if card.value == 11: has_ace += 1 total += card.value #if total exceds 21, set aces value to 1 until total gets to 21 or below while total > 21 and has_ace > 0: total = total - 10 has_ace -= 1 #busted if total > 21: self.bust = True return total def players_run(self): ''' hit or stand actions for the player ''' while self.bj_player is False: self.total_p = self.check_hand(self.player.cards) #check hand if self.total_p == 21: #player has 21 break elif self.bust: #bust print('You lost.') self.play_again() return else: while True: try: action = int(input('Press 1 for Hit or 2 for Stand: ')) break except ValueError: pass if action == 1: #one for the player card = self.deck.deal() self.player.hit(card) #show table self.deck.draw_table(self.player.cards, self.dealer.cards) else: #stand self.player.stand() break def dealers_run(self): ''' hit or stand actions for the dealer ''' #show hidden card self.dealer.cards[0].show() self.deck.draw_table(self.player.cards, self.dealer.cards) while self.bj_dealer is False and self.bj_player is False: # if the player has blackjack and the dealer is not, # dealing more cards doesn't make sense self.total_d = self.check_hand(self.dealer.cards) #check hand if self.total_d == 21: #dealer has 21 break elif self.bust is True: #bust print('You won {} chip(s).'.format(2*self.player.bet_value)) self.player.chips += 2*self.player.bet_value self.play_again() return elif self.total_d <= self.dealer.draw_until: card = self.deck.deal() self.dealer.hit(card) self.deck.draw_table(self.player.cards, self.dealer.cards) elif self.total_d >= self.dealer.must_stand: self.dealer.stand() break def conclude(self): ''' decide who the winner is ''' if (self.bj_player == True and self.bj_dealer == True) or (self.total_p == self.total_d): # tie print('Tie game') self.player.chips += self.player.bet_value elif self.bj_player: print('You won {} chip(s)'.format((self.bj_pays+1)*self.player.bet_value)) self.player.chips += (self.bj_pays+1)*self.player.bet_value elif self.total_p > self.total_d: print('You won {} chip(s)'.format(2*self.player.bet_value)) self.player.chips += 2*self.player.bet_value else: print('You lost.') self.play_again() def play(self): ''' game thread ''' #check if player has chips if self.player.chips == 0: print('You don\'t have any chips') quit() #check if enough cards if len(self.deck.cards) < self.deck.min_in_shoe: print('Not enough cards') self.deck.reset() # place bet print('You have {} chips'.format(self.player.chips)) self.player.bet() #deal cards self.deal_two_foreach() # check player for blackjack self.total_p = self.check_hand(self.player.cards) self.bj_player = (self.total_p == 21) # check dealer for blackjack self.total_d = self.check_hand(self.dealer.cards) self.bj_dealer = (self.total_d == 21) #player first self.players_run() #dealer second self.dealers_run() #decide who the winner is self.conclude() def play_again(self): ''' new game ''' while True: action = str(input('Play again? (y/n)')) if action.lower() == 'y': self.reset() self.play() break elif action.lower() == 'n': quit() def reset(self): ''' reset game ''' self.player.cards = [] self.dealer.cards = [] self.player.bet_value = 1 self.bust = False self.bj_player = False self.bj_dealer = False self.total_p = 0 self.total_d = 0
count = 0 while count < players_num: player_name = input('Player {}: '.format(count + 1)) if player_name == '': player_name = 'Player {}'.format(count + 1) # Create player players.append(Player(player_name)) count += 1 clear_console() """ CREATE PLAYERS - END """ # Creating decks main_deck = Deck() stock_deck = Deck() # Cleaning stock stock_deck.clear() # Hand out / distribute cards hand_out_cards(players, main_deck) """ START THE GAME""" GAME_OVER = False # Game state ct_turn = 0 # Current Turn clockwise = True # Defines the game flow # Moving a card to the table move_card(main_deck, stock_deck, -1)
from classes.card import Card from classes.deck import Deck from classes.player import Player player_one = Player("One") player_two = Player("Two") new_deck = Deck() new_deck.shuffle() for x in range(26): player_one.add_cards(new_deck.deal_one()) player_two.add_cards(new_deck.deal_one()) game_on = True round_number = 0 while game_on: round_number += 1 print(f"Round {round_number}") 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
# @SEENPAY from flask import Flask, request, render_template from classes.deck import Deck from classes.farm import Farm from flask_sqlalchemy import SQLAlchemy import requests from helpers import get_env_variable import os from flask_script import Manager from flask_migrate import Migrate, MigrateCommand #from helpers import get_env_variable app = Flask(__name__) deck = Deck() farms = {} app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get( 'DATABASE_URL' ) #'postgres://*****:*****@ec2-3-222-30-53.compute-1.amazonaws.com:5432/d3qts4a8o2lf4p' app.config['DATABASE_URL'] = get_env_variable( 'DATABASE_URL' ) #'postgres://*****:*****@ec2-3-222-30-53.compute-1.amazonaws.com:5432/d3qts4a8o2lf4p' db = SQLAlchemy(app) migrate = Migrate(app, db) #manager = Manager(app) #manager.add_command('db', MigrateCommand)
def main(): """ main method of blackjack game """ os.system('clear') or None print("Welcome to BlackJack -_- \n") name = input("First, What is your name? ") balance = int(input("How many money have you today? ")) player = RealPlayer(name, balance) bot = input("Could you choose a name for a bot? ") computer = Bot(bot, balance) os.system('clear') or None computer.welcome_message() input("\nSo let's play? ") os.system('clear') or None del balance, bot, name card = Cards() dealer = Dealer() deck = Deck() bj = BlackJack() game = False while not game: global hand_repr_player global hand_repr_bot player.hand = [] computer.hand = [] game_deck = deck.shuffle_deck(deck.create_deck(card)) os.system('clear') or None bj.check_balance(game, player) bj.check_balance(game, computer) if game == True: break os.system('clear') or None bets = bj.bet(player, computer) ask_player = False while not ask_player: if len(player.hand) == 0: print("You don't have any card in your hand") else: hand_repr_player = card.show_card(player.hand) [[print(x) for x in c] for c in hand_repr_player] i = input('Would you like one more card? ') i = i.upper() if i == 'Y': player.hand.append(game_deck.pop()) ask_player = False else: ask_player = True os.system('clear') or None bot_player = False while not bot_player: i = computer.play_game() if i is True: computer.hand.append(game_deck.pop()) else: bot_player = True result = dealer.check_winner(player.hand, computer.hand) bj.check_result(player, computer, bets, result) player.show_info() for c in hand_repr_player: for x in c: print(x) print("\n") computer.show_info() hand_repr_bot = card.show_card(computer.hand) for c in hand_repr_bot: for x in c: print(x) print("\n") choice = input("Do you wanna play again (Y/N): ") choice = choice.upper() game = bj.check_play_again(choice)
class Round(): # Deck setup deck = Deck() deck.shuffle() # Dealer setup dealer = Player( 'Dealer', PLAYER_TYPES.get('computer'), ) def __init__(self, pot, player): self.pot = pot self.player = player print(len(self.deck)) self.player.init_hand(self.deck.draw_card(2)) self.dealer.init_hand(self.deck.draw_card(2)) def show_hand(self, showdown=False): """ Shows player and dealer hands """ print('YOUR CARDS:') self.player.show_hand() print(f'SCORE: {self.player.get_score()}') print() print('DEALER CARDS:') self.dealer.show_hand(showdown) if showdown: print(f'SCORE: {self.dealer.get_score()}') print() def check_bust_blackjack(self): """ Checks player's hand for blackjack or bust """ if self.player.status == 1: clear() self.player.bankroll.add_funds(self.pot) print('BLACKJACK!!! YOU WIN!!') print() print('YOUR CARDS:') self.player.show_hand(True) print(f'SCORE: {self.player.get_score()}') print() print(self.player.bankroll) input() return True if self.player.status == -1: clear() print('BUST!!! YOU LOST!!') print() print('YOUR CARDS:') self.player.show_hand(True) print(f'SCORE: {self.player.get_score()}') print() print(self.player.bankroll) input() return True return False def showdown(self): """ Shows final hands, scores and result (win/lose) """ clear() print('SHOWDOWN') self.show_hand(True) dealer_bust = self.dealer.get_score() > 21 dealer_lose = self.player.get_score() >= self.dealer.get_score() if dealer_bust or dealer_lose: self.player.bankroll.add_funds(self.pot) print('YOU WON!') else: print('YOU LOST!') print(self.player.bankroll) def player_round(self): """ Starts player round """ while True: self.player.check_status() if self.player.status != 0: break clear() self.show_hand() hit = input('Do you want another card? (YES/no)') if hit.upper() == 'NO': self.player.check_status() break self.player.add_card(self.deck.draw_card(1).pop()) def computer_round(self): """ Starts computer round """ while self.dealer.get_score() < 21: clear() self.show_hand(True) input('Press any key...') if self.dealer.get_score() > self.player.get_score(): break self.dealer.add_card(self.deck.draw_card(1).pop())
class Game: def __init__(self, users: List[str]): self.users: List[str] = users self.n_of_players: int = len(users) self.players: List[Player] = self.init_players(users) self.deck = Deck() self.board: Board = Board(self.n_of_players) self.minister: Player = choice(self.players) self.director: Player = None self.last_minister: Player = None self.last_director: Player = None self.phase: GamePhase = GamePhase.PROPOSE_DIRECTOR self.cards: List[Card] = self.deck.take_3_cards() self.votes: Dict[str, Vote] = dict() self.last_update = datetime.now() self.casted_imperius_by: Player = None self.chaos_counter: int = 0 self.investigated_players: List[Player] = list() self.casted_expelliarmus: bool = False def init_players(self, users: List[str]): # Create empty players players: List[Player] = [] for user in users: players.append(Player(user)) # Calculate number of death eaters n_death_eaters = self.n_of_players // 2 if self.n_of_players % 2 == 0: n_death_eaters -= 1 # Randomize who are the death eaters death_eaters = sample(range(0, self.n_of_players), n_death_eaters) for i in death_eaters: players[i].set_role(Role.DEATH_EATER) players[i].set_loyalty(Loyalty.DEATH_EATER) # Assign one death eater to be voldemort players[choice(death_eaters)].set_role(Role.VOLDEMORT) # Assign the rest of the players to be fenix order for player in players: if player.get_role() == Role.TBD: player.set_role(Role.FENIX_ORDER) player.set_loyalty(Loyalty.FENIX_ORDER) return players def build_from_json(self, json): players = [] for user in json["player_list"]: new_player = Player(user) if user not in json["death_eaters"]: new_player.set_loyalty(Loyalty.FENIX_ORDER) new_player.set_role(Role.FENIX_ORDER) else: new_player.set_loyalty(Loyalty.DEATH_EATER) if json["voldemort"] == user: new_player.set_role(Role.VOLDEMORT) else: new_player.set_role(Role.DEATH_EATER) players.append(new_player) self.chaos_counter = json["chaos"] self.minister = next( (p for p in self.players if p.get_user() == json["minister"]), None) self.director = next( (p for p in self.players if p.get_user() == json["director"]), None) self.last_minister = next( (p for p in self.players if p.get_user() == json["last_minister"]), None) self.last_director = next( (p for p in self.players if p.get_user() == json["last_director"]), None) self.board.de_proclaims = json["de_procs"] self.board.fo_proclaims = json["fo_procs"] self.board.load_spells(json["spells"]) cards = [] for card in json["game_cards"]: if card == Card.FO.value: cards.append(Card.FO) else: cards.append(Card.DE) self.cards = cards self.players = players self.deck.load_deck(json["deck_cards"]) # Maybe set phase using the phase field in the json? if json["phase"] == GamePhase.PROPOSE_DIRECTOR.value: self.set_phase(GamePhase.PROPOSE_DIRECTOR) elif json["phase"] == GamePhase.VOTE_DIRECTOR.value: self.set_phase(GamePhase.VOTE_DIRECTOR) def get_minister_user(self): if self.minister is None: return "Undefined" else: return (self.minister.get_user()) def change_minister(self): """ Method that changes the current minister, it will be called at the beggining of a new turn. It changes the minister just assigning the role to the next player alive in the list of players of the match. """ if (self.casted_imperius_by is None): alive_players = list( filter(lambda p: (p.is_player_alive() or p == self.minister), self.players)) self.last_minister = self.minister last_minister_index = alive_players.index(self.last_minister) new_minister_index = (last_minister_index + 1) % (len(alive_players)) else: alive_players = list( filter( lambda p: (p.is_player_alive() or p == self.last_minister), self.players)) last_minister_index = alive_players.index(self.last_minister) new_minister_index = (last_minister_index + 1) % (len(alive_players)) self.last_minister = self.minister self.casted_imperius_by = None self.minister = alive_players[new_minister_index] def get_nof_players(self): return self.n_of_players def get_director_user(self): if self.director is None: return "Undefined" else: return (self.director.get_user()) def set_director(self, uname): if uname is None: self.director = None else: self.director = self.__get_player_by_uname(uname) def get_last_minister_user(self): if self.last_minister is None: return "Undefined" else: return (self.last_minister.get_user()) def get_last_director_user(self): if self.last_director is None: return "Undefined" else: return (self.last_director.get_user()) def get_de_procs(self): return (self.board.get_de_procs()) def get_fo_procs(self): return (self.board.get_fo_procs()) def get_cards(self): return self.cards def get_board_spells(self): result = {key.value: value for key, value in self.board.spells.items()} return result def get_deck(self): result = map(lambda c: c.value, self.deck.cards) return list(result) def discard(self, index): self.cards.pop(index) def is_expelliarmus_casted(self): return self.casted_expelliarmus def cast_expelliarmus(self): self.casted_expelliarmus = True def deal_cards(self): new_cards = self.deck.take_3_cards() self.cards = new_cards def get_current_players(self): """ method that makes a list from players in game TO DO: check if the lad is a fiambre """ unames: list = [] for player in self.players: unames.append(player.get_user()) return unames def get_alive_players(self): all_players = self.players alive_players = filter(lambda p: p.is_player_alive(), all_players) return list(map(lambda p: p.get_user(), alive_players)) def __get_player_by_uname(self, uname: str): player = next(p for p in self.players if p.get_user() == uname) return player def get_player_role(self, uname: str): return self.__get_player_by_uname(uname).get_role() def get_de_list(self): filtered = filter(lambda p: p.get_loyalty() == Loyalty.DEATH_EATER, self.players) return list(map(lambda p: p.get_user(), filtered)) def get_voldemort(self): voldemort = next(p for p in self.players if p.is_voldemort()) return voldemort.get_user() # option : This parameter is neceessary to check if a player # has already voted. def get_votes(self, option=False): if ((len(self.get_alive_players()) == len(self.votes) and self.phase == GamePhase.VOTE_DIRECTOR) or option): return self.votes return {} def register_vote(self, vote, uname: str): #self.votes[uname] = vote self.votes.update({uname: vote}) def get_phase(self): return self.phase def set_phase(self, phase: GamePhase): self.last_update = datetime.now() self.phase = phase def proc_top_card(self): card = self.deck.take_card() self.board.proclaim(card) self.reset_chaos() def get_chaos(self): return self.chaos_counter def reset_chaos(self): self.chaos_counter = 0 def do_chaos(self): self.proc_top_card() # Just decrease the spell number self.board.spell_check(self.n_of_players) def increase_chaos(self): if self.chaos_counter < 3: self.chaos_counter += 1 pass # ? async def compute_votes(self): votes = Counter(self.votes.values()) lumos_count = votes['Lumos'] nox_count = votes['Nox'] # Wait so the players can see the votes await async_sleep(5) if (lumos_count > nox_count): if (self.director.is_voldemort() and self.board.get_de_procs() >= 3): self.set_phase(GamePhase.DE_WON) else: self.set_phase(GamePhase.MINISTER_DISCARD) else: self.set_director(None) self.increase_chaos() if self.get_chaos() == 3: self.do_chaos() self.restart_turn() def proc_leftover_card(self): card = self.cards.pop(0) self.board.proclaim(card) self.reset_chaos() self.deal_cards() self.executive_phase() def get_top_card(self): return self.deck[0] def restart_turn(self): self.last_director = self.director self.director = None self.casted_expelliarmus = False self.votes.clear() self.change_minister() voldemort = next(p for p in self.players if p.is_voldemort()) if self.board.get_de_procs() >= 6: self.set_phase(GamePhase.DE_WON) elif self.board.get_fo_procs() >= 5 or not voldemort.is_player_alive(): self.set_phase(GamePhase.FO_WON) else: self.set_phase(GamePhase.PROPOSE_DIRECTOR) def executive_phase(self): spell = self.board.spell_check(self.n_of_players) if spell == Spell.DIVINATION: self.set_phase(GamePhase.CAST_DIVINATION) elif spell == Spell.AVADA_KEDAVRA: self.set_phase(GamePhase.CAST_AVADA_KEDAVRA) elif spell == Spell.IMPERIUS: self.set_phase(GamePhase.CAST_IMPERIUS) elif spell == Spell.CRUCIO: self.set_phase(GamePhase.CAST_CRUCIO) else: self.restart_turn() def divination(self): top_three = self.cards return top_three def avada_kedavra(self, target): for player in self.players: if target == player.get_user(): player.kill() self.restart_turn() def imperius(self, casted_by, target): for player in self.players: if casted_by == player.get_user(): self.casted_imperius_by = player if target == player.get_user(): self.last_director = self.director self.director = None self.last_minister = self.minister self.minister = player self.votes.clear() self.set_phase(GamePhase.PROPOSE_DIRECTOR) def get_investigated_players(self): return self.investigated_players def crucio(self, victim_uname: str): victim = self.__get_player_by_uname(victim_uname) self.investigated_players.append(victim_uname) return victim.get_loyalty().value def expelliarmus(self, vote): if (vote == 'Lumos'): self.cards = [] self.deal_cards() self.increase_chaos() if self.get_chaos() == 3: self.do_chaos() self.restart_turn() pass else: self.set_phase(GamePhase.REJECTED_EXPELLIARMUS) pass def player_can_speak(self, user: str): role_bool = user in [ self.get_minister_user(), self.get_director_user() ] phase_bool = self.get_phase() in [ GamePhase.MINISTER_DISCARD, GamePhase.DIRECTOR_DISCARD ] is_dead = not (self.__get_player_by_uname(user).is_player_alive()) return (not ((role_bool and phase_bool) or is_dead))
def game(): """ Gameplay """ #Initial setup deck = Deck() chips = 1000 print('Welcome to Blackjack!!\n') #Outer loop keeps going until player can't or doesn't want to play anymore while chips > 0: #Takes initial bet bet = input(f'You have {chips} chips. Enter your bet for this hand: ') while not bet.isdigit(): bet = input('Please enter a valid number') bet = int(bet) while bet > chips: bet = int( input( 'You cannoy bet more than you currently have. Enter another bet: ' )) #Sets up initial hand dealer_hand = Hand() player_hand = Hand() deal(deck, dealer_hand) deal(deck, dealer_hand) deal(deck, player_hand) deal(deck, player_hand) # Initial printouts dealer_hand.print_dealer() player_hand.print_hand(PLAYER) #Hit or stand while player_hand.value <= 21: hitstand = input('Would you like to hit (h) or stand(s)? ').lower() while not (hitstand == 'h' or hitstand == 's'): hitstand = input( 'Invalid input, please enter h for hit or s for stand: ' ).lower() #stand --> stop dealing cards if hitstand == 's': break else: deal(deck, player_hand) player_hand.print_hand(PLAYER) #Player busted if player_hand.value > 21: print('You busted! Dealer wins!') chips -= bet else: #Dealer hand plays out while dealer_hand.value <= 17: deal(deck, dealer_hand) #Print final hands dealer_hand.print_hand(DEALER) player_hand.print_hand(PLAYER) #Decide Winner if dealer_hand.value > 21: print('Dealer busted! Player wins!') chips += bet elif dealer_hand.value < player_hand.value: print('Player\'s hand is higher! Player wins!') chips += bet elif dealer_hand.value == player_hand.value: print('Tie! Chips returned') else: print('Dealer\'s hand is higher! Dealer wins!') chips -= bet #Play again? if chips > 0: play_again = input( 'Would you like to keep playing? Enter q to quit, anything else to continue: ' ).lower() if play_again == 'q': break print(f'Thanks for Playing! Total Winnings: ${chips - 1000}')