# Python OOP implementation of blackjack. from random import choice from os import system, name as os_name class Card: def __init__(self): # Set colour as random between red and black self.colour = choice(["red", "black"]) # Set suit depending on colour since a suit has an allocated colour self.suit = choice(["hearts", "diamonds"]) if self.colour == "red" else choice(["clubs", "spades"]) # Set value self.value = choice(["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"]) # Set whether the value is a face card or not self.face = True if self.value in ["Jack", "Queen", "King"] else False class Player: def __init__(self, number=None): self.name = f"player-{number}" self.cards = [] # This is so each player can take cards until they are "done" # Then the dealer can take his cards self.done = False def show_cards(self): print(f"{self.name}'s cards:") for card in self.cards: print(f"> {card.value} of {card.suit}") print(f"Total: {self.total()}") print() def total(self): values = {"Ace": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7":7, "8": 8, "9": 9, "10": 10, "Jack": 10, "Queen": 10, "King": 10} aces_in_cards = 0 total = 0 for card in self.cards: total += values[card.value] if card.value == "Ace": aces_in_cards += 1 return total if aces_in_cards == 0 else (total, total+(10*aces_in_cards)) class Dealer(Player): def __init__(self): super().__init__(self) self.name = "dealer" def show_cards(self, game): print(f"{self.name}'s cards:") if not game.players_are_done(): print(f"> {self.cards[0].value} of {self.cards[0].suit}") for card in self.cards[1:]: print(f"> HIDDEN") print(f"Total: UNKNOWN") print() return for card in self.cards: print(f"> {card.value} of {card.suit}") print(f"Total: {super().total(self)}") print() class Game: def __init__(self): self.players = [Dealer()] for player_num in range(1): self.players.append(Player(player_num+1)) self.deal_cards() def main_loop(self): system("cls" if os_name == "nt" else "clear") self.overview() def deal_cards(self): for player in self.players: for _ in range(2): player.cards.append(Card()) def overview(self): self.players[0].show_cards(self) for player in self.players[1:]: player.show_cards() def players_are_done(self): for player in self.players[1:]: if not player.done: return False return True if __name__ == "__main__": game = Game() game.main_loop() # TODO: # - Win checking # - Player choice (hit, stand) # - Dealers turn