【发布时间】:2019-04-03 01:35:33
【问题描述】:
我正在尝试制作一个弹跳球模拟器。我需要一些帮助来尝试让球在它们接触时相互反弹,就像如果它们接触到球,它们会向另一个方向反弹。
我试过这样做:
def is_collided_with(a):
for ball in balls:
if abs(a.xcor() - ball.xcor()) < 3 and abs(a.ycor() - ball.ycor()) < 3:
a.dx *= -1
ball.dx *= -1
a.dy *= -1
ball.dy *= -1
while True:
... other code
[is_collided_with(ball) for ball in balls]
但球似乎没有相互反弹。你能帮帮我吗?
代码:
import turtle
import random
import time
wn = turtle.Screen()
wn.bgcolor("black")
wn.tracer(0)
balls = []
numOfBalls = len(balls)
for _ in range(10):
balls.append(turtle.Turtle())
colors = ["yellow", "gold", "orange", "red", "maroon", "violet", "magenta", "purple", "navy", "blue", "skyblue", "cyan", "turquoise", "lightgreen", "green", "darkgreen", "chocolate", "brown", "black", "gray", "white"]
for ball in balls:
ball.shape("circle")
ball.color(random.choice(colors))
ball.penup()
ball.speed(0)
x = random.randint(-290, 290)
y = random.randint(200, 400)
ball.goto(x, y)
ball.dy = 0
ball.dx = random.randint(-3, 3)
gravity = 0.1
def addBall():
balls.append(turtle.Turtle())
balls[-1].shape("circle")
balls[-1].color(random.choice(colors))
balls[-1].penup()
balls[-1].speed(0)
x = random.randint(-290, 290)
y = random.randint(200, 400)
balls[-1].goto(x, y)
balls[-1].dy = 0
balls[-1].dx = random.randint(-3, 3)
def removeBall():
balls[-1].reset()
balls.pop()
def reload():
for ball in balls:
ball.shape("circle")
ball.color(random.choice(colors))
ball.penup()
ball.speed(0)
x = random.randint(-290, 290)
y = random.randint(200, 400)
ball.goto(x, y)
ball.dy = 0
ball.dx = random.randint(-3, 3)
_tick2_frame = 0
_tick2_fps = 20000000
_tick2_t0 = time.time()
def tick(fps=60):
global _tick2_frame,_tick2_fps,_tick2_t0
n = _tick2_fps/fps
_tick2_frame += n
while n>0: n-=1
if time.time()-_tick2_t0>1:
_tick2_t0 = time.time()
_tick2_fps = _tick2_frame
_tick2_frame=0
def is_collided_with(a):
for ball in balls:
if abs(a.xcor() - ball.xcor()) < 3 and abs(a.ycor() - ball.ycor()) < 3:
a.dx *= -1
ball.dx *= -1
a.dy *= -1
ball.dy *= -1
turtle.onkey(addBall, "a")
turtle.onkey(removeBall, "p")
turtle.onkey(reload, "r")
turtle.onkey(turtle.bye, "q")
turtle.listen()
while True:
wn.update()
numOfBalls = len(balls)
if numOfBalls > 1:
wn.title(str(numOfBalls) + ' Bouncing Balls')
elif numOfBalls == 1:
wn.title(str(numOfBalls) + ' Bouncing Ball')
elif numOfBalls == 0:
wn.title(str(numOfBalls) + ' Bouncing Balls')
else:
wn.title('NaN Bouncing Balls')
for ball in balls:
ball.dy -= gravity
ball.sety(ball.ycor() + ball.dy)
ball.setx(ball.xcor() + ball.dx)
if ball.xcor() > 450 or ball.xcor() < -450:
ball.dx *= -1
if ball.ycor() < -300:
ball.sety(-300)
ball.dy *= -1
[is_collided_with(ball) for ball in balls]
tick(60)
turtle.listen()
turtle.mainloop()
【问题讨论】:
标签: python python-3.x turtle-graphics