用Python构造随机移动的点

import turtle
import random
# 背景
wn = turtle.Screen()
wn.bgcolor("white")
wn.title("infection simulator")

wn.tracer(1, 1)
# 球的属性
ball = turtle.Turtle()
ball.shape("circle")
ball.color("red")

# 移动速度以及初始化位置
ball.speed(1)
x = random.randint(-3, 3)
y = random.randint(-3, 3)
ball.goto(x,y)

# 移动公式
while True:
    wn.update()

    ball.dy = random.randint(-20, 20)
    ball.dx = random.randint(-20, 20)
    ball.setx(ball.xcor() + ball.dx)
    ball.sety(ball.ycor() + ball.dy)
	# 如遇到背景的边界控制转向
    angel = -1
    if ball.xcor() < -300:
        ball.dx *= angel
    if ball.xcor() > 300:
        ball.dx *= angel
    if ball.ycor() < -300:
        ball.dy *= angel
    if ball.ycor() > 300:
        ball.dy *= angel

最后欣赏一下机器的大作:
用Python构造随机移动的点_第1张图片

你可能感兴趣的:(用Python构造随机移动的点)