我正在尝试让龟r
与龟b
碰撞时将颜色更改为红色。由于某种原因,它会在视觉碰撞之前改变颜色。我不确定该怎么办,请帮忙。
我在trinket.io
上运行此代码。您将需要导入turtle和数学来运行它。
blue = {'turtle':turtle.Turtle(),'radius': 20,'x':100,'y': 5,'speed': 5}
ran = {'turtle':turtle.Turtle(),'radius': 20,'x': 100,'y':0}
game = {"status": "new", "mode": "play"}
b = blue['turtle']
b.penup()
b.shape('circle')
r = ran['turtle']
r.penup()
r.setx(ran['x'])
r.sety(ran['y'])
r.shape('circle')
screen = b.getscreen()
def up():
current_y = b.ycor()
new_y = current_y + blue['speed']
b.sety(new_y)
def down():
current_y = b.ycor()
new_y = current_y - blue['speed']
b.sety(new_y)
def left():
current_y = b.xcor()
new_y = current_y - blue['speed']
b.setx(new_y)
def right():
current_y = b.xcor()
new_y = current_y + blue['speed']
b.setx(new_y)
def coll(obj_1,obj_2):
turt_1 = obj_1['turtle']
turt_2 = obj_2['turtle']
dx = turt_1.xcor() - turt_2.xcor()
dy = turt_1.ycor() - turt_2.ycor()
distance = math.sqrt(dx**2 + dy**2)
if distance <= obj_1['radius'] + obj_2['radius']:
turt_2.color('red')
else:
turt_2.color('black')
screen.onkey(up,'Up')
screen.onkey(down,'down')
screen.onkey(left,'left')
screen.onkey(right,'right')
screen.listen()
# continue until game is over
while game["status"] != "over":
# if not paused
if (game["mode"] != "paused"):
coll(blue,ran)
答案 0 :(得分:0)
由于某种原因,乌龟会在视觉碰撞之前改变颜色。
这似乎是由于当所讨论的对象的直径为20而 radius 为20时,您使用了 radius 的结果。 10.以下是我通过此调整和其他调整对您的代码的重做:
import turtle
import math
blue = {'turtle': turtle.Turtle(), 'radius': 10, 'x': 0, 'y': 0, 'speed': 5}
ran = {'turtle': turtle.Turtle(), 'radius': 10, 'x': 100, 'y': 0}
def up():
b.sety(b.ycor() + blue['speed'])
coll(blue, ran)
def down():
b.sety(b.ycor() - blue['speed'])
coll(blue, ran)
def left():
b.setx(b.xcor() - blue['speed'])
coll(blue, ran)
def right():
b.setx(b.xcor() + blue['speed'])
coll(blue, ran)
def coll(obj_1, obj_2):
turt_1 = obj_1['turtle']
turt_2 = obj_2['turtle']
dx = turt_1.xcor() - turt_2.xcor()
dy = turt_1.ycor() - turt_2.ycor()
distance = math.sqrt(dx**2 + dy**2)
if distance <= obj_1['radius'] + obj_2['radius']:
turt_2.color('red')
else:
turt_2.color('black')
b = blue['turtle']
b.shape('circle')
b.penup()
b.color('blue')
b.setposition(blue['x'], blue['y'])
r = ran['turtle']
r.shape('circle')
r.penup()
r.setposition(ran['x'], ran['y'])
screen = b.getscreen()
screen.onkey(up, 'Up')
screen.onkey(down, 'Down')
screen.onkey(left, 'Left')
screen.onkey(right, 'Right')
screen.listen()
screen.mainloop()