为什么使用turtle模块在我的python代码上触发冲突的意图早于意图?

问题描述 投票:-1回答:1

我在trinket.io上运行此代码。我试图让乌龟r与乌龟b碰撞时变为红色。由于某种原因,乌龟r会在视觉碰撞之前改变颜色。您将需要导入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)
python geometry collision-detection turtle-graphics
1个回答
0
投票

由于某种原因,乌龟会在视觉碰撞之前改变颜色。

这似乎是由于当所讨论的对象的diameter为20且radius为10时,您使用的radius为20。以下是我对您的代码的修改与此和其他调整:

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()
© www.soinside.com 2019 - 2024. All rights reserved.