"""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 Turtle Graphics
我還沒有嘗試過任何東西。有人告訴我應該使用setpos()函數,但我不知道如何使用它。 – Learner
http://docs.python.org/2/library/turtle.html#turtle.setpos – jonrsharpe