python中random模块产生随意行走的路线

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


  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值