Python 3 Turtle:如何启用环绕

Python 3 Turtle: How to enable wrap around

Turtle and Logo 是探索编程的好方法。 Python 3 包含一个很棒的 turtle 模块。

不幸的是,Python 3 turtle 似乎不支持环绕。如果乌龟离开屏幕,它会停留在那里,而不是到另一边。对于不知道如何将其取回的孩子来说,这可能会非常令人沮丧。

有没有办法或解决方法在 Python 3 turtle 中绕过?

Is there a way or work around to get wrap around in Python 3 turtle?

是的,你可以实现它!同时向孩子们展示 object-oriented 编程的力量!一个simple-minded例子:

from turtle import Screen, Turtle, _CFG

class WrappedTurtle(Turtle):
    def __init__(self, shape=_CFG['shape'], undobuffersize=_CFG['undobuffersize'], visible=_CFG['visible']):
        super().__init__(shape=shape, undobuffersize=undobuffersize, visible=visible)

    def forward(self, distance):
        super().forward(distance)

        screen = self.getscreen()

        x_flag = abs(self.xcor()) > screen.window_width()/2
        y_flag = abs(self.ycor()) > screen.window_height()/2

        if x_flag or y_flag:
            down = self.isdown()

            if down:
                self.penup()

            x, y = self.position()

            self.hideturtle()
            self.setposition(-x if x_flag else x, -y if y_flag else y)
            self.showturtle()

            if down:
                self.pendown()


if __name__ == '__main__':
    screen = Screen()

    yertle = WrappedTurtle('turtle')
    yertle.speed('fastest')
    yertle.left(31)

    while True:
        yertle.forward(2)

    screen.mainloop()  # never reached