我已经添加了一个函数定义,当你按下空格键时告诉我的乌龟跳起来。在我的代码中还有一个while True
循环,只要按下空格键,while True
循环就会暂时冻结,直到跳转完成,然后继续执行。
我已经尝试在while True
循环和外部添加函数定义。我只能将函数定义放在while True
循环之前,因为如果我把它放在while True
之后,代码将永远不会到达它。
#making the player jump
def jump():
player.fd(100)
player.rt(180)
player.fd(100)
player.lt(180)
turtle.listen()
turtle.onkey(jump, "space")
我希望while True
循环不会冻结,但无论我在哪里尝试放置def
,它似乎都不起作用。
我也看到了与此类似的另一个答案,但我不明白如何将其应用于我的代码。
任何其他的建议都会很棒。
发布于 2019-04-07 22:50:07
在你让异步的东西工作之前,这里有一个最简单的实现,使用turtle自己的计时器事件来保持障碍向前移动,即使是在跳跃的时候:
from turtle import Screen, Turtle
def jump():
screen.onkey(None, 'space') # disable handler inside handler
if jumper.ycor() == 0: # if jumper isn't in the air
jumper.forward(150)
jumper.backward(150)
screen.onkey(jump, 'space')
def move():
hurdle.forward(6)
if hurdle.xcor() > -400:
screen.ontimer(move, 100)
jumper = Turtle('turtle')
jumper.speed('slowest')
jumper.penup()
jumper.setheading(90)
hurdle = Turtle('turtle')
hurdle.speed('fastest')
hurdle.penup()
hurdle.setheading(180)
hurdle.setx(400)
screen = Screen()
screen.onkey(jump, 'space')
screen.listen()
move()
screen.mainloop()
你可以找到几个,更丰富的版本,所以通过搜索‘海龟-图形跳转’
避免在turtle的基于事件的环境中使用while True:
循环。
发布于 2019-04-07 22:52:27
我本以为用async
很难做到这一点,但我构建了一个可以工作的示例。
在jump
中,我使用asyncio.sleep
,这样当一只海龟在睡觉时,其他海龟就可以行走了。没有asyncio.sleep
,第一只乌龟一直在散步。
import asyncio
import turtle
t1 = turtle.Turtle()
t2 = turtle.Turtle()
async def jump1():
while True:
t1.fd(100)
await asyncio.sleep(0.01)
t1.left(90)
async def jump2():
while True:
t2.fd(100)
await asyncio.sleep(0.01)
t2.right(90)
tasks = [jump1(), jump2()]
# Python 3.6.7
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))
# Python 3.7
#asyncio.run(asyncio.wait(tasks))
但构建更复杂的东西可能会更困难。
我还找到了使用async
的aioturtle - turtle。也许使用aioturtle
会更容易。
发布于 2019-04-07 19:27:32
问题如下:
跳转事件的代码被同步调用。这意味着,在继续之前,一切都必须等待跳转()完成。这可以通过异步声明/调用jump()方法来修复。这个网站很好地解释了异步python的含义以及如何实现它:https://hackernoon.com/asynchronous-python-45df84b82434
简而言之,它是如何实现的(在python 3.3或更高版本中):
async def jump():
#your code here
这只会使jump()函数异步运行。
现在,当你调用它的时候,你必须这样调用它:
await jump()
这可能不起作用,这取决于您的确切设置。
我希望这能帮到你。如果你还有其他问题,请问我。
编辑:示例
https://stackoverflow.com/questions/55562732
复制