python - 想知道我用海龟绘制棋盘的python代码发生了什么?有什么帮助吗?
问题描述
import turtle
def main():
turtle.pensize(4)
for x in range(5):
for y in range(5):
turtle.penup()
turtle.goto(x*50,y*50)
turtle.pendown()
if (x+y)%2 == 0:
turtle.begin_fill()
black_square(50)
turtle.end_fill()
else:
turtle.begin_fill()
white_square(50)
turtle.end_fill()
def black_square(width):
turtle.fillcolor('black')
for x in range(4):
turtle.forward(width)
turtle.left(90)
def white_square(width):
turtle.fillcolor('white')
for x in range(4):
turtle.forward(width)
turtle.right(90)
main()
当前图像:
预期图像:
我的代码不会绘制正确的棋盘图案,但我想知道为什么每个 for 循环我的方形黑色和白色都同时执行?我不是要求正确的代码来获得正确的棋盘格,我只是想要解释我的代码中的错误。
解决方案
如果不给你正确的代码,我不知道如何解释你的错误,但我会尝试:
基本上错误是 black_square 和 white_square 在同一位置绘制正方形。起点相距 50 个单位,但由于正方形是按相反的方向(顺时针和逆时针)绘制的,因此生成的区域重叠。black_square 将在起点下方绘制一个正方形,而 white_square 将在其起点上方绘制一个正方形。
推荐阅读
- c++ - 如何在 C++ 中前向声明 std::set?
- laravel - Laravel:本地运行应用程序并将 ASSET_URL 设置为本地端口永远加载
- splunk - SUSE Linux12.4 上的 Splunk 7.2.9.1 通用转发器在一段时间后不通信并将日志转发到 Indexer
- mongodb - 在 mongodb 的地理空间查询中使用多个坐标进行搜索
- c# - 从子窗体启用、禁用父级面板
- neo4j - 收到总数后过滤节点
- python - 使用python比较数据库结构txt文件
- nginx - 如何使用lua从有效uuid开始的主字符串中提取子字符串
- highcharts - Highcharts - 使用导航器作为单独的时间选择器
- python-3.x - Django model_set.add() 方法不起作用但没有错误