[Python] 用 turtle 来绘制国际象棋棋盘(不含棋子)

背景

turtle --- Turtle graphics 中提供了关于 turtle\text{turtle} turtle 模块的介绍。我想用 turtle\text{turtle} turtle 来生成些简单的图案,以巩固学习的效果。最近我经常下国际象棋,于是想到可以用 turtle\text{turtle} turtle 来绘制国际象棋的棋盘。

正文

基本的分析

国际象棋的棋盘长这样 ⬇️

为了降低难度,我们不关心以下内容

  • 棋子
  • 棋盘边上用于表示坐标的数字和字母

那么我们的目标就变为,绘制 8×88\times 8 8×8 个黑白相间的正方形格子(左上角的格子是白色的)。考虑到只有 8×88\times 8 8×8 个格子,我们可以遍历 88 8 行 88 8 列,绘制对应的格子(需要计算每个格子的颜色)。

代码

有了上述思路后,结合 turtle --- Turtle graphics 中的文档,不难写出对应的 Python\text{Python} Python 代码。

我写的版本如下(trae 提供了一些帮助)⬇️

python 复制代码
import turtle

cell_size = 50
init_x = -200
init_y = 200
row_cnt = 8
col_cnt = 8

def fill_color(r, c):
    if (r + c) % 2 == 0:
        return "white"
    return "black"

turtle.speed('fastest')
for row in range(row_cnt):
    for col in range(col_cnt):
        x = init_x + col * cell_size
        y = init_y - row * cell_size
        turtle.teleport(x, y)
        turtle.setheading(0)

        turtle.color("black", fill_color(row, col))
        with turtle.fill():
            for i in range(4):
                turtle.forward(cell_size)
                turtle.right(90)

turtle.hideturtle()

turtle.mainloop()

请将以上代码保存为 draw_chessboard.py。执行以下命令可以运行 draw_chessboard.py

bash 复制代码
python3 draw_chessboard.py

运行中的效果如下图所示

最终的效果如下图所示

参考资料

相关推荐
默_笙4 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
qq_426003964 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫4 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
长沙三为智能科技4 天前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
伞伞悦读4 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
只睡四小时4 天前
Canvas 弹道联机实战:700 行 + 固定时间步长
python·websocket·html5·游戏开发·canvas
奇思妙想聪明勤奋的小羊4 天前
DeepAgents第5章:子Agent 与上下文隔离—让 Agent学会委派
人工智能·python·学习·语言模型
lpfasd1234 天前
2026年第38周GitHub趋势周报
python·科技·github
IZero074 天前
Jev 与 Laya
python·语言模型