[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

运行中的效果如下图所示

最终的效果如下图所示

参考资料

相关推荐
范中勤11 分钟前
Python 协程(Coroutine)通俗讲解与技术原理:从 await 挂起到 Agent 高并发
python·agent·协程·并发编程·asyncio
2601_966949651 小时前
如何判断实时行情数据是否已经更新?从时间戳、交易时段到行情有效性
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
MoRanzhi12031 小时前
106.正则问题(分治)
python·算法·正则表达式·蓝桥杯·递归·分治算法·字符串处理
Pingred1 小时前
我把一个私有化 RAG 系统真正跑通了:LocalRAG v0.1.0 发布
人工智能·python
Dmz丶1 小时前
前端转 AI 100 天 Day 24:API 测试——用 httpx + pytest 测 FastAPI
python
东莞市云毅网络有限公司2 小时前
监测问句清单去重:停用词表、数字归一与贪心聚类的参数取法
python·数据清洗·rag·企业知识库·文档解析
雪域迷影2 小时前
Python Django 7 小时课程
开发语言·python·django
量化吞吐机2 小时前
最高最低都一样,价格就同样集中吗
人工智能·python
FITA阿泽要努力2 小时前
如何调用 LLM 接口
python·api·agent
江湖中的阿龙2 小时前
大模型应用怎么做评测?从样本集、自动评分到上线回归的完整实战
人工智能·python·回归·大模型评测