Python Turtle Positional Errors

这一生的挚爱 提交于 2019-12-12 02:59:39

问题


I've been trying to scale a Turtle drawing by a single axis and after some testing, I managed the following function:

def DrawSquare(length=50.0, Yscale=2):

   setheading(0)

   for n in range(0,4):
      oldYcor = int(ycor())
      oldPos = pos()
      penup()
      forward(length)
      newYcor = int(ycor())

      print 'OldYcor = ', int(oldYcor)
      print 'NewYcor = ', int(newYcor)
      print '------'

      setpos(oldPos)
      pendown()

      if (oldYcor == newYcor):
          print 'dont scale'          
          forward(length)
      elif (oldYcor != newYcor):
          print 'scale'
          forward(length*Yscale)

      left(90)

penup()
speed('slowest')
goto(0,0)

#TESTS
DrawSquare(50.0, 2)
DrawSquare(50.0, 2)
DrawSquare(50.0, 2)
DrawSquare(50.0, 2)

The output of these tests should just be four overlapping squares scaled on the y axis, but for some very strange reason Python is randomly changing my Y values before and after a movement by 1 unit, when they should be the same. (for instance, a line being drawn horizontally has an oldYcor of 99, but a newYcor of 100), which completely breaks my code and produces the squares out of place.

Another strange thing i noticed is that without converting the turtle's ycor() to an int, the print statements display some bizarre values that dont make any sense to me...

I appreciate any help!!


回答1:


Although Python's turtle graphics provide all the usual transformations (scale, shear, tilt, etc.) for the turtle image itself, it doesn't provide them for the images it draws! Rather than add a scaling factor to every drawing routine you define, let's try to manipulate the image scale independent of your drawing routines:

from turtle import *
import time

SCREEN_WIDTH = 400
SCREEN_HEIGHT = 400

def DrawSquare(length=1):

    oldPos = pos()
    setheading(0)
    pendown()

    for n in range(0, 4):
        forward(length)
        left(90)

    setpos(oldPos)

def Scale(x=1, y=1):
    screen = Screen()
    screen.setworldcoordinates(- (SCREEN_WIDTH / (x * 2)), - (SCREEN_HEIGHT / (y * 2)), (SCREEN_WIDTH / (x * 2)), (SCREEN_HEIGHT / (y * 2)))

setup(SCREEN_WIDTH, SCREEN_HEIGHT)
mode("world")

penup()
goto(-25, -25)

# TESTS

Scale(1, 1) # normal size
DrawSquare(50)
time.sleep(2)

Scale(1, 2)  # twice as tall
time.sleep(2)

Scale(2, 1)  # twice as wide
time.sleep(2)

Scale(2, 2)  # twice as big
time.sleep(2)

Scale(1, 1)  # back to normal

done()

Just set Scale(1, 2) to make anything you draw twice as big in the Y dimension. Either before or after you draw it.



来源:https://stackoverflow.com/questions/36224422/python-turtle-positional-errors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!