我被指派用 python 创建类似版本的
slither.io
。我计划使用Turtle
。如何让 turtle
跟随鼠标移动而不必每次都点击?
这就是我点击时的做法,但我宁愿不必点击:
from turtle import *
turtle = Turtle()
screen = Screen()
screen.onscreenclick(turtle.goto)
turtle.getscreen()._root.mainloop()
其关键是在海龟上使用
ondrag()
事件处理程序。一个简短但不太甜蜜的解决方案:
import turtle
turtle.ondrag(turtle.goto)
turtle.mainloop()
在开始拖动后不久可能会崩溃。更好的解决方案是拖动更大的海龟,并关闭拖动处理程序内的拖动处理程序以防止事件堆积:
from turtle import Turtle, Screen
def dragging(x, y):
yertle.ondrag(None)
yertle.setheading(yertle.towards(x, y))
yertle.goto(x, y)
yertle.ondrag(dragging)
screen = Screen()
yertle = Turtle('turtle')
yertle.speed('fastest')
yertle.ondrag(dragging)
screen.mainloop()
请注意,您必须单击并拖动海龟本身,而不仅仅是单击屏幕上的某个位置。如果你想让乌龟跟随鼠标而不按住左键,请参阅我对用鼠标指针移动Python乌龟的回答。