'''用turtle模块来模拟随意行走
就像在花园里散步转过去看一朵小花
从中心位置开始,在边缘处某点停下'''
import turtle
from random import randint
turtle.speed(1)
turtle.color("gray")
x = -80
for y in range (-80, 80 + 1, 10): #10是步长
turtle.penup()
turtle.goto(x, y)
turtle.pendown() #Draw a horizontal line
turtle.forward(160)
y = 80
turtle.right(90)
for x in range(-80, 80 + 1, 10):
turtle.penup()
turtle.goto(x, y) #Draw a vertical line
turtle.pendown()
turtle.forward(160)
turtle.pensize(3)
turtle.color("red")
turtle.penup()
turtle.goto(0, 0) #Go to the center
turtle.pendown()
x = y = 0 #current pen location at the center of the lattice
while abs(x) < 80 and abs(y) < 80:
r = randint(0, 3)
if r == 0:
x += 10 #walk right
#将turtle的方向设定为指定角度。0--东、 90--北、 180--西、 270--南
turtle.setheading(0)
turtle.forward(10)
elif r == 1:
y -= 10
turtle.setheading(270)
turtle.forward(10)
elif r == 2:
x -=10
turtle.setheading(180)
turtle.forward(10)
elif r == 3:
y += 10
turtle.setheading(90)
turtle.forward(10)
turtle.done()
python中random模块产生随意行走的路线
最新推荐文章于 2022-12-11 23:50:37 发布