【发布时间】: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 度。请尽可能详细。
【问题讨论】:
-
我还没有真正尝试过任何东西。有人告诉我应该使用 setpos() 函数,但我不知道如何使用。
标签: python coordinates turtle-graphics