def createPlayingDeck(suites: List[Suite], ranks: List[Rank]) -> Deck: deck = Deck() for rank in ranks: for suite in suites: card = Card(rank, suite) deck.pushToTop(card) return deck
def shuffleDeck(self, deck: Deck): """ shuffles deck """ #:: remove all the cards from the deck. cards = deck.popAll() #:: shuffle the list. random.shuffle(cards) #:: put it pack in the deck. deck.extend(cards)
def test_get_suit(self): """ This tests whether the correct suit is returned given different card indices """ d = Deck() actual_suits1 = [d.get_suit(i) for i in [0, 13, 26, 39]] actual_suits2 = [d.get_suit(i) for i in [5, 18, 31, 44]] self.assertListEqual(actual_suits1, d.suits) self.assertListEqual(actual_suits2, d.suits)
def test_draw_edge(self): """ This tests whether the deck can correctly be drawn from until exhaustion """ d = Deck() curr_num_cards = 52 while d.draw(): curr_num_cards -= 1 self.assertEqual(sum(d.cards), curr_num_cards)
def setUp(self): self.example_card_1 = self.card_library.get_card(name="Plains") self.example_card_2 = self.card_library.get_card(name="Island") self.example_card_3 = self.card_library.get_card(name="Swamp") self.example_card_4 = self.card_library.get_card(name="Mountain") self.example_card_5 = self.card_library.get_card(name="Forest") self.example_deck = Deck([ self.example_card_1, self.example_card_2, self.example_card_3, self.example_card_4, self.example_card_5 ])
class testDeck(TestCase): def setUp(self): self.deck = Deck() def testDeckCreation(self): pass def testThatCardsCanBeAdded(self): card = Mock() self.deck.addCard(card) self.assertIn(card, self.deck.cards)
def setUp(self): suites = [Suite.HEART, Suite.TILES] ranks = [ Rank.ACE, Rank.KING, ] self.initial_deck = createPlayingDeck(suites, ranks) player_one = Player("Mario", Deck()) player_two = Player("Luigi", Deck()) self.players = [player_one, player_two] self.shuffle_strategy = SimpleShuffleStrategy() self.ranking_strategy = RankScore()
def __init__(self, logger, **kwargs): """ constructor :param logger: logger :param kwargs: inherited params """ super().__init__(logger, True, **kwargs) self.init_socket() self.deck = Deck(self.logger) self.round = 0 self.player_earnings = 0 self.tie = False self.player_card = None self.dealer_card = None self.bet = 0
def test_player_deck(self): deck = Deck() player = Player("Mustapha", deck) #:: cards = [Card(Rank.ACE, Suite.HEART), Card(Rank.TWO, Suite.PIKES)] player.addToDeckBottom(cards) self.assertEqual(player.popDeckTopCard(), cards[0]) self.assertEqual(player.popDeckTopCard(), cards[1])
class TestDeck(unittest.TestCase): @classmethod def setUpClass(cls): cls.card_library = CardLibrary() def setUp(self): self.example_card_1 = self.card_library.get_card(name="Plains") self.example_card_2 = self.card_library.get_card(name="Island") self.example_card_3 = self.card_library.get_card(name="Swamp") self.example_card_4 = self.card_library.get_card(name="Mountain") self.example_card_5 = self.card_library.get_card(name="Forest") self.example_deck = Deck([ self.example_card_1, self.example_card_2, self.example_card_3, self.example_card_4, self.example_card_5 ]) def test_shuffle(self): """ Checks whether or not the shuffle() method randomly reorders the cards in a Deck. """ self.example_deck.shuffle() drawn_card = self.example_deck.draw() self.assertIsNot(drawn_card, self.example_card_1) def test_draw(self): """ Checks whether or not the draw() method correctly removes and returns a Card from a Deck. """ initial_size = self.example_deck.size drawn_card = self.example_deck.draw() self.assertIsInstance(drawn_card, Card) self.assertEqual(self.example_deck.size, initial_size - 1) def test_add_card(self): """ Checks that the Deck.add_card() method adds a Card to a Deck. """ another_card = self.card_library.get_card(name="Wasteland") self.assertNotIn(another_card, self.example_deck) self.example_deck._add_card(another_card) self.assertIn(another_card, self.example_deck) def test_add_cards(self): """ Checks that the Deck.add_cards() method adds multiple Cards to a Deck. """ another_card = self.card_library.get_card(name="Wasteland") another_card_2 = self.card_library.get_card(name="Strip Mine") self.assertNotIn(another_card, self.example_deck) self.assertNotIn(another_card_2, self.example_deck) self.example_deck._add_cards([another_card, another_card_2]) self.assertIn(another_card, self.example_deck) self.assertIn(another_card_2, self.example_deck)
def __createDeck(self): """Command to create a new Deck""" # TODO: Get the user to specify the card size, max number, and number of cards size = self.__getNumberInput("Card Size: ") while size < 3 or size > 15: print("That is not a valid size!\n") size = self.__getNumberInput("Card Size: ") max_num = self.__getNumberInput("\nMax Number: ") while max_num < 2*size*size or max_num > 4*size*size: print("That is not a valid max number!\n") max_num = self.__getNumberInput("Max Number: ") num_cards = self.__getNumberInput("\nNumber of Cards: ") while num_cards < 3 or num_cards > 10000: print("That is not a valid number of cards!\n") num_cards = self.__getNumberInput("Number of Cards: ", ) # TODO: Create a new deck self.__m_currentDeck = Deck(size, num_cards, max_num) # TODO: Display a deck menu and allow use to do things with the deck self.__deckMenu()
def display_next_hand(*args): """ Create the card list use Deck().deal and display_cardlist them""" global twentyfive_cards, six_hands # disable show_next and enable show_best # print ("running display_next_hand") display_best25_hand_button["state"] = "normal" display_next_hand_button["state"] = "disabled" six_hands = Deck(6, 25, 3).deal() pyramid_poker_hand = six_hands[0] twentyfive_cards = (sorted(pyramid_poker_hand, key=rank_sort, reverse=True)) window.title("Play Pyramid Poker") w.delete("all") # clear out last hand # playing_board is list(number of white squares, then list of yellow cells) playing_board = [[0, []], [1, []], [3, []], [5, [3, 4]], [6, [3, 4, 5]], [8, [5, 6, 7]], [10, [5, 6, 7, 8, 9]]] X_OFFSET = 5 * X_GAP + 5 y = Y_OFFSET for hand_show in playing_board[6:0:-1]: x = X_OFFSET fill_color = "white" squares = hand_show[0] yellow = hand_show[1] for i in range(squares): if i in yellow: fill_color = "light yellow" w.create_rectangle((x, y, x + X_GAP, y + Y_GAP), fill=fill_color, tag=("hand" + str(i), "board")) x += X_GAP y += Y_GAP # create 5 grey rectangles - discards x = 5 for i in range(5): fill_color = "light grey" w.create_rectangle((x, y, x + X_GAP, y + Y_GAP), fill=fill_color, tags=("hand3", "board")) x += X_GAP show_twentyfive_cards() rank_button["state"] = "disabled" # clear out player, best and diff scores for previous hand x = 10 * X_GAP + 6 y = 3 * Y_GAP + 15 display_points_clear(x, y) # best hand points
class TestDeck(unittest.TestCase): def setUp(self): self.deck = Deck(cardSize=7, cardCount=3, numberMax=100) self.deck1 = Deck(0, 0, 0) def test_getCardCount(self): self.assertNotEqual(self.deck.getCardCount(), 0) self.assertEqual(self.deck.getCardCount(), 3) self.assertEqual(self.deck1.getCardCount(), 0) def test_getCard(self): self.assertIsNotNone(self.deck.getCard(1)) self.assertIsNone(self.deck.getCard(0)) self.assertIsNone(self.deck1.getCard(1)) # This requires the students to name their card array __m_cards. # .. It also accesses a private member which may not be preferred. self.assertIs(self.deck._Deck__m_cards[0], self.deck.getCard(1)) self.assertIs(self.deck._Deck__m_cards[1], self.deck.getCard(2)) self.assertIs(self.deck._Deck__m_cards[2], self.deck.getCard(3)) self.assertIsNot(self.deck._Deck__m_cards[0], self.deck.getCard(2)) self.assertIsNot(self.deck._Deck__m_cards[1], self.deck.getCard(3)) self.assertIsNot(self.deck._Deck__m_cards[2], self.deck.getCard(1))
def prepare(self): """ Prepares the Deck of Cards, and splits it evenly among players """ #:: shuffle the playing deck. #:: copy self._current_play_deck = Deck() cards = self._playing_deck.getCards() deck = Deck() deck.extend(cards) self._shuffle_strategy.shuffleDeck(deck) #:: split evenly among players. num_players = len(self._players) next_player = 0 expected_count = (deck.size() // num_players) * num_players count = 0 while (not deck.isEmpty() and count < expected_count): card = deck.popTopCard() self._players[next_player].addToDeckBottom([card]) next_player = (next_player + 1) % num_players count += 1
def test_draw_simple(self): """ This tests whether the state of the deck is correctly updated following a series of draws """ d = Deck() d.draw() self.assertEqual(sum(d.cards), 51) d.draw() d.draw() self.assertEqual(sum(d.cards), 49) for _, card in d.card_mapping.items(): # ensure cards remain generic self.assertIsNone(card.get_suit())
def display_next_hand(*args): """ Create the card list use Deck().deal and display_cardlist them""" global twentyfive_cards, six_hands # disable show_next and enable show_best print("running display_next_hand") display_best25_hand_button["state"] = "normal" display_next_hand_button["state"] = "disabled" six_hands = Deck(6, 25, 3).deal() pyramid_poker_hand = six_hands[0] twentyfive_cards = (sorted(pyramid_poker_hand, key=rank_sort, reverse=True)) window.title("Play Pyramid Poker") w.delete("all") # clear out last hand display_board(w, X_GAP, Y_GAP, X_OFFSET, Y_OFFSET) show_twentyfive_cards() rank_button["state"] = "disabled" # clear out player, best and diff scores for previous hand x = 10 * X_GAP + 6 y = 3 * Y_GAP + 15 display_points_clear(x, y) # best hand points
def main(): #:: for a longer game play(longer because of the number of cards in deck), # uncomment and use this input below # suites = [Suite.HEART, Suite.TILES, Suite.CLOVERS, Suite.PIKES] # ranks = [ # Rank.ACE, Rank.KING, Rank.QUEEN, Rank.JACK, # Rank.TEN, Rank.NINE, Rank.EIGHT, Rank.SEVEN, # Rank.SIX, Rank.FIVE, Rank.FOUR, Rank.THREE, # Rank.TWO # ] # initial_deck = createPlayingDeck(suites, ranks) initial_deck_list = [ Card(Rank.ACE, Suite.HEART), Card(Rank.ACE, Suite.CLOVERS), Card(Rank.ACE, Suite.PIKES), Card(Rank.TWO, Suite.CLOVERS) ] initial_deck = Deck() initial_deck.extend(initial_deck_list) #:: create a list of players. player_one = Player("Mario", Deck()) player_two = Player("Luigi", Deck()) players = [player_one, player_two] #:: create your shuffle strategy shuffleStrategy = SimpleShuffleStrategy() #:: create your ranking strategy rankingStrategy = RankScore() #:: create game game = Game(initial_deck, players, shuffleStrategy, rankingStrategy) #:: call game.start() game.start()
def test_empty_deck(self): deck = Deck() player = Player("Mustapha", deck) self.assertEqual(player.isDeckEmpty(), True)
from src.DisplayBoard import DisplayBoard from src.Deck import Deck from src.ShowDownPoints import ShowDownPoints from src.PlaySixHands25 import PlaySixHands25 # testing Display.display_6hands displayboard = DisplayBoard() playsixhands = PlaySixHands25(Deck(6, 25, 3).deal()) displayboard.pyramid_hands = playsixhands.best_pyramid_hands displayboard.player_win_points = playsixhands.player_win_points displayboard.display_6hands()
def createDeck(self): deck = Deck() for _ in itertools.repeat(None, 60): card = self.createCard() deck.addCard(card) return deck
class Game: def __init__(self, playing_deck: Deck, players: Iterable[Player], shuffle_strategy: DeckShuffleStrategy, rank_score_strategy: RankScore): self._players = players #:: deck must be even in length / divisible by the number of players. #:: this represents the card deck for the game. self._playing_deck = playing_deck self._current_play_deck = None self._status = GameStatus.BATTLE self._shuffle_strategy = shuffle_strategy self._rank_score_strategy = rank_score_strategy self._winner = None def prepare(self): """ Prepares the Deck of Cards, and splits it evenly among players """ #:: shuffle the playing deck. #:: copy self._current_play_deck = Deck() cards = self._playing_deck.getCards() deck = Deck() deck.extend(cards) self._shuffle_strategy.shuffleDeck(deck) #:: split evenly among players. num_players = len(self._players) next_player = 0 expected_count = (deck.size() // num_players) * num_players count = 0 while (not deck.isEmpty() and count < expected_count): card = deck.popTopCard() self._players[next_player].addToDeckBottom([card]) next_player = (next_player + 1) % num_players count += 1 def getStatus(self) -> GameStatus: return self._status def _checkForDrawOrWinner(self): """ set game status to 'WIN' if there's a winner. """ num_players_with_card = 0 winner = None for player in self._players: if not player.isDeckEmpty(): num_players_with_card += 1 winner = player #:: if we have only one player with a non-empty deck...that is the winner. if (num_players_with_card == 1): self._setStatus(GameStatus.WIN) self._winner = winner elif (num_players_with_card == 0): self._setStatus(GameStatus.DRAW) self._winner = None def getWinner(self): """ returns the game winner. This is the player with a non-empty deck """ return self._winner def _makeCardPlays(self) -> List[Tuple[Card, Player]]: """ gets all the top cards from the players, and adds it to current deck """ plays = [] for player in self._players: card = player.popDeckTopCard() #: add the card to the current playing deck. self._current_play_deck.pushToTop(card) plays.append((card, player)) #::sort the plays in decreasing order. #::for the key, use the first item which is the card. sort_key = lambda item: self._rank_score_strategy.getScore(item[0]. getRank()) plays.sort(key=sort_key, reverse=True) return plays def printPlayerDecks(self): print("Player Decks ####################################") for player in self._players: player.printDeck() print("###################################################") def _setStatus(self, status: GameStatus): self._status = status def _makeBattlePlay(self): #:: print current decks of players self.printPlayerDecks() #:: check if we have a winner. self._checkForDrawOrWinner() if (self.getStatus() == GameStatus.WIN or self.getStatus() == GameStatus.DRAW): # we have a winner. return # make a play. plays = self._makeCardPlays() self.printPlays(plays) #:: the player who wins this round is at the top of plays. #:: if both cards are of the same rank...then it's war. if self._rank_score_strategy.getScore( plays[0][0].getRank()) == self._rank_score_strategy.getScore( plays[1][0].getRank()): #:: this means war. self._setStatus(GameStatus.WAR) else: #:: give the current deck to the highest card. self._setStatus(GameStatus.BATTLE) winning_player = plays[0][1] winning_player.addToDeckBottom(self._current_play_deck.popAll()) print("Game: Assigneed Deck to ", winning_player.getName()) def printPlays(self, plays): print("The current card played ") for i in range(len(plays)): player = plays[i][1] print("[{}] ".format(player.getName()), str(plays[i][0])) print("##########################") def _makeWarPlay(self): """ makes the war game play """ self.printPlayerDecks() self._checkForDrawOrWinner() if (self.getStatus() == GameStatus.WIN or self.getStatus() == GameStatus.DRAW): # we have a winner. return #: make plays from players. (first cards down) plays = self._makeCardPlays() self.printPlays(plays) #:: make the second plays from players. (similar to battle play) self._makeBattlePlay() def makePlay(self): """ executes one round of play for war game """ status = self.getStatus() #:: print player card if status == GameStatus.WAR: self._makeWarPlay() elif status == GameStatus.BATTLE: self._makeBattlePlay() # means we have a winner. print("Game Status: ", self.getStatus()) def start(self): #:: starts the game loop self.prepare() while (self.getStatus() != GameStatus.WIN and self.getStatus() != GameStatus.DRAW): self.makePlay() input("Press Enter key to make next game play ") if self.getStatus() == GameStatus.WIN: print("Winner: ", self._winner.getName()) else: print("Draw")
from src.print_obj import * from src.Analysis import Analysis from src.Deck import Deck g = globals() l = locals() x = 10 y = 20 z = 30 print_obj(x, g) print_obj(y, g) print_obj(z, g) # print_obj(g, g) print (g) print (l) pyramid_poker_hands = Deck(6, 25, 3).deal() a = Analysis(pyramid_poker_hands[0]) print_obj(a.singles_list, g) print_obj(a.pairs_list, g) print_obj(a.trips_list, g)
class CardGameDealer(Host): def __init__(self, logger, **kwargs): """ constructor :param logger: logger :param kwargs: inherited params """ super().__init__(logger, True, **kwargs) self.init_socket() self.deck = Deck(self.logger) self.round = 0 self.player_earnings = 0 self.tie = False self.player_card = None self.dealer_card = None self.bet = 0 def init_game(self): """ initializing a game :return: """ self.logger.debug(f"starting to a new game") self.play_game() def play_game(self): """ manages a game and its end """ while len(self.deck) > 0: self.logger.info(f"deck length is {len(self.deck)}") self.round += 1 self.handle_game_turn() self.logger.info("game concluded") self.handle_game_termination() def handle_game_turn(self): """ handle a given turn in the game and all of the communications with the client :return: """ self.logger.debug(f"handling turn") self.handle_player_turn() winner = self.handle_dealer_turn() if not self.tie: end_of_round_msg = self.build_end_of_round_msg(winner) self.send_msg_to_player(end_of_round_msg) else: self.tie = False def handle_dealer_turn(self): """ handling the dealer turn and the followed logic :return: the round winner (player / dealer / no one (surrender)) """ self.logger.debug(f"handling dealer turn") self.dealer_card = self.deck.draw_card() return self.calculate_winner() def calculate_winner(self): """ calculate the winner of the round :return: player / dealer / no one """ if self.player_card == self.dealer_card: return self.handle_tie( ) if not self.tie else self.conclude_tie_after_war("player") winner = "player" if self.player_card > self.dealer_card else "dealer" self.player_earnings += self.bet if self.player_card > self.dealer_card else -self.bet return winner def handle_player_turn(self): """ handling the player turn and the followed logic and communications with the client :return: """ self.logger.debug(f"handling player turn") self.player_card = self.deck.draw_card() msg = self.build_player_card_msg(self.player_card) self.send_msg_to_player(msg) player_msg = self.await_player_turn_response() if self.is_game_terminated_by_player(player_msg): return self.handle_game_termination() self.bet = self.parse_player_bet(player_msg) def handle_game_termination(self): """ handles game termination by the player """ termination_msg = self.build_termination_msg() self.send_msg_to_player(termination_msg) self.logger.info("termination msg was sent to the user") exit(1) def handle_tie(self): """ handle the logic for a tie """ self.tie = True tie_msg = self.build_tie_msg() self.send_msg_to_player(tie_msg) player_tie_msg = self.await_player_turn_response() player_tie_decision = self.parse_tie_decision(player_tie_msg) if player_tie_decision: for i in range(3): self.deck.draw_card() self.dealer_card = self.deck.draw_card() self.bet *= 2 winner = self.calculate_winner() return self.conclude_tie_after_war(winner) else: self.tie = False return "no one" def conclude_tie_after_war(self, winner): """ handle the communications after a tie :param winner: :return: """ end_of_tie_msg = self.build_end_of_tie_msg(winner) self.send_msg_to_player(end_of_tie_msg) def parse_tie_decision(self, player_tie_msg): """ parse the chosen response from the player :param player_tie_msg: client message :return: boolean """ return player_tie_msg.get("tie_decision") def send_msg_to_player(self, msg): """ send a message to the client :param msg: a dictionary based message """ self.transmit(msg) def await_player_turn_response(self): """ awaiting a response from the client :return: a dictionary based message """ return self.receive() def parse_player_bet(self, player_msg): """ parse the player bet from the client response :param player_msg: client message :return: """ return int(player_msg['player_bet']) def is_game_terminated_by_player(self, player_msg): """ parse the decision to terminate the game from a client message :param player_msg: client message :return: boolean """ return player_msg.get('terminate') def build_end_of_round_msg(self, winner): """ build end of round summery message to be sent to the client :param winner: :return: a summery of the round dictionary """ return { "dealer_card": str(self.dealer_card), "player_card": str(self.player_card), "bet": self.bet, "round": self.round, "winner": winner } def build_end_of_tie_msg(self, winner): """ build the end of tie summery message to be sent to the client :param winner: who won :return: a summery of tie round dictionary """ return { "dealer_card": str(self.dealer_card), "player_card": str(self.player_card), "bet": self.bet, "round": self.round, "winner": winner, "original_bet": self.bet / 2 } def build_termination_msg(self): """ build an end of game message to be sent to the client :return: end of game message dictionary """ return { "player_earnings": self.player_earnings, "round": self.round, "termination": True } def build_tie_msg(self): """ build a tie status message to be sent to the client :return: a dictionary based tie summery message """ return { "round": str(self.round), "tie": True, "dealer_card": str(self.dealer_card), "player_card": str(self.player_card), "bet": str(self.bet) } def build_player_card_msg(self, player_card): """ build a player card message to be sent to the client :param player_card: the player drawn card :return: a dictionary based card message """ return {"player_card": str(player_card)}
def setUp(self): self.deck = Deck(cardSize=7, cardCount=3, numberMax=100) self.deck1 = Deck(0, 0, 0)
class UserInterface(): def __init__(self): self.__m_currentDeck = None def run(self): """Present the main menu to the user and repeatedly prompt for a valid command""" print("Welcome to the Bingo! Deck Generator\n") menu = Menu("Main") menu.addOption("C", "Create a new deck") keepGoing = True while keepGoing: command = menu.show() if command == "C": self.__createDeck() elif command == "X": keepGoing = False def __createDeck(self): """Command to create a new Deck""" # TODO: Get the user to specify the card size, max number, and number of cards size = self.__getNumberInput("Card Size: ") while size < 3 or size > 15: print("That is not a valid size!\n") size = self.__getNumberInput("Card Size: ") max_num = self.__getNumberInput("\nMax Number: ") while max_num < 2*size*size or max_num > 4*size*size: print("That is not a valid max number!\n") max_num = self.__getNumberInput("Max Number: ") num_cards = self.__getNumberInput("\nNumber of Cards: ") while num_cards < 3 or num_cards > 10000: print("That is not a valid number of cards!\n") num_cards = self.__getNumberInput("Number of Cards: ", ) # TODO: Create a new deck self.__m_currentDeck = Deck(size, num_cards, max_num) # TODO: Display a deck menu and allow use to do things with the deck self.__deckMenu() def __deckMenu(self): """Present the deck menu to user until a valid selection is chosen""" menu = Menu("Deck") menu.addOption("P", "Print a card to the screen") menu.addOption("D", "Display the whole deck to the screen") menu.addOption("S", "Save the whole deck to a file") keepGoing = True while keepGoing: command = menu.show() if command == "P": self.__printCard() elif command == "D": print() self.__m_currentDeck.print() elif command == "S": self.__saveDeck() elif command == "X": keepGoing = False def __printCard(self): """Command to print a single card""" cardToPrint = self.__getNumberInput("Id of card to print: ")#, 1, self.__m_currentDeck.getCardCount()) if cardToPrint > 0 and cardToPrint <= self.__m_currentDeck.getCardCount(): print() self.__m_currentDeck.print(idx=cardToPrint) else: print("Can't print card! Invalid card ID!") def __saveDeck(self): """Command to save a deck to a file""" fileName = self.__getStringInput("Enter output file name: ") if fileName != "": # TODO: open a file and pass to currentDeck.print() outputStream = open(fileName, 'w') self.__m_currentDeck.print(outputStream) outputStream.close() print("Done!") def __getNumberInput(self, prompt): return int(input(prompt)) def __getStringInput(self, prompt): return input(prompt)
from src.Player import * from src.Deck import Deck from src.Game import Game print('\n' * 10) print('Welcome to the Casino Royale\'s high roller blackjack table, ' 'please enter your starting chip amount!') try: chips = int(input('Chips: ')) except ValueError: print('You have crashed the game bad boy') exit(1) my_player = Player(chips, [], 0) my_deck = Deck() my_dealer = Dealer([]) game = Game() who = 0 play_again = True game_options = { 1: 'Raise Bet', 2: 'Hit me', 3: 'Stop', 4: 'Check_hand', 5: 'Check total chips', 6: 'Cash out' } while play_again:
def test_player_constructor(self): deck = Deck() player = Player("Mustapha", deck) self.assertEqual(player.getName(), "Mustapha") self.assertEqual(player._deck, deck)
def setUp(self): self.deck = Deck()