How to speed up python's 'turtle' function and stop it freezing at the end

后端 未结 4 1813
后悔当初
后悔当初 2020-12-05 14:13

I have written a turtle program in python, but there are two problems.

  1. It goes way too slow for larger numbers, I was wonder how I can speed up turtle.
4条回答
  •  醉梦人生
    2020-12-05 14:30

    For reference, turtle being slow is an existing problem. Even with speed set to max, turtle can take quite a long time on things like fractals. Nick ODell reimplemented turtle for speed here: Hide Turtle Window?

    import math
    
    class UndrawnTurtle():
    def __init__(self):
        self.x, self.y, self.angle = 0.0, 0.0, 0.0
        self.pointsVisited = []
        self._visit()
    
    def position(self):
        return self.x, self.y
    
    def xcor(self):
        return self.x
    
    def ycor(self):
        return self.y
    
    def forward(self, distance):
        angle_radians = math.radians(self.angle)
    
        self.x += math.cos(angle_radians) * distance
        self.y += math.sin(angle_radians) * distance
    
        self._visit()
    
    def backward(self, distance):
        self.forward(-distance)
    
    def right(self, angle):
        self.angle -= angle
    
    def left(self, angle):
        self.angle += angle
    
    def setpos(self, x, y = None):
        """Can be passed either a tuple or two numbers."""
        if y == None:
            self.x = x[0]
            self.y = x[1]
        else:
            self.x = x
            self.y = y
        self._visit()
    
    def _visit(self):
        """Add point to the list of points gone to by the turtle."""
        self.pointsVisited.append(self.position())
    
    # Now for some aliases. Everything that's implemented in this class
    # should be aliased the same way as the actual api.
    fd = forward
    bk = backward
    back = backward
    rt = right
    lt = left
    setposition = setpos
    goto = setpos
    pos = position
    
    ut = UndrawnTurtle()
    

提交回复
热议问题