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

如何在Python控制台8×8棋盘(每格3×3)中标记中心方块为primary

问题描述

我制作了一个8×8的棋盘,每个棋盘格由3×3共9个小方块组成,其中普通小方块标记为secondary,需将每个棋盘格的中心小方块标记为primary。以下是我的Python代码,请问如何实现该功能?

原代码
print("""
Chess



Press Enter to Start...
""")
noneed = input()
if noneed== "":
    line = []
    chessboard = ""
    changeColorAllowed = False
    lineQueue = False
    queue = 0
    
    for linecount in range(24):
        for i in range(24):
            if (linecount // 3) % 2 == (i // 3) % 2:
                line.append([queue,"white", "a" + str(i//3), "primary", "none"])
            else:
                line.append([queue,"black", "a" + str(i//3), "primary", "none"])

    for i in line:
        if len(chessboard)%25==0:
            chessboard+="\n"
        if i[1] == "white":
            chessboard += "⬜"
        else: 
            chessboard += "⬛"
        
    print(chessboard)
解决方案

要实现每个3×3棋盘格的中心小方块标记为primary,其余为secondary,核心是判断当前小方块是否处于所在3×3区域的中心位置:

  • 对每个小方块坐标(linecount, i),先计算所属大棋盘格的索引:big_row = linecount // 3,big_col = i // 3
  • 再计算在3×3小区域内的相对坐标:small_row = linecount % 3,small_col = i % 3
  • 当small_row == 1且small_col == 1时,该小方块为中心,标记为primary,否则标记为secondary

修改后的代码如下:

print("""
Chess



Press Enter to Start...
""")
noneed = input()
if noneed == "":
    line = []
    chessboard = ""
    
    for linecount in range(24):
        for i in range(24):
            # 计算大棋盘格的颜色
            big_row = linecount // 3
            big_col = i // 3
            is_white = (big_row % 2) == (big_col % 2)
            color = "white" if is_white else "black"
            
            # 判断是否为3×3区域的中心小方块
            small_row = linecount % 3
            small_col = i % 3
            tag = "primary" if (small_row == 1 and small_col == 1) else "secondary"
            
            line.append([0, color, f"a{big_col}", tag, "none"])

    for idx, cell in enumerate(line):
        # 每24个小方块换行(对应大棋盘的一行:8个大格×3个小方块)
        if idx % 24 == 0 and idx != 0:
            chessboard += "\n"
        chessboard += "⬜" if cell[1] == "white" else "⬛"
        
    print(chessboard)

关键调整

  • 新增相对坐标计算,精准识别中心小方块
  • 修正换行逻辑:原代码的len(chessboard)%25==0会导致换行错位,改为按每24个小方块换行,匹配大棋盘一行的长度
  • 简化变量逻辑,让代码可读性更强

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 13:04:58