import pygame import random import sys # Initialize Pygame pygame.init() # Constants WIDTH, HEIGHT = 800, 600 CARD_WIDTH, CARD_HEIGHT = 70, 95 FPS = 60 # Colors WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) # Fonts FONT = pygame.font.Font(None, 36) class BlackjackGame: def __init__(self): self.deck = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11] * 4 self.player_hand = [] self.dealer_hand = [] def deal_card(self): return random.choice(self.deck) def calculate_score(self, hand): if sum(hand) == 21 and len(hand) == 2: return 0 # Blackjack if 11 in hand and sum(hand) > 21: hand.remove(11) hand.append(1) return sum(hand) # Initialize game blackjack = BlackjackGame() # Initialize Pygame screen screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Blackjack") # Load card images card_images = {2: pygame.image.load("2.png"), 3: pygame.image.load("3.png"), 4: pygame.image.load("4.png"), 5: pygame.image.load("5.png"), 6: pygame.image.load("6.png"), 7: pygame.image.load("7.png"), 8: pygame.image.load("8.png"), 9: pygame.image.load("9.png"), 10: pygame.image.load("10.png"), 11: pygame.image.load("11.png")} def draw_text(text, color, x, y): text_surface = FONT.render(text, True, color) text_rect = text_surface.get_rect(center=(x, y)) screen.blit(text_surface, text_rect) def draw_hand(hand, is_player=True): x = 50 if is_player else WIDTH - CARD_WIDTH - 50 y = 200 if is_player else 50 offset = 0 for card in hand: screen.blit(card_images[card], (x + offset, y)) offset += 20 if is_player else 70 def main(): clock = pygame.time.Clock() running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False pygame.quit() sys.exit() screen.fill(WHITE) # Deal initial cards if not blackjack.player_hand or sum(blackjack.player_hand) == 0: for _ in range(2): blackjack.player_hand.append(blackjack.deal_card()) blackjack.dealer_hand.append(blackjack.deal_card()) # Draw hands draw_hand(blackjack.player_hand) draw_hand(blackjack.dealer_hand, False) # Calculate scores player_score = blackjack.calculate_score(blackjack.player_hand) dealer_score = blackjack.calculate_score(blackjack.dealer_hand) draw_text(f"Your Score: {player_score}", BLACK, WIDTH // 4, HEIGHT - 100) draw_text(f"Dealer Score: {dealer_score}", BLACK, 3 * WIDTH // 4, HEIGHT - 100) pygame.display.flip() clock.tick(FPS) if __name__ == "__main__": main()