首页 > 解决方案 > 想知道我用海龟绘制棋盘的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 循环我的方形黑色和白色都同时执行?我不是要求正确的代码来获得正确的棋盘格,我只是想要解释我的代码中的错误。

标签: python

解决方案


如果不给你正确的代码,我不知道如何解释你的错误,但我会尝试:

基本上错误是 black_square 和 white_square 在同一位置绘制正方形。起点相距 50 个单位,但由于正方形是按相反的方向(顺时针和逆时针)绘制的,因此生成的区域重叠。black_square 将在起点下方绘制一个正方形,而 white_square 将在其起点上方绘制一个正方形。


推荐阅读