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

Python老虎机开发:实现旋转结果的格式化打印

实现老虎机界面打印函数

针对你已经拿到的9个符号的列表,我们可以通过将列表拆分为3行3列的结构,再用ASCII边框进行排版,来模拟老虎机的界面。以下是两种实现方式:

基础版(适配单字符符号)

这个版本针对单个字符的符号设计,排版简洁直观:

def print_slot_machine(slots):
    # 校验输入列表长度必须为9
    if len(slots) != 9:
        raise ValueError("老虎机符号列表必须包含恰好9个元素")
    
    # 将9个元素拆分为3行,每行3个符号
    rows = [slots[i:i+3] for i in range(0, 9, 3)]
    
    # 打印顶部边框
    print("┌─────┬─────┬─────┐")
    for row in rows:
        # 格式化每行,符号居中显示在格子内
        print(f"│  {row[0]}  │  {row[1]}  │  {row[2]}  │")
        # 非最后一行打印分隔线
        if row != rows[-1]:
            print("├─────┼─────┼─────┤")
    # 打印底部边框
    print("└─────┴─────┴─────┘")

测试示例

用你提供的符号列表测试:

test_slots = ['A', 'B', 'E', 'A', 'C', 'B', 'C', 'F', 'B']
print_slot_machine(test_slots)

输出效果:

┌─────┬─────┬─────┐
│  A  │  B  │  E  │
├─────┼─────┼─────┤
│  A  │  C  │  B  │
├─────┼─────┼─────┤
│  C  │  F  │  B  │
└─────┴─────┴─────┘

通用版(适配任意长度符号)

如果你的老虎机支持多字符符号(比如'77'、'BAR'),可以用这个自适应宽度的版本:

def print_slot_machine(slots):
    if len(slots) != 9:
        raise ValueError("老虎机符号列表必须包含恰好9个元素")
    
    rows = [slots[i:i+3] for i in range(0, 9, 3)]
    # 计算每个单元格的宽度:最长符号长度 + 2(左右留白)
    cell_width = max(len(sym) for sym in slots) + 2
    
    # 构建各类边框线
    top_border = "┌{}┐".format("┬".join(["─" * cell_width] * 3))
    separator = "├{}┤".format("┼".join(["─" * cell_width] * 3))
    bottom_border = "└{}┘".format("┴".join(["─" * cell_width] * 3))
    
    print(top_border)
    for idx, row in enumerate(rows):
        # 每个符号居中对齐填充到单元格宽度
        formatted_cells = [f"{sym:^{cell_width}}" for sym in row]
        print("│{}│".format("│".join(formatted_cells)))
        # 最后一行不打印分隔线
        if idx != len(rows) - 1:
            print(separator)
    print(bottom_border)

测试多字符符号

test_slots = ['BAR', '7', 'CHERRY', 'BAR', '77', 'CHERRY', '7', 'BAR', '777']
print_slot_machine(test_slots)

输出效果:

┌───────┬───────┬───────┐
│  BAR  │   7   │ CHERRY│
├───────┼───────┼───────┤
│  BAR  │  77   │ CHERRY│
├───────┼───────┼───────┤
│   7   │  BAR  │  777  │
└───────┴───────┴───────┘

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 08:15:43