【发布时间】:2020-03-31 14:02:34
【问题描述】:
我一直在 youtube 上观看此视频--https://www.youtube.com/watch?v=horBQxH0M5A 这会创建一个弹跳的球列表。
我正在尝试更改代码以使一个球为红色,其余为绿色,当红球“接触”一个绿球时,绿球将颜色变为红色。这并不难,但我还想确保当新的红球碰到另一个绿球时,那个绿球也会变成绿色。
我所做的是创建一个红球和一个绿球列表:
import turtle
import random
wn = turtle.Screen()
wn.bgcolor("white")
wn.title("simulator")
wn.tracer(1, 1)
# red ball
rball = turtle.Turtle()
rball.shape("circle")
rball.color("red")
# rball.penup()
rball.speed(1)
x = random.randint(-10, 10)
y = random.randint(-12, 12)
rball.goto(x,y)
# green ball
gballlist = []
for _ in range(5):
gballlist.append(turtle.Turtle())
for gballpeople in gballlist:
gballpeople.shape("circle")
gballpeople.color("green")
gballpeople.speed(1)
xh = random.randint(-10, 10)
yh = random.randint(-12, 12)
gballpeople.goto(xh, yh)
while True:
wn.update()
# rball.dy += acclerate
rball.dy = random.randint(-2, 2)
rball.dx = random.randint(-2, 2)
rball.setx(rball.xcor() + rball.dx)
rball.sety(rball.ycor() + rball.dy)
# list = [-1, 1]
# angel = random.choice(list)
angel = -1
if rball.xcor() < -100:
rball.dx *= angel
if rball.xcor() > 100:
rball.dx *= angel
if rball.ycor() < -100:
rball.dy *= angel
if rball.ycor() > 100:
rball.dy *= angel
for gball in gballlist:
gball.dy = random.randint(-2, 2)
gball.dx = random.randint(-2, 2)
gball.setx(gball.xcor() + gball.dx)
gball.sety(gball.ycor() + gball.dy)
# list = [-1, 1]
# angel = random.choice(list)
angel = -1
if gball.xcor() < -100:
gball.dx *= angel
if gball.xcor() > 100:
gball.dx *= angel
if gball.ycor() < -100:
gball.dy *= angel
if gball.ycor() > 100:
gball.dy *= angel
# change the color when distance is near
for gball in gballlist:
if abs(rball.xcor() - gball.xcor()) < 4 and abs(rball.ycor() - gball.ycor()) < 4 :
gball.color("red")
有什么建议吗?
【问题讨论】: