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

Python打印塔防网格:添加行首字母且不破坏循环及值替换

解决塔防游戏网格打印的三个问题:使用None列表、添加行号、对齐网格

核心修改后的代码

field = [
    [None, None, None, None, None, None, None],
    [None, None, None, None, None, None, None],
    [None, None, None, None, None, None, None],
    [None, None, None, None, None, None, None],
    [None, None, None, None, None, None, None]
]

num_rows = len(field)
num_columns = len(field[0])

# 打印顶部分隔线,给行号预留位置
print('     ', end='')
for _ in range(num_columns):
    print('+----', end='')
print('+')

for row_idx in range(num_rows):
    # 生成A-E的行号
    row_label = chr(ord('A') + row_idx)
    # 打印单元格内容行(可显示塔/怪物标记)
    print(f' {row_label}  ', end='')
    for cell in field[row_idx]:
        # None替换为空格,后续直接修改field元素即可更新显示
        content = ' ' if cell is None else str(cell)
        print(f'| {content:^2} ', end='')
    print('|')
    # 打印单元格空行(可扩展显示更多内容)
    print('     ', end='')
    for _ in field[row_idx]:
        print('|    ', end='')
    print('|')
    # 打印行分隔线
    print('     ', end='')
    for _ in range(num_columns):
        print('+----', end='')
    print('+')

关键修改说明

  • 利用None嵌套列表:现在每个单元格的显示内容直接从field读取,None会转为空格。后续要放置塔/怪物,只需修改field的元素(比如field[2][3] = 'T'),打印时自动更新,完美适配后续替换需求。
  • 添加行号A-E:通过chr(ord('A') + row_idx)生成对应行的字母,在打印每行内容前输出,同时预留了5个字符的对齐位置,完全不会破坏原有循环结构。
  • 修复网格对齐问题:顶部分隔线、内容行、分隔线都预留了行号的位置,内容行用{content:^2}让内容居中显示,保证网格整体整齐,后续替换内容也不会错位。

原代码的问题点

  1. 定义了field列表但未使用,浪费了地图数据存储的容器;
  2. 没有预留行号位置,直接加字母会导致网格错位;
  3. 内容行完全为空,无法后续替换显示游戏元素。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 13:06:26