【问题标题】:Python Turtle GraphicsPython 海龟图形
【发布时间】:2014-03-18 16:16:54
【问题描述】:
"""Import turtle to start drawing"""
from turtle import *
"""imports the random function"""
from random import *


"""draws the bounding box"""
def bounding_box():
    up()
    right(90)
    forward(200)
    down()
    left(90)
    forward(200)
    left(90)
    forward(400)
    left(90)
    forward(400)
    left(90)
    forward(400)
    left(90)
    forward(200)
    up()
    goto(0,0)
    down()
"""I want the snake to stay within that box above"""

"""draws the recursive snake"""
def drawSnakeRec(segments, length):
    """Draws the iterative snake and returns the total length"""
    if segments <= 0 or length <= 0:
        return 0
    else:
        color(random(), random(), random())
        forward(length)
        pensize(randint(1,10))
        left(randint(-30, 30))
        return length + drawSnakeRec(segments - 1, randint(1,20))

"""draws the iterative snake"""
def drawSnakeIter(segments, length):
    TL = 0
    """Draws the iterative snake and returns the total length"""
    while segments > 0:
        color(random(), random(), random())
        pensize(randint(1,10))
        forward(length)
        left(randint(-30, 30))
        TL += length
        segments -=1
    return TL

"""defines the main function"""
def main():
    segments = int(input("Enter the segments between 0 and 500: "))
    bounding_box()
    hideturtle()
    speed('fast')
    """ask for the number of segments"""
    if segments < 0 or segments > 500:
        print("Segments is out of range. Segment must be between 0 and 500 inclusive")
        input("Press enter to close")
    else:
        """draw the first snake"""
        x = drawSnakeRec(segments, randint(1, 20))
        print("Recursive Snake's Length is:",x,"Units")
        input("Press Enter to draw Iterative Snake")
        up()
        goto(0,0)
        reset()
        """start the second drawing"""
        bounding_box()
        y = drawSnakeIter(segments, randint(1,20))
        print("Iterative Snake's Length is:",y," Units")
        input("Press Enter to exit...")
        bye()

"""runs the main function"""
main()

问题: 如何将蛇保持在边界框内?我希望蛇在碰到边界框时转 180 度。请尽可能详细。

【问题讨论】:

标签: python coordinates turtle-graphics


【解决方案1】:

我认为乌龟没有检测到,看不到.. 所以你需要用pos()xcor()ycor()来测试坐标。

我认为你的栅栏从 x = 0,y = 0 向左、向上、向右和向下 200 个。(你 goto(0,0)。)

所以你的测试是

if xcor() > 200: # move to left, make x smaller, turn around!
if xcor() < -200: # move to right, make x bigger, turn around!
if ycor() > 200: 
if ycor() < -200: 

您需要填写 x 和 y。 可能是这样的:

if xcor() > 200: setx(200)
if xcor() < -200: setx(-200)
if ycor() > 200: sety(200)
if ycor() < -200: sety(-200)

但这可能看起来不太漂亮。你可以让它绕圈走,直到它再次进入里面……也许吧。它是由你决定。你想要 180 度转身……你可以用这个来代替 setx 和 sety。提示:如果你迈出一小步,没有人会注意到你已经走出了笼子。

如果您需要有关海龟的更多信息,可以使用help('turtle')。它将向您展示许多您可以使用的功能。

【讨论】:

  • 经过一些调整,终于成功了。非常感谢!
  • 欢迎您!您可以发布您的修改并接受答案吗?顺便说一句:谷歌搜索“Python for 循环”。你可以使用它。 Here are some tutorials for Python.也是一只乌龟..你可能已经知道很多了。