You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现点击Start按钮退出Pygame标题屏并进入游戏循环

How to Separate Pygame Title Screen and Blackjack Game into Functions

Got it, let's break this down into simple, actionable steps. You'll want to split your code into two main functions: one for the Pygame title screen, and another for your Blackjack game loop. Here's a complete example that ties it all together:


Step 1: Full Refactored Code

First, here's the full code structure. I'll include a sample terminal-based Blackjack game and a functional Pygame title screen with a Start button:

import pygame
import random

def title_screen():
    # Initialize Pygame
    pygame.init()
    screen_width, screen_height = 800, 600
    screen = pygame.display.set_mode((screen_width, screen_height))
    pygame.display.set_caption("Blackjack")
    
    # Color definitions
    BLACK = (0, 0, 0)
    GREEN = (0, 220, 0)
    WHITE = (255, 255, 255)
    
    # Font setup
    title_font = pygame.font.Font(None, 80)
    button_font = pygame.font.Font(None, 50)
    
    # Start button rectangle (x, y, width, height)
    start_button = pygame.Rect(
        screen_width//2 - 100, 
        screen_height//2 + 50, 
        200, 
        80
    )
    
    # Title screen loop
    running = True
    while running:
        # Fill screen with black background
        screen.fill(BLACK)
        
        # Draw title text
        title_text = title_font.render("BLACKJACK", True, WHITE)
        screen.blit(
            title_text, 
            (screen_width//2 - title_text.get_width()//2, screen_height//2 - 150)
        )
        
        # Draw start button
        pygame.draw.rect(screen, GREEN, start_button)
        button_text = button_font.render("START GAME", True, BLACK)
        screen.blit(
            button_text, 
            (start_button.centerx - button_text.get_width()//2, start_button.centery - button_text.get_height()//2)
        )
        
        # Handle events
        for event in pygame.event.get():
            # Quit if user clicks the window close button
            if event.type == pygame.QUIT:
                pygame.quit()
                exit()
            # Check if Start button is clicked
            if event.type == pygame.MOUSEBUTTONDOWN:
                if start_button.collidepoint(event.pos):
                    running = False  # Exit title screen loop
        
        # Update display
        pygame.display.flip()
    
    # Clean up Pygame before moving to game
    pygame.quit()

def game_loop():
    # Replace this with your existing terminal Blackjack code
    print("🎮 Welcome to Blackjack! 🎮")
    
    def deal_card():
        """Return a random card from the deck"""
        cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
        return random.choice(cards)
    
    def calculate_score(cards):
        """Calculate the score of a hand, handling aces correctly"""
        if sum(cards) == 21 and len(cards) == 2:
            return 0  # Represents Blackjack
        if 11 in cards and sum(cards) > 21:
            cards.remove(11)
            cards.append(1)
        return sum(cards)
    
    def determine_winner(user_score, computer_score):
        """Determine the winner based on scores"""
        if user_score == computer_score:
            return "Draw! 🙃"
        elif computer_score == 0:
            return "You lose! Opponent has Blackjack 😱"
        elif user_score == 0:
            return "You win! Blackjack 😎"
        elif user_score > 21:
            return "You went over! Lose 😭"
        elif computer_score > 21:
            return "Opponent went over! Win 😁"
        elif user_score > computer_score:
            return "You win! 😃"
        else:
            return "You lose! 😤"
    
    # Initialize game state
    user_cards = []
    computer_cards = []
    is_game_over = False
    
    # Deal initial cards
    for _ in range(2):
        user_cards.append(deal_card())
        computer_cards.append(deal_card())
    
    # User turn
    while not is_game_over:
        user_score = calculate_score(user_cards)
        computer_score = calculate_score(computer_cards)
        
        print(f"\nYour cards: {user_cards} | Current score: {user_score}")
        print(f"Computer's first card: {computer_cards[0]}")
        
        # Check for immediate game over conditions
        if user_score == 0 or computer_score == 0 or user_score > 21:
            is_game_over = True
        else:
            # Ask user to hit or stand
            choice = input("\nType 'y' to hit, 'n' to stand: ").lower()
            if choice == 'y':
                user_cards.append(deal_card())
            else:
                is_game_over = True
    
    # Computer turn
    while computer_score != 0 and computer_score < 17:
        computer_cards.append(deal_card())
        computer_score = calculate_score(computer_cards)
    
    # Display final results
    print("\n--- Final Results ---")
    print(f"Your final hand: {user_cards} | Final score: {user_score}")
    print(f"Computer's final hand: {computer_cards} | Final score: {computer_score}")
    print(determine_winner(user_score, computer_score))

# Run the program
if __name__ == "__main__":
    title_screen()  # Show title screen first
    game_loop()     # Start the game after title screen is closed

Step 2: Key Explanations

1. title_screen() Function

  • Handles all Pygame initialization, window setup, and rendering for the title screen.
  • Uses a pygame.Rect to define the Start button's area, making it easy to detect clicks with collidepoint().
  • When the Start button is clicked, it sets running = False to exit the title screen loop, then quits Pygame cleanly before moving to the game.

2. game_loop() Function

  • Contains all your Blackjack game logic (replace the sample code with your existing terminal-based code).
  • Is isolated from the Pygame code, so you don't have to mix terminal and Pygame logic unless you want to.

3. Main Execution

  • The if __name__ == "__main__": block ensures the code only runs when the script is executed directly.
  • First, it calls title_screen() — once that function finishes (when Start is clicked), it immediately starts game_loop().

Bonus: If You Want the Game in Pygame

If you want to move your Blackjack game into Pygame instead of using the terminal, you can modify game_loop() to use Pygame's rendering functions (like blit() for text, handling mouse/keyboard events) instead of print() and input(). The core structure of separating the title screen and game loop into functions will still work exactly the same way.

内容的提问来源于stack exchange,提问作者Jack Jones

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 12:22:44