Last active
September 12, 2021 01:34
-
-
Save JosephTLyons/7d642262b36a07cac42cf9cae41b8637 to your computer and use it in GitHub Desktop.
A class-based approach to displaying a shuffled deck of cards
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import random | |
| class Card: | |
| def __init__(self, card_value): | |
| self.card_value = card_value | |
| def __str__(self): | |
| rank_string = self.get_rank_string() | |
| rank_string_justified = rank_string.rjust(2, " ") | |
| suit_string = self.get_suit_string() | |
| return f"{rank_string_justified} {suit_string}" | |
| def __lt__(self, other): | |
| return self.card_value < other.card_value | |
| def get_rank_string(self): | |
| rank_value = self.card_value % 13 | |
| if rank_value == 0: | |
| rank_string = "A" | |
| elif rank_value in range(1, 10): | |
| rank_string = str(rank_value + 1) | |
| elif rank_value == 10: | |
| rank_string = "J" | |
| elif rank_value == 11: | |
| rank_string = "Q" | |
| elif rank_value == 12: | |
| rank_string = "K" | |
| else: | |
| raise Exception("Impossible rank value") | |
| return rank_string | |
| def get_suit_string(self): | |
| suit_value = self.card_value // 13 | |
| if suit_value == 0: | |
| suit_string = "♠️" | |
| elif suit_value == 1: | |
| suit_string = "♦️" | |
| elif suit_value == 2: | |
| suit_string = "♣️" | |
| elif suit_value == 3: | |
| suit_string = "❤️" | |
| else: | |
| raise Exception("Impossible suit value") | |
| return suit_string | |
| class Deck: | |
| def __init__(self): | |
| self.deck = [] | |
| for card_value in range(52): | |
| self.deck.append(Card(card_value)) | |
| def __str__(self, horizontal=False): | |
| card_string_list = [str(card) for card in self.deck] | |
| return "\n".join(card_string_list) | |
| def shuffle(self): | |
| random.shuffle(self.deck) | |
| def sort(self): | |
| self.deck.sort() | |
| def main(): | |
| deck = Deck() | |
| deck.shuffle() | |
| print(deck) | |
| if __name__ == "__main__": | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment