turtle.setworldcoordinates 函数有什么作用?

what does the turtle.setworldcoordinates function do?

初学者的 Python 书往往越到中间页越陡峭,几乎没有任何解释。因此,我很难弄清楚 turtle.setworldcoordinates 函数的作用,因为我无法通过阅读非常无用的文档并且无法凭经验推断出任何关于文档。谁能指出这个函数在海龟图形中的作用?

由于 turtle.py 附带 Python,并且写在 Python 中,您可以查看源代码以了解该函数的作用(我发现我经常使用turtle.py) 见下文。

我相信 setworldcoordinates() 可以让您 select 一个更方便解决您的问题的坐标系。例如,假设您不希望 (0,0) 位于屏幕中央。如果不合并偏移量,您可以使用 setworldcoordinates() 将其移动到一个角落,如果这样更适合您的话。您还可以设置在水平和垂直方向上具有不同比例因子的坐标系。

例如,请参阅 my answer to this question,其中我定义了一个例程,该例程使用 setworldcoordinates() 缩放您绘制的任何内容,而无需将任何缩放因子合并到您自己的绘图代码中。

或者你可以设置一个坐标系,角点在(0,0)、(1,0)、(0,1)和(1,1),完全在单位正方形内工作。

棘手的一点是它将您的坐标系映射到现有的 window 形状上——因此您必须将坐标调整为 window 或重塑 window 以匹配你的坐标系。否则你可能会发现自己的纵横比不理想。

def setworldcoordinates(self, llx, lly, urx, ury):
    """Set up a user defined coordinate-system.

    Arguments:
    llx -- a number, x-coordinate of lower left corner of canvas
    lly -- a number, y-coordinate of lower left corner of canvas
    urx -- a number, x-coordinate of upper right corner of canvas
    ury -- a number, y-coordinate of upper right corner of canvas

    Set up user coodinat-system and switch to mode 'world' if necessary.
    This performs a screen.reset. If mode 'world' is already active,
    all drawings are redrawn according to the new coordinates.

    But ATTENTION: in user-defined coordinatesystems angles may appear
    distorted. (see Screen.mode())

    Example (for a TurtleScreen instance named screen):
    >>> screen.setworldcoordinates(-10,-0.5,50,1.5)
    >>> for _ in range(36):
    ...     left(10)
    ...     forward(0.5)
    """
    if self.mode() != "world":
        self.mode("world")
    xspan = float(urx - llx)
    yspan = float(ury - lly)
    wx, wy = self._window_size()
    self.screensize(wx-20, wy-20)
    oldxscale, oldyscale = self.xscale, self.yscale
    self.xscale = self.canvwidth / xspan
    self.yscale = self.canvheight / yspan
    srx1 = llx * self.xscale
    sry1 = -ury * self.yscale
    srx2 = self.canvwidth + srx1
    sry2 = self.canvheight + sry1
    self._setscrollregion(srx1, sry1, srx2, sry2)
    self._rescale(self.xscale/oldxscale, self.yscale/oldyscale)
    self.update()

my book gives a weird example like this: setworldcoordinates(-10, 0.5, 1, 2), could you tell me what this operation exactly does?

setworldcoordinates() 这些奇怪的例子比比皆是,但解释很少,例如,请参阅@TessellatingHeckler 的幻灯片。它们只是表明你可以用坐标做极端的事情。但是要回答你的后续问题,如果我们有一个 100 x 100 window,这就是该特定调用对我们的坐标系所做的事情: