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

Python开发21点游戏时如何将ASCII艺术卡片横向并排打印

解决方法

核心思路是调整打印逻辑:原有代码逐张生成卡片后直接打印全部行,因此卡片纵向堆叠。要实现横向并排,需先收集所有卡片的各行内容,再按行拼接后统一打印。

修改后的完整代码

phand = ["2 of Hearts", "King of Diamonds", "Ace of Clubs"]
print(phand)

all_cards = []  # 存储所有卡片的行数据

for card_info in phand:
    # 拆分牌面值和花色,适配10这类双字符牌面值
    rank, suit = card_info.split(" of ")
    # 取牌面值的展示字符,10保留两位,其余取首字符
    rank_show = rank if rank == "10" else rank[0]
    
    pcarddisplay = [] 
    pcarddisplay.append("┌─────────┐")
    # 调整格式化逻辑适配双字符牌面值
    pcarddisplay.append(f"│{rank_show:<2}. . . .│")
    pcarddisplay.append("│. . . . .│")
    pcarddisplay.append("│. . . . .│")
    # 花色映射
    suit_icon = {"Diamonds":"♦", "Clubs":"♣", "Hearts":"♥", "Spades":"♠"}[suit]
    pcarddisplay.append(f"│. . {suit_icon} . .│")
    pcarddisplay.append("│. . . . .│")
    pcarddisplay.append("│. . . . .│")
    pcarddisplay.append(f"│. . . .{rank_show:>2}│")
    pcarddisplay.append("└─────────┘")
    
    all_cards.append(pcarddisplay)

# 按行拼接所有卡片并打印,每张卡片共9行
for line_idx in range(9):
    print("".join([card[line_idx] for card in all_cards]))

效果说明

运行后输出的卡片会横向并排展示,如下所示:

['2 of Hearts', 'King of Diamonds', 'Ace of Clubs']
┌─────────┐┌─────────┐┌─────────┐
│2 . . . .││K . . . .││A . . . .│
│. . . . .││. . . . .││. . . . .│
│. . . . .││. . . . .││. . . . .│
│. . ♥ . .││. . ♦ . .││. . ♣ . .│
│. . . . .││. . . . .││. . . . .│
│. . . . .││. . . . .││. . . . .│
│. . . . 2││. . . . K││. . . . A│
└─────────┘└─────────┘└─────────┘

额外优化点

  • 新增了牌面值拆分逻辑,解决原代码取首字符无法适配10的问题
  • 用字典映射花色图标,替代多分支if判断,代码更简洁
  • 格式化字符串时用左对齐/右对齐适配不同长度的牌面值,卡片布局更整齐

内容的提问来源于stack exchange,提问作者ORKUN CIRAK

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 00:36:03