如何使用坐标列表在Python/Turtle中绘制形状坐标、如何使用、形状、列表

2023-09-03 11:15:38 作者:我们真的不合适

我是新手,我有一个问题。我想把乌龟移动到一个特定的开始位置,然后从那里画一个形状。该形状具有预先确定的坐标,因此我需要连接点以形成该形状。

我必须创建两个函数,以便下面的代码调用这两个函数并绘制三个形状:

 def testPolyLines():
    # First square
    squareShape = [(50, 0), (50, 50), (0, 50), (0, 0)]
    drawPolyLine((200, 200), squareShape)
    # Second square
    drawPolyLine((-200, 200), squareShape, lineColour="green")
    biggerSquareShape = generateSquarePoints(100)
    # A triangle
    triangleShape = [(200, 0), (100, 100), (0, 0)]
    drawPolyLine((100, -100), triangleShape, fillColour="green")

def main():
    testPolyLines()
main()
Python turtle图形绘制

我制作了第一个函数来为任意大小的正方形生成点:

def generateSquarePoints(i):
    squareShape = [(i, 0), (i, i), (0, i), (0, 0)]

但当我实际绘制形状时,我就卡住了。我可以让乌龟走到起点位置,但我不知道如何让它通过一系列的点,并将它们连接成一个形状。这是我所拥有的:

def drawPolyLine(start, squareShape, lineColour="black", fillColour = "white"):
    pencolor(lineColour)
    fillcolor(fillColour)
    penup()
    goto(start)
    pendown()
    begin_fill()
    goto(squareShape)
    end_fill()

这显然是不对的……我困惑的是如何告诉乌龟去找点的列表,并沿途将它们连接起来形成形状。我的程序现在只转到开始位置,但不绘制形状。

如果有任何帮助或建议,我将非常感激!提前谢谢。

推荐答案

代码问题:您不能只goto()点,您需要将它们调整到起始位置,将点中的x和y更多地视为增量-x,增量-y;generateSquarePoints()需要返回其点列表,而不是分配它;显然,需要像其他人提到的那样,需要for循环;您需要显式地回到起点以关闭形状。

尝试对您的代码进行以下修改,以查看它是否执行了您想要的操作:

import turtle

def generateSquarePoints(i):
    """ generate points for a square of any size """
    return [(i, 0), (i, i), (0, i), (0, 0)]

def drawPolyLine(start, points, lineColour="black", fillColour="white"):
    """ draw shapes using a list of coordinates """
    turtle.pencolor(lineColour)
    turtle.fillcolor(fillColour)

    turtle.penup()

    turtle.goto(start)  # make the turtle go to the start position

    turtle.pendown()
    turtle.begin_fill()

    x, y = start

    for point in points:  # go through a list of (relative) points
        dx, dy = point
        turtle.goto(x + dx, y + dy)
    turtle.goto(start)  # connect them to start to form a closed shape

    turtle.end_fill()
    turtle.penup()

if __name__ == "__main__":

    def testPolyLines():
        """ test shapes shape drawing functions """
        # First square
        squareShape = [(50, 0), (50, 50), (0, 50), (0, 0)]
        drawPolyLine((200, 200), squareShape)

        # Second square
        biggerSquareShape = generateSquarePoints(100)
        drawPolyLine((-200, 200), biggerSquareShape, lineColour="green")

        # A triangle
        triangleShape = [(200, 0), (100, 100), (0, 0)]
        drawPolyLine((100, -100), triangleShape, fillColour="green")


    def main():
        testPolyLines()
        turtle.done()

    main()