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

如何简化卡牌列表,实现随机生成带颜色标识的卡牌?

Optimized Solution for Dynamic Random Card Selection

Let's clean up your code to hit your goal: simplifying card list management and building a random card picker that doesn’t rely on pre-defined full card lists. This will make your code way cleaner, easier to maintain, and more flexible for future changes.

Key Pain Points in the Original Code

  • You’re maintaining redundant lists (validOptionsR/B/Y) that follow a fixed pattern (prefix + 01-10) — this adds unnecessary overhead if you ever want to add new colors.
  • The color check using find() is redundant since random.choice(colours) directly returns one of the exact color strings from your list.
  • The card selection logic repeats across three color branches, violating the DRY (Don’t Repeat Yourself) principle.

Optimized Code

import random
from tkinter import Tk

# Map color names to their abbreviated prefixes (easy to add/remove colors here)
COLOR_PREFIX_MAP = {
    'red': 'r',
    'black': 'b',
    'yellow': 'y'
}

def pick_random_color():
    # Grab a random color from our mapped color names
    return random.choice(list(COLOR_PREFIX_MAP.keys()))

def generate_random_card(color):
    # Get the matching prefix for the selected color
    prefix = COLOR_PREFIX_MAP.get(color)
    if not prefix:
        raise ValueError(f"Oops, invalid color: {color}")
    
    # Generate a 2-digit number between 01 and 10
    card_number = f"{random.randint(1, 10):02d}"
    
    # Combine prefix and number to make the card ID (e.g., b09)
    return f"{prefix}{card_number}"

def open_color_window(selected_color):
    colourWind = Tk()
    colourWind.title('Cards')
    colourWind.configure(bg=selected_color)
    # Start the Tkinter loop to display the window
    colourWind.mainloop()

def player_card_pick():
    # Step 1: Pick a random color
    random_color = pick_random_color()
    print(f"Selected color: {random_color}")
    
    # Step 2: Generate a random card for that color
    chosen_card = generate_random_card(random_color)
    print(f"Chosen card: {chosen_card}")
    
    # Optional: Open the color-themed window
    open_color_window(random_color)

# Run the example
if __name__ == "__main__":
    player_card_pick()

What’s Better About This Version?

  • No hardcoded card lists: We dynamically generate card IDs using the color prefix + random 2-digit number, so you never have to update or maintain bulky lists like carddeck or validOptionsR/B/Y.
  • Easy to extend: Want to add a blue color? Just add 'blue': 'bl' to COLOR_PREFIX_MAP — no other code changes needed.
  • DRY logic: All card generation happens in one function instead of repeating the same shuffle/choice code for each color.
  • Clearer structure: Each function has a single job (pick color, generate card, open window), making the code easier to debug and modify.
  • Basic error handling: We added a check for invalid colors to catch mistakes early.

How It Works

  1. pick_random_color() selects a random color from our mapped color names.
  2. generate_random_card() takes that color, grabs its prefix, generates a 2-digit number (01-10), and combines them into a card ID like b09.
  3. player_card_pick() ties everything together: picks the color, generates the card, prints the results, and opens the color-themed window.

内容的提问来源于stack exchange,提问作者Zakariya Hasan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 07:38:38