def play(self): poker_players = [] num_players = input("How many players? ") for i in range(int(num_players)): player_name = input("Name of poker player {}? ".format(i + 1)) poker_player = PokerPlayer(player_name) poker_players.append(poker_player) print("Dealing cards") deck = Deck() deck.shuffle() for i in range(7): for poker_player in poker_players: poker_player.add_card(deck.deal()) print(poker_player) if (i < 6): dealmore = input("Deal more card(y or n)? ") if (dealmore.lower() == 'n'): return for poker_player in poker_players: poker_player.review_all_fiver_hands() poker_score = poker_player.get_top_poker_score() print(poker_player.name.center(30, '-')) print(poker_score)
class TestDeck(unittest.TestCase): def setUp(self): self.deck = Deck() def test_is_constructed(self): self.assertIsInstance(self.deck, Deck) self.assertTrue(len(self.deck.cards), 52) def test_card_draw(self): self.assertIsInstance(self.deck.draw(), Card) def test_discard(self): card = self.deck.draw() self.deck.discard(card) self.assertTrue(len(self.deck.discard_pile), 1) def test_deck_reshuffled_if_all_cards_drawn(self): # draw and discard all cards for i in range(52): card = self.deck.draw() self.deck.discard(card) # draw initiates reshuffle card = self.deck.draw() self.deck.discard(card) self.assertEqual(len(self.deck.cards), 51) self.assertEqual(len(self.deck.discard_pile), 1)
def __init__(self, num_players=2): self.deck = Deck() self.hands = [] self.community_cards = [] self.num_players = num_players self.pot = 0 self.bet_amt = 0
def __init__(self): self._deck = Deck() self._deck.shuffle() # Pass the player and dealer two cards each self._player = Player([self._deck.deal(), self._deck.deal()]) self._dealer = Dealer([self._deck.deal(), self._deck.deal()])
def test_validate_influence(self): self.container = Deck(json='over_influence.json') self.assertFalse(self.container.validate_influence()) self.container = Deck(json='at_influence.json') self.assertTrue(self.container.validate_influence()) self.container = Deck(json='under_influence.json') self.assertTrue(self.container.validate_influence())
def test_validate_gte_minimum_deck_size(self): self.container = Deck(json='under_minimum_deck_size.json') self.assertFalse(self.container.validate_deck_size()) self.container = Deck(json='at_minimum_deck_size.json') self.assertTrue(self.container.validate_deck_size()) self.container = Deck(json='above_minimum_deck_size.json') self.assertTrue(self.container.validate_deck_size())
def shuffle_and_deal(self): self.deck = Deck() self.deck.shuffle() for seat in self.seats: seat.set_card_1(self.deck.deal()) for seat in self.seats: seat.set_card_2(self.deck.deal())
def setUp(self): # get a deck with no cards to test scoring self.score_deck = Deck() self.score_deck.cards = [] # get a regular deck self.deck = Deck() # get a Hand self.hand = Hand(self.deck)
def deal_start(self): """ deals the cards for the start of the game @return: tuple( hand:3Card deck table: 4 card Deck) """ hand = Deck([]) table = Deck([]) for i in range(0, 3): hand.cards.append(self.draw_pile.draw()) for i in range(0, 4): table.cards.append(self.draw_pile.draw()) return (hand, table)
def __init__(self): self._players_nb = None self._blend = None self._max_game = 100000 self._deck = Deck(6) strat_simple = Simple() strat_base = Base() self._dealer = Player(10000, 1, strat_simple, 'dealer') self._players = [] self._players.append(Player(0, 0, strat_base, 'guest'))
def __init__(self, players, verbose=False): """ players is a list of four players """ self.verbose = verbose if len(players) != 4: raise ValueError('There must be four players.') self.players = players # Invariant: the union of these lists makes up exactly one deck of cards deck = Deck() self._player_hands = tuple(deck.deal()) self._cards_taken = ([], [], [], [])
class Env: def __init__(self, conf): self.players = conf['players'] self.players.append("local") self.floor = conf['floor'] self.nb_card = conf['nb_card'] self.nb_round = conf['nb_round'] random.shuffle(self.players) def reset(self): self.board = Board(self.floor) self.deck = Deck() self.deck.deal(len(self.players), self.nb_card)
class Blackjack(object): def __init__(self): self._deck = Deck() self._deck.shuffle() # Pass the player and dealer two cards each self._player = Player([self._deck.deal(), self._deck.deal()]) self._dealer = Dealer([self._deck.deal(), self._deck.deal()]) def play(self): print("Player:\n", self._player) print("Dealer:\n", self._dealer) # Player hits until user says NO while True: choice = input("Do you want a hit? [y/n]: ") if choice in ("Y", "y"): self._player.hit(self._deck.deal()) points = self._player.getPoints() print("Player:\n", self._player) if points >= 21: break else: break playerPoints = self._player.getPoints() if playerPoints > 21: print("You bust and lose") else: # Dealer's turn to hit self._dealer.hit(self._deck) print("Dealer:\n", self._dealer) dealerPoints = self._dealer.getPoints() # Determine the outcome if dealerPoints > 21: print(" Dealer busts and you win") elif dealerPoints > playerPoints: print("Dealer wins") elif dealerPoints < playerPoints and playerPoints <= 21: print("You win") elif dealerPoints == playerPoints: if self._player.hasBlackjack() and \ not self._dealer.hasBlackjack(): print("You win") elif not self._player.hasBlackjack() and \ self._dealer.hasBlackjack(): print("Dealer wins") else: print("There is a tie")
class DeckTest(unittest.TestCase): def setUp(self): self.deck = Deck() def test_init(self): self.assertTrue(isinstance(self.deck.cards, list)) self.assertEqual(len(self.deck.cards), 52) def test_repr(self): self.assertEqual(repr(self.deck), "Deck of 52 cards.") def test_count(self): self.assertEqual(self.deck.count(), 52) self.deck.cards.pop() self.assertEqual(self.deck.count(), 51)
def __init__(self, gameid, draw_pile=None, players=[], game_board=[], prev_turn=[]): if not draw_pile: self.draw_pile = Deck() self.draw_pile.shuffle() else: self.draw_pile = draw_pile self.players = players self.game_board = game_board self.id = gameid self.prev_turn = prev_turn
def __init__(self): self.state = None self.state_history = [] self.width = 1300 self.height = 700 self.window = None self.clock = None # used for fps self.game_over = False # true when game is over self.title_image = None # title image self.empty_table = None # empty table image self.cards = Deck() self.cards.shuffle() # O(n) self.table = Table() self.player = Player('p') self.bot = Bot()
def setup(self): self.deck = Deck() self.player = Player() self.dealer = Dealer() for _ in range(2): self.player.hit(self.deck.next_card()) self.dealer.hit(self.deck.next_card())
class CardDemo(Frame): def __init__(self): """Sets up the window and widgets.""" Frame.__init__(self) self.master.title("Card Demo") self.grid() self._deck = Deck() self._backImage = PhotoImage(file=Card.BACK_NAME) self._cardImage = None self._imageLabel = Label(self, image=self._backImage) self._imageLabel.grid(row=0, column=0, rowspan=3) self._textLabel = Label(self, text="") self._textLabel.grid(row=3, column=0) # DealButton self._dealButton = Button(self, text="Deal", command=self._deal) self._dealButton.grid(row=0, column=1) # ShuffleButton self._shuffleButton = Button(self, text="Shuffle", command=self._shuffle) self._shuffleButton.grid(row=1, column=1) # newButton self._newButton = Button(self, text="New Deck", command=self._new) self._newButton.grid(row=2, column=1) def _deal(self): """If the deck is not empty, deals and display the next card. Otherwise, returns the program to its initial state.""" card = self._deck.deal() if card != None: self._cardImage = PhotoImage(file=card.fileName) self._imageLabel["image"] = self._cardImage self._textLabel["text"] = str(card) else: self._new() def _shuffle(self): self._deck.shuffle() def _new(self): """Returns the program to its initial state.""" self._deck = Deck() self._cardImage = None self._imageLabel["image"] = self._backImage self._textLabel["text"] = ""
def __init__(self, game_type: str) -> None: self.players: List[Player] = [] self.deck: Deck = Deck() self.playthrough: int = 0 self.discards: Deck = Deck() self.current_player_index: int = 0 self.status: str = 'Awaiting' # Awaiting, Running, Completed self.id: str = str(uuid.uuid4())[:6] self.stage_index: int = 0 self.market: List[Card] = [] self.trades: List[Trade] = [] self.winner = None self.game_type: str = game_type self.last_updates: List[Dict] = [] self.deck.build_deck() self.deck.shuffle()
def setup(self): """Setup game to prepare for round_loop() """ self.round = 1 self.players = [] self.deck = Deck() self.add_players() self.deal_cards()
def play_card(self, game, other_info={}, simulation_time_limit=1): for player_idx, suits in other_info.get("lacking_info", {}).items(): for suit in suits: game.lacking_cards[player_idx][suit] = True self.say("Player-{} may lack of {} suit({}, {})", player_idx, suit, game.lacking_cards[player_idx], other_info) self.say("Player-{}, the information of lacking_card is {}", \ self.position, [(player_idx, k) for player_idx, info in enumerate(game.lacking_cards) for k, v in info.items() if v]) hand_cards = [[] if player_idx != self.position else game._player_hands[player_idx] for player_idx in range(4)] remaining_cards = Deck().cards for card in self.seen_cards + hand_cards[self.position]: remaining_cards.remove(card) taken_cards = [] for player_idx, cards in enumerate(game._cards_taken): taken_cards.append(card_to_bitmask(cards)) init_trick = [[None, game.trick]] void_info = {} for player_idx, info in enumerate(game.lacking_cards): if player_idx != self.position: void_info[player_idx] = info must_have = self.transfer_cards selection_func = expert_choose self.say("proactive_mode: {}, selection_func={}, num_of_cpu={}", self.proactive_mode, selection_func, self.num_of_cpu) played_card = run_one_step( game.trick_nr + 1, self.position, self.num_hand_cards, copy.deepcopy(init_trick), hand_cards, game.is_heart_broken, [2 if player.expose else 1 for player in game.players], remaining_cards, taken_cards, None, selection_func, must_have, void_info) self.say("pick {} card", played_card) return played_card
def __init__(self, verbose=False): self.verbose = verbose if verbose: deck = Deck() deck.cards.sort(key=self.undesirability) self.say('Card undesirability: ') for card in deck.cards: self.say('{}: {}', card, self.undesirability(card))
class BlackJack: def __init__(self): self.deck = Deck() self.players = [Dealer(), Player()] self.max_players = max_players def add_player(self, player): if len(self.players) <= 8: raise TooManyPlayers self.players.append(player) def initial_deal(self): self.deck.shuffle() self.deck.cut() def deal(self): for player in players: player.hand.add_card(self.deck.draw())
def draw( player: 'Player', deck: Deck, num: int=1 ) -> typing.Tuple['Player', Deck]: if num not in range(1, len(deck) + 1): return player, deck return ( Player(player.name(), hand=player.hand() + Cards(deck[:num])), Deck(deck[num:]))
def get_remaining_cards(self, hand_cards): deck = Deck() remaining_cards = [] for c in deck.cards: for pc in hand_cards + self.seen_cards: if c == pc: break else: remaining_cards.append(c) return remaining_cards
def __init__(self): deck = Deck() deck.shuffle() deck = deck.get_cards() piles: List[List[Card]] = [] for i in range(Game.PILES): piles.append([]) pile_len = i + 1 for j in range(pile_len): card = deck.pop() if not j == pile_len - 1: card.visible = False piles[i].append(card) hand: List[Card] = [] self.varInput = VarInput() self.deck = deck self.hand = hand self.piles = piles self.finished = [0] * len(Card.SUITS)
def reset(self): self.trick_nr = 0 self.current_player_idx = 0 self.trick = [] self.trick_cards = [] for _ in range(13): self.trick_cards.append([None, None, None, None]) self.player_scores = [0, 0, 0, 0] self.player_action_pos = [[0] * 13, [0] * 13, [0] * 13, [0] * 13] self.expose_info = [1, 1, 1, 1] self.take_pig_card = False self.is_heart_broken = False self.is_shootmoon = False for i in range(4): self.players[i].set_position(i) self.players[i].reset() deck = Deck() self._player_hands = list(deck.deal()) self._cards_taken = ([], [], [], []) self._b_cards_taken = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] self._temp_score = [0, 0, 0, 0] self.lacking_cards = [] for _ in range(4): self.lacking_cards.append({ Suit.spades: False, Suit.hearts: False, Suit.diamonds: False, Suit.clubs: False })
class Game: def __init__(self): self._players_nb = None self._blend = None self._max_game = 100000 self._deck = Deck(6) strat_simple = Simple() strat_base = Base() self._dealer = Player(10000, 1, strat_simple, 'dealer') self._players = [] self._players.append(Player(0, 0, strat_base, 'guest')) def play(self): game_nb = 1 while game_nb <= self._max_game: # Get a new deck if needed if self._deck.isFinished(): self._deck.initCards() # Players bet beters = [] for player in self._players: if player.bet(): beters.append(player) # Dealer picks one card self._dealer.getMainHand().addCard(self._deck.pick()) # Players pick 2 cards for i in [1, 2]: for player in self._players: player.getMainHand().addCard(self._deck.pick()) # Players play for player in self._players: player.play(self._deck, self._dealer.getMainHand()) # Dealer plays self._dealer.getMainHand().addCard(self._deck.pick()) self._dealer.play(self._deck) # Money transferts for player in self._players: player.getGains(self._dealer.getMainHand()) self._dealer._chairs = [] game_nb += 1 print "FINAL : {0:.2f}€ in {1:.0f} hours. [{2:.2f}% benefit, {3:.2f} €/h]"\ .format(self._players[0]._pot, game_nb / 50, self._players[0]._pot / game_nb, self._players[0]._pot / (game_nb / 50))
def __init__(self): """Sets up the window and widgets.""" Frame.__init__(self) self.master.title("Card Demo") self.grid() self._deck = Deck() self._backImage = PhotoImage(file=Card.BACK_NAME) self._cardImage = None self._imageLabel = Label(self, image=self._backImage) self._imageLabel.grid(row=0, column=0, rowspan=3) self._textLabel = Label(self, text="") self._textLabel.grid(row=3, column=0) # DealButton self._dealButton = Button(self, text="Deal", command=self._deal) self._dealButton.grid(row=0, column=1) # ShuffleButton self._shuffleButton = Button(self, text="Shuffle", command=self._shuffle) self._shuffleButton.grid(row=1, column=1) # newButton self._newButton = Button(self, text="New Deck", command=self._new) self._newButton.grid(row=2, column=1)
def play(): print('********************') print('* Blackjack') dealer = Player(name='Dealer') guest = Player(name='Guest') deck = Deck().shuffle().shuffle() for _ in range(2): dealer, deck = Player.draw(dealer, deck) guest, deck = Player.draw(guest, deck) print('') print(f"{dealer.name()}'s 1st card: " + str(dealer.hand()[0])) print('') print(f"* {guest.name()}'s turn *") Blackjack._show_hand(guest) while not BlackjackRule.busts(guest): decision = GuestDecision.decide() if decision is GuestDecision.STAND: break if decision is GuestDecision.HIT: guest, deck = Player.draw(guest, deck) Blackjack._show_hand(guest) else: print('Bust!') Blackjack._result(dealer=dealer, guest=guest) return print('') print(f"* {dealer.name()}'s turn *") Blackjack._show_hand(dealer) while not BlackjackRule.busts(dealer): if BlackjackRule.point(dealer) >= 17: break else: dealer, deck = Player.draw(dealer, deck) Blackjack._show_hand(dealer) else: print('Bust!') Blackjack._result(dealer=dealer, guest=guest) return Blackjack._result(dealer=dealer, guest=guest)
def __init__(self, player1, player2, player3, player4): self.cpu1 = player1 self.cpu2 = player2 self.cpu3 = player3 self.cpu4 = player4 self.deck = Deck() self.deck.shuffle() self.games = BIDDINGS self.game_to_be_played = 'Pass' self.cpu1.coplayer = self.cpu3 self.cpu2.coplayer = self.cpu4 self.cpu3.coplayer = self.cpu1 self.cpu4.coplayer = self.cpu2 self.team1 = p.Team(self.cpu1, self.cpu3) self.team2 = p.Team(self.cpu2, self.cpu4) self.single_hand = [self.cpu1, self.cpu2, self.cpu3, self.cpu4]
def __init__(self, verbose=False): self.seen_cards = [] self.freeze_cards = [] self.transfer_cards = {} self.name = None self.position = None self.expose = False self.proactive_mode = set() self.void_info = { 0: { Suit.spades: False, Suit.hearts: False, Suit.diamonds: False, Suit.clubs: False }, 1: { Suit.spades: False, Suit.hearts: False, Suit.diamonds: False, Suit.clubs: False }, 2: { Suit.spades: False, Suit.hearts: False, Suit.diamonds: False, Suit.clubs: False }, 3: { Suit.spades: False, Suit.hearts: False, Suit.diamonds: False, Suit.clubs: False } } self.remaining_cards = set(Deck().cards) self.num_hand_cards = {0: 13, 1: 13, 2: 13, 3: 13} self.verbose = verbose
def test_validate_only_one_identity(self): self.container = Deck(json='two_identities.json') self.assertFalse(self.container.validate_has_only_one_identity()) self.container = Deck(json='one_identity.json') self.assertTrue(self.container.validate_has_only_one_identity())
class Round: def __init__(self, player1, player2, player3, player4): self.cpu1 = player1 self.cpu2 = player2 self.cpu3 = player3 self.cpu4 = player4 self.deck = Deck() self.deck.shuffle() self.games = BIDDINGS self.game_to_be_played = 'Pass' self.cpu1.coplayer = self.cpu3 self.cpu2.coplayer = self.cpu4 self.cpu3.coplayer = self.cpu1 self.cpu4.coplayer = self.cpu2 self.team1 = p.Team(self.cpu1, self.cpu3) self.team2 = p.Team(self.cpu2, self.cpu4) self.single_hand = [self.cpu1, self.cpu2, self.cpu3, self.cpu4] def valid_games(self, called): if called == 'Pass' or called not in self.games: pass else: i = self.games.index(called) self.games = self.games[:i] def set_pregame(self): self.cpu1.add_cards(self.deck[0:5]) self.cpu2.add_cards(self.deck[5:10]) self.cpu3.add_cards(self.deck[10:15]) self.cpu4.add_cards(self.deck[15:20]) self.deck.remove(self.deck[0:20]) def pregame(self): self.set_pregame() c1 = self.cpu1.pregame(self.games) c2 = self.cpu2.pregame(self.games) c3 = self.cpu3.pregame(self.games) c4 = self.cpu4.pregame(self.games) if all([c == 'Pass' for c in [c1, c2, c3, c4]]): self.game_to_be_played = 'Pass' else: BREAKER = -1 while True: c1 = self.cpu1.pregame(self.games) self.valid_games(c1) if c1 == 'Pass': BREAKER += 1 else: BREAKER = 0 if BREAKER == 3: self.game_to_be_played = c2 break c2 = self.cpu2.pregame(self.games) self.valid_games(c2) if c2 == 'Pass': BREAKER += 1 else: BREAKER = 0 if BREAKER == 3: self.game_to_be_played = c3 break c3 = self.cpu3.pregame(self.games) self.valid_games(c3) if c3 == 'Pass': BREAKER += 1 else: BREAKER = 0 if BREAKER == 3: self.game_to_be_played = c4 break c4 = self.cpu4.pregame(self.games) self.valid_games(c4) if c4 == 'Pass': BREAKER += 1 else: BREAKER = 0 if BREAKER == 3: self.game_to_be_played = c1 break def set_rest_of_cards(self): self.cpu1.add_cards(self.deck[0:3]) self.cpu2.add_cards(self.deck[3:6]) self.cpu3.add_cards(self.deck[6:9]) self.cpu4.add_cards(self.deck[9:12]) self.deck.remove(self.deck[0:12]) def reorder(self, index): self.single_hand = self.single_hand[index:] + self.single_hand[:index] def take_cards(self): curr_type = p.ALL_GIVEN_CARDS_ON_TABLE[0].type if self.game_to_be_played == 'All Trumps': arr = [] for c in p.ALL_GIVEN_CARDS_ON_TABLE[1:]: if c.type == curr_type: arr.append(c) if len(arr) == 0: return 0 else: res = [all_trumps_dic[c.value] for c in arr] max_value = max(res) if max_value < all_trumps_dic[p.ALL_GIVEN_CARDS_ON_TABLE[0].value]: return 0 else: for i in range(len(arr)): if all_trumps_dic[arr[i].value] == max_value: return p.ALL_GIVEN_CARDS_ON_TABLE.index(arr[i]) elif self.game_to_be_played == 'No Trumps': arr = [] for c in p.ALL_GIVEN_CARDS_ON_TABLE[1:]: if c.type == curr_type: arr.append(c) if len(arr) == 0: return 0 else: res = [no_trumps_dic[c.value] for c in arr] max_value = max(res) if max_value < no_trumps_dic[p.ALL_GIVEN_CARDS_ON_TABLE[0].value]: return 0 else: for i in range(len(arr)): if no_trumps_dic[arr[i].value] == max_value: return p.ALL_GIVEN_CARDS_ON_TABLE.index(arr[i]) else: arr = [] curr_type = self.game_to_be_played if p.ALL_GIVEN_CARDS_ON_TABLE[0].type == curr_type: for card in p.ALL_GIVEN_CARDS_ON_TABLE[1:]: if card.type == curr_type and all_trumps_dic[card.value] > all_trumps_dic[p.ALL_GIVEN_CARDS_ON_TABLE[0].value]: arr.append(card) if len(arr) == 0: return 0 else: result = [all_trumps_dic[c.value] for c in arr] max_value = max(result) for i in range(len(arr)): if all_trumps_dic[arr[i].value] == max_value: return p.ALL_GIVEN_CARDS_ON_TABLE.index(arr[i]) elif p.ALL_GIVEN_CARDS_ON_TABLE[0].type != curr_type: for card in p.ALL_GIVEN_CARDS_ON_TABLE[1:]: if card.type == curr_type: arr.append(card) if len(arr) != 0: result = [all_trumps_dic[c.value] for c in arr] max_value = max(result) for i in range(len(arr)): if all_trumps_dic[arr[i].value] == max_value: return p.ALL_GIVEN_CARDS_ON_TABLE.index(arr[i]) else: result = [no_trumps_dic[c.value] for c in p.ALL_GIVEN_CARDS_ON_TABLE] max_value = max(result) for i in range(len(arr)): if no_trumps_dic[arr[i].value] == max_value: return p.ALL_GIVEN_CARDS_ON_TABLE.index(arr[i]) def game_on(self): self.pregame() print(self.game_to_be_played) self.set_rest_of_cards() print([str(x) for x in self.cpu1.cards]) print([str(x) for x in self.cpu2.cards]) print([str(x) for x in self.cpu3.cards]) print([str(x) for x in self.cpu4.cards]) cur_res1 = 0 cur_res2 = 0 while len(p.ALL_GIVEN_CARDS) < 32: if len(p.ALL_GIVEN_CARDS_ON_TABLE) == 0: if self.game_to_be_played == 'All Trumps': print(self.single_hand[0].name) self.single_hand[0].throw_card( all_trumps_logic(self.single_hand[0], self.single_hand[2])) print(self.single_hand[1].name) self.single_hand[1].throw_card( all_trumps_logic(self.single_hand[1], self.single_hand[3])) print(self.single_hand[2].name) self.single_hand[2].throw_card( all_trumps_logic(self.single_hand[2], self.single_hand[0])) print(self.single_hand[3].name) self.single_hand[3].throw_card( all_trumps_logic(self.single_hand[3], self.single_hand[1])) print("\n") elif self.game_to_be_played == 'No Trumps': print(self.single_hand[0].name) self.single_hand[0].throw_card( no_trumps_logic(self.single_hand[0], self.single_hand[2])) print(self.single_hand[1].name) self.single_hand[1].throw_card( no_trumps_logic(self.single_hand[1], self.single_hand[3])) print(self.single_hand[2].name) self.single_hand[2].throw_card( no_trumps_logic(self.single_hand[2], self.single_hand[0])) print(self.single_hand[3].name) self.single_hand[3].throw_card( no_trumps_logic(self.single_hand[3], self.single_hand[1])) print("\n") elif self.game_to_be_played in CARD_TYPES: self.single_hand[0].throw_card( game_type_logic(self.game_to_be_played, self.single_hand[0], self.single_hand[2])) print(game_type_logic(self.game_to_be_played, self.single_hand[0], self.single_hand[2])) self.single_hand[1].throw_card( game_type_logic(self.game_to_be_played, self.single_hand[1], self.single_hand[3])) print(game_type_logic(self.game_to_be_played, self.single_hand[1], self.single_hand[3])) self.single_hand[2].throw_card( game_type_logic(self.game_to_be_played, self.single_hand[2], self.single_hand[0])) print('---------------------') print(game_type_logic(self.game_to_be_played, self.single_hand[2], self.single_hand[0])) self.single_hand[3].throw_card( game_type_logic(self.game_to_be_played, self.single_hand[3], self.single_hand[1])) print(game_type_logic(self.game_to_be_played, self.single_hand[3], self.single_hand[1])) else: break winner = self.take_cards() if winner == 0 or winner == 2: self.team1.take_hand(p.ALL_GIVEN_CARDS_ON_TABLE) self.reorder(winner) cur_res1 += self.team1.cards_to_points(self.game_to_be_played) del p.ALL_GIVEN_CARDS_ON_TABLE[:] else: self.team2.take_hand(p.ALL_GIVEN_CARDS_ON_TABLE) self.reorder(winner) cur_res2 += self.team2.cards_to_points(self.game_to_be_played) del p.ALL_GIVEN_CARDS_ON_TABLE[:] sleep(2)
class Game(object): def setup(self): self.deck = Deck() self.player = Player() self.dealer = Dealer() for _ in range(2): self.player.hit(self.deck.next_card()) self.dealer.hit(self.deck.next_card()) def player_turn(self): player_choice = input("[H]it, [S]tay, or [Q]uit?").lower() os.system('clear') if player_choice == 'h': self.player.hit(self.deck.next_card()) self.display_info() if self.player.hand_value() > 21: pass else: self.player_turn() elif player_choice == 's': pass elif player_choice == 'q': sys.exit() else: self.player_turn def dealer_turn(self): while self.dealer.hand_value() <= 16: self.display_info(True) time.sleep(2) self.dealer.hit(self.deck.next_card()) def check_for_outcome(self): if self.dealer.hand_value() > 21: print("Dealer bust! You Win!") self.play_again() elif self.player.hand_value() > self.dealer.hand_value(): print("You win!") elif self.player.hand_value() < self.dealer.hand_value(): print("You lose!") elif self.player.hand_value() == self.dealer.hand_value(): print("Push!") def check_for_bust(self): if self.player.hand_value() > 21: print("You bust! You lose!") self.play_again() def display_info(self,show = False): os.system('clear') print("Blackjack") print("="*20) if show: print(self.dealer) else: print(self.dealer.hidden()) print(self.player) print("="*20) def play_again(self): play_again = input("Do you want to play again? [Y]/[N]?").lower() if play_again == 'y': Game() else: sys.exit() def __init__(self): self.setup() self.display_info() self.player_turn() self.check_for_bust() self.display_info(True) self.dealer_turn() self.display_info(True) self.check_for_outcome() self.play_again()
def load(self, id_code): with open(__directory + '/' + id_code + '.' + __file_extension) as player_file: player = pickle.decode(player_file) self.id_code = player.id_code self.name = player.name self.decks = [Deck.from_list(deck) for deck in player.decks]
class Sushi_Game(Game): def setup(self): """Setup game to prepare for round_loop() """ self.round = 1 self.players = [] self.deck = Deck() self.add_players() self.deal_cards() def play(self): """Play sushi game """ while True: self.show_hand() if self.players[0].pre_hand: # player has pre_hand cards print_key(self) # show useful info self.choose_card() self.swap_hands() else: #round over update_points(self, self.players, self.round, TOTAL_ROUNDS) self.show_score() # show player score if self.round < TOTAL_ROUNDS: #not final round self.round += 1 self.deal_cards() #play again else: #final round, game over self.decide_winner() break def choose_card(self): """Prompts user to choose a card from player.pre_hand adds chosen card to post_hand if player chooses nigiri, check for wasabi """ choice = input("Which plate do you want to keep? ").upper() if check_choice_validity(self, choice) == False: self.choose_card() if check_hand_for_card(self, self.players[0].pre_hand, choice) == False: self.choose_card() index = index_of_choice(self, choice, self.players[0].pre_hand) # Nigiri and Wasabi if choice == 'N' and self.players[0].wasabi: # player has wasabi dip = input("Dip in wasabi? [Y/N] ").upper() if dip == 'Y': self.players[0].pre_hand[index].points *= WASABI_MULTIPLIER self.players[0].wasabi -= 1 if choice == 'W': self.players[0].wasabi += 1 # move card to post_hand self.players[0].post_hand.append(self.players[0].pre_hand.pop(index)) # one robot #self.computer.post_hand.append(self.computer.pre_hand.pop()) # multiple robots index = 1 for player in self.players: if index > len(self.players)-1: break self.players[index].post_hand.append(self.players[index].pre_hand.pop()) index += 1 def swap_hands(self): """ Swaps pre_hands for all players in players[] """ last_hand = self.players[len(self.players)-1].pre_hand for player in self.players: temp = player.pre_hand player.pre_hand = last_hand last_hand = temp def add_players(self): """Adds player objects to self.players[] """ name = input("What's your name? ") self.player = User(name) self.players.append(self.player) # one robot #self.computer = Computer("name") #self.players.append(self.computer) # multiple robots num_opponents = int(input("How many robots would you like to play against? [1, 2, 3, or 4] ")) while num_opponents: name = input("Robot name please... ") self.computer = Computer(name) self.players.append(self.computer) num_opponents -= 1 def deal_cards(self): """Deal cards to each player to begin a round """ # if players already have cards, remove them if self.players[0].post_hand: for player in self.players: #don't remove pudding! puddings = 0 for card in player.post_hand: if card.name == 'Pudding': puddings += 1 other_cards = True while (other_cards): if len(player.post_hand) == puddings: other_cards = False for card in player.post_hand: if card.name != 'Pudding': player.post_hand.remove(card) player.pre_hand = [] player.wasabi = 0 # deal cards to pre_hand for player in self.players: for _ in range(CARDS_PER_PLAYER[len(self.players)]): player.hit(self.deck.next_card()) def show_hand(self): """Show hand """ self.clear() print("Sushi Go") print("="*20) print("Conveyor Belt") hand = ', '.join(str(x) for x in self.player.pre_hand) print(hand) print("="*20) print("{}'s Plates".format(self.player.name)) hand = ', '.join(str(x) for x in self.player.post_hand) print(hand) print("="*20) def show_score(self): """Show score after round of play """ # show score for all players for player in self.players: print("{}:Round={} Total={}".format(player.name, player.points, player.total_points)) input("Press Enter to continue...") # show point tabulation for user? point_tabulation(self) def decide_winner(self): """Iterate through players to determine final scoring order (eg 1st, 2nd, 3rd...) """ self.clear() standings = [] index = 0 for player in self.players: standings.append((index, player.total_points)) index += 1 standings.sort(key=lambda tup: tup[1], reverse=True) index = 1 for tup in standings: print("{}. {} with {} points".format(index, self.players[tup[0]].name, self.players[tup[0]].total_points)) index += 1 def clear(self): """Clear the screen """ os.system('cls' if os.name == 'nt' else 'clear') # initializer def __init__(self): """Play a game of sushi game """ self.setup() self.play()
def __init__(self, name='dealer', cash_balance=100, number_of_decks=1): self.name = name self.cash_balance = cash_balance self.number_of_decks = number_of_decks self.deck = Deck(self.number_of_decks) self.hand = Hand()
""" for c in hand: if c.rank.rank == Rank.jack: if c.suit == starter.suit: return 1 return 0 if __name__ == '__main__': import doctest doctest.testmod() # Play around verbose = False deck = Deck() n_hands = 1000000 hist = {} total = 0 mn = 30 mx = -1 for h in range(n_hands): deck.shuffle() hand = [] for i in range(4): hand.append(deck.deal.next()) starter = deck.deal.next()
self.hand.sort(key=partial(card_func_key, valueby='rank')) def card_count(self): return len(self.hand) def has_empty_hand(self): return not self.hand if __name__ == '__main__': from card import Deck """Reference: Implementing an Unordered List: Linked Lists http://interactivepython.org/courselib/static/pythonds/BasicDS/ImplementinganUnorderedListLinkedLists.html """ deck = Deck() deck.shuffle() john = Player('John') jane = Player('Jane') jess = Player('Jess') june = Player('June') jack = Player('Jack') player_list = ActivePlayer(john, jane, jess, june) # player_list.in_control(june) # player_list.remove(june) # print(player_list.next_turn()) # print(player_list.next_turn()) # print(player_list.next_turn()) # print(player_list.next_turn())
class DeckTests(TestHelper): def test_validate_agenda_points(self): self.container = Deck(json='missing_agenda.json') self.assertFalse(self.container.validate_agenda_points()) self.container = Deck(json='correct_agenda.json') self.assertTrue(self.container.validate_agenda_points()) def test_validate_composition(self): self.container = Deck(json='mixed.json') self.assertFalse(self.container.validate_composition()) self.container = Deck(json='only_weyland.json') self.assertTrue(self.container.validate_composition()) def test_validate_only_one_identity(self): self.container = Deck(json='two_identities.json') self.assertFalse(self.container.validate_has_only_one_identity()) self.container = Deck(json='one_identity.json') self.assertTrue(self.container.validate_has_only_one_identity()) def test_validate_influence(self): self.container = Deck(json='over_influence.json') self.assertFalse(self.container.validate_influence()) self.container = Deck(json='at_influence.json') self.assertTrue(self.container.validate_influence()) self.container = Deck(json='under_influence.json') self.assertTrue(self.container.validate_influence()) def test_validate_gte_minimum_deck_size(self): self.container = Deck(json='under_minimum_deck_size.json') self.assertFalse(self.container.validate_deck_size()) self.container = Deck(json='at_minimum_deck_size.json') self.assertTrue(self.container.validate_deck_size()) self.container = Deck(json='above_minimum_deck_size.json') self.assertTrue(self.container.validate_deck_size())
class Game: def __init__(self): self.state = None self.state_history = [] self.width = 1300 self.height = 700 self.window = None self.clock = None # used for fps self.game_over = False # true when game is over self.title_image = None # title image self.empty_table = None # empty table image self.cards = Deck() self.cards.shuffle() # O(n) self.table = Table() self.player = Player('p') self.bot = Bot() def init(self): pygame.init() # setup pygame self.window = pygame.display.set_mode( (self.width, self.height)) # initializes the window pygame.display.set_caption("Texas Holdem") # Title of window self.clock = pygame.time.Clock() self.title_image = pygame.image.load("PNG-cards-1.3/title_image.png") self.title_image = pygame.transform.scale( self.title_image, (self.width, self.height)) # resizing self.empty_table = pygame.image.load("PNG-cards-1.3/empty_table.jpg") self.empty_table = pygame.transform.scale( self.empty_table, (self.width, self.height)) # resizing self.game_over = False def set_game_state(self, state): self.state = state self.state_history.append(state) def infer_state(self, player_turn, table, current_call, can_raise, done): if done: self.set_game_state(GameState.END_ROUND) return if not can_raise: self.set_game_state(GameState.ALL_IN) return self.set_game_state( GameState.calc_state( table, player_turn, type(current_call) is int and current_call > 0)) return def get_events(self): return pygame.event.get() def is_over(self): return self.game_over def end_game(self): pygame.quit() quit()
def test_validate_agenda_points(self): self.container = Deck(json='missing_agenda.json') self.assertFalse(self.container.validate_agenda_points()) self.container = Deck(json='correct_agenda.json') self.assertTrue(self.container.validate_agenda_points())
def test_validate_composition(self): self.container = Deck(json='mixed.json') self.assertFalse(self.container.validate_composition()) self.container = Deck(json='only_weyland.json') self.assertTrue(self.container.validate_composition())