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

Python井字棋while循环中ANSI转义序列的颜色异常问题

解决井字棋添加颜色后界面变形的问题

问题核心是ANSI颜色转义序列(如\033[35m)会增加字符串的实际长度,但终端显示时不占用额外宽度,直接用字符串replace替换单个数字字符后,会打乱原来的排版结构,导致界面变形。

解决方案

放弃直接修改棋盘字符串的方式,改用数组维护棋盘状态,每次更新后重新生成带颜色的棋盘,确保排版始终对齐。

修改后的完整可运行代码

import sys

def get_board(board_state):
    PURPLE = '\033[35m'
    YELLOW = '\033[33m'
    ENDC = '\033[0m'
    board = ""
    # 按行生成棋盘,每行3个格子
    for row in range(3):
        line_parts = []
        for col in range(3):
            idx = row * 3 + col
            value = board_state[idx]
            # 为棋子添加颜色,数字保持原样
            if value == 'o':
                colored_val = f"{PURPLE}{value}{ENDC}"
            elif value == 'x':
                colored_val = f"{YELLOW}{value}{ENDC}"
            else:
                colored_val = value
            # 每个格子占2字符宽度,居中显示,保证排版一致
            line_parts.append(f" {colored_val:^2} ")
        board += "|".join(line_parts) + "\n"
        # 添加行分隔线,最后一行无需添加
        if row < 2:
            board += "-" * 11 + "\n"
    return board

def main():
    # 初始化棋盘状态,存储0-8的字符串形式
    board_state = [str(i) for i in range(9)]
    filled_spaces = []
    players = ["o", "x"]
    move_count = 0
    print(get_board(board_state))
    while move_count < 9:
        space = input(f"Enter a space on the board for player '{players[move_count%2]}'\n")
        if space not in filled_spaces:
            idx = int(space)
            board_state[idx] = players[move_count % 2]
            filled_spaces.append(space)
            move_count += 1
        else:
            print(f"\nERROR: {space} has already been taken, choose a different space\n")
        print(get_board(board_state), flush=True)

    print("GAME OVER")

if __name__ == "__main__":
    main()

关键修改说明

  • 用board_state数组维护棋盘的实际内容,避免直接操作字符串带来的排版问题。
  • 每次生成棋盘时,为每个格子固定宽度并居中对齐,无论内容是数字还是带颜色的棋子,都能保持一致的占位。
  • 颜色转义序列仅在生成显示字符串时添加,不会影响状态数组的结构,彻底解决了因字符串长度变化导致的界面变形问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 18:18:28