如何一次只能移动一只乌龟?

时间:2020-07-10 01:49:59

标签: python turtle-graphics python-turtle

因此,在添加第27和42行的if语句之前,我的程序已经运行: 分别为if (currentTurtle == "") or (currentTurtle == "one"):if (currentTurtle == "") or (currentTurtle == "two"):。在添加这些检查之前,如果乌龟确实彼此靠近,它们只会同时移动,因为我使用了if语句来检查光标到乌龟的距离。我尝试在第27行和第42行上添加检查,一次只能移动一个,但是后来我的乌龟变得没有反应了。

这是我的代码:

from turtle import Screen, Turtle

screen = Screen()

turt1 = Turtle("turtle")
turt2 = Turtle("turtle")
turt1.speed(0)
turt2.speed(0)
turt1.shape('circle')
turt2.shape('circle')
turt1.color('green')
turt2.color('blue')

turt1.penup()
turt1.goto(-100,100)
turt2.penup()
turt2.goto(100,-100)

currentTurtle = ""

def resetCurrent():
  currentTurtle = ""

def dragging(x, y):
  if (x <= turt1.xcor() + 10) and (x >= turt1.xcor() - 10):
    if (y <= turt1.ycor() + 10) and (y >= turt1.ycor() - 10):
      if (currentTurtle == "") or (currentTurtle == "one"):
        currentTurtle = "one"
    elif (currentTurtle == "one"):
      currentTurtle == ""
  elif (currentTurtle == "one"):
    currentTurtle == ""

  if currentTurtle == "one":
    if (x <= turt1.xcor() + 10) and (x >= turt1.xcor() - 10):
      if (y <= turt1.ycor() + 10) and (y >= turt1.ycor() - 10):
        turt1.goto(x, y)

def dragging2(x, y):
  if (x <= turt2.xcor() + 10) and (x >= turt2.xcor() - 10):
    if (y <= turt2.ycor() + 10) and (y >= turt2.ycor() - 10):
      if (currentTurtle == "") or (currentTurtle == "two"):
        currentTurtle = "two"
    elif (currentTurtle == "two"):
      currentTurtle = ""
  elif (currentTurtle == "two"):
    currentTurtle = ""

  if currentTurtle == "two":
    if (x <= turt2.xcor() + 10) and (x >= turt2.xcor() - 10):
      if (y <= turt2.ycor() + 10) and (y >= turt2.ycor() - 10):
        turt2.goto(x, y)

def main():  # This will run the program
    screen.listen()
    
    turt1.ondrag(dragging)
    turt2.ondrag(dragging2)

    screen.mainloop()  # This will continue running main() 

main()

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您的dragging()代码已经变得非常复杂,以至于您无法理解想要和您正在做什么 。我将以一种完全不同的,更简单的方法重新开始:

from turtle import Screen, Turtle
from functools import partial

def dragging(tortoise, x, y):
    for turtle in screen.turtles():  # disable event handlers inside handler
        turtle.ondrag(None)

    tortoise.goto(x, y)

    for turtle in screen.turtles():  # reenable event handers on the way out
        turtle.ondrag(partial(dragging, turtle))

def main():

    turtle_1.ondrag(partial(dragging, turtle_1))
    turtle_2.ondrag(partial(dragging, turtle_2))

    screen.mainloop()

screen = Screen()

turtle_1 = Turtle('turtle')
turtle_1.shape('circle')
turtle_1.speed('fastest')
turtle_1.penup()

turtle_1.color('green')
turtle_1.goto(-100, 100)

turtle_2 = turtle_1.clone()  # turtle_2 is a lot like turtle_1

turtle_2.color('blue')
turtle_2.goto(100, -100)

main()

这是否给您您想要的控制和行为?如果不是,请在您的问题中告诉我们您想要发生什么,而不仅仅是代码不执行什么事情。