【问题标题】:Why does it say my mainloop is unreachable?为什么它说我的主循环无法访问?
【发布时间】:2020-02-22 06:09:38
【问题描述】:
import turtle 
import time

delay = 0.1

ms = turtle.Screen() 
ms.title("hungry snake Game by @Rafa") 
ms.bgcolor("green") 
ms.setup(width=600, height=600)
ms.tracer(0)

head = turtle.Turtle() 
head.speed(0) 
head.shape("square") 
head.color("black") 
head.penup() 
head.goto(0, 0) 
head.direction = "stop"

def move():
    if head.direction == "up":
        y = head.ycor()
        head.sety(y + 20)

    if head.direction == "down":
        y = head.ycor()
        head.sety(y - 20)

    if head.direction == "left":
        x = head.xcor()
        head.setx(x + 20)

    if head.direction == "right":
        x = head.xcor()
        head.setx(x - 20)


# main game loop

while True:
    ms.update()
    move()

    time.sleep(delay)

//Here is where am having trouble with the code?

ms.mainloop()

【问题讨论】:

  • 你有一个永无止境的while循环。之后的任何事情都无法访问
  • @khelwood 他发布的代码格式不正确,我可能在修复时弄错了缩进,所以我修复了它。
  • 应该是turtle.mainloop(),而不是ms.mainloop()
  • @Barmar 问题的标题是询问为什么代码无法访问,而不是为什么它不起作用。在您重新编辑之前,最后一行无法访问,这大概就是问题所在。
  • 哎呀,你是对的。但他也说错了,链接的问题显示了如何解决这个问题。

标签: python loops pycharm turtle-graphics


【解决方案1】:

这里真正的错误是在像turtle这样的事件驱动环境中使用while True:sleep()。我们可以用海龟ontimer()方法替换无限循环和time.sleep()

from turtle import Screen, Turtle

DELAY = 100  # milliseconds

def move():
    if direction == 'up':
        y = turtle.ycor()
        turtle.sety(y + 20)
    elif direction == 'down':
        y = turtle.ycor()
        turtle.sety(y - 20)
    elif direction == 'left':
        x = turtle.xcor()
        turtle.setx(x - 20)
    elif direction == 'right':
        x = turtle.xcor()
        turtle.setx(x + 20)

    screen.update()
    screen.ontimer(move, DELAY)

def up():
    global direction
    direction = 'up'

def down():
    global direction
    direction = 'down'

def left():
    global direction
    direction = 'left'

def right():
    global direction
    direction = 'right'

screen = Screen()
screen.title("Hungry Snake Game")
screen.bgcolor('green')
screen.setup(width=600, height=600)
screen.tracer(0)

turtle = Turtle()
turtle.shape('square')
turtle.speed('fastest')
turtle.penup()

direction = 'stop'

screen.onkey(up, 'Up')
screen.onkey(down, 'Down')
screen.onkey(left, 'Left')
screen.onkey(right, 'Right')
screen.listen()

# main game loop

move()

screen.mainloop()

【讨论】:

  • 你能分享一些关于ontimer的知识吗?方法有什么用? @cdlane?
猜你喜欢
  • 2021-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-06
  • 1970-01-01
  • 2015-01-11
  • 2014-04-06
相关资源
最近更新 更多