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

时间:2016-05-24 22:31:22

标签: python python-3.x coordinates shape turtle-graphics

我是Python的新手并且有一个问题。我想将乌龟移动到特定的起始位置,并从那里绘制一个形状。形状具有预先确定的坐标,因此我需要连接点以形成形状。

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

 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()

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

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()

这显然是不对的...我很困惑的部分是如何告诉乌龟去点的列表,并沿途连接它们以形成形状。我的程序现在只进入起始位置,但没有绘制形状。

我真的很感激任何帮助或建议!提前谢谢。

1 个答案:

答案 0 :(得分:0)

您的代码问题:您不仅可以goto()点,还需要将它们调整到起始位置,处理x& y更多的是delta-x,delta-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()