2

我正在做一项家庭作业,其中的说明是:

使用 Turtle 图形,实现函数 planets(),该函数将模拟火星行星旋转一圈期间水星、金星、地球和火星的行星运动。你可以假设:

  1. 在模拟开始时,所有行星都排成一列(比如沿着负 y 轴)。
  2. 水星、金星、地球和火星与太阳(自转中心)的距离分别为 58、108、150 和 228 像素。
  3. 火星每旋转 1 度,地球、金星和水星将分别移动 2、3 和 7.5 度。

下图显示了当地球绕太阳运行大约四分之一时的模拟状态。请注意,水星几乎完成了它的第一次自转。

预期图像

我得到的输出是:

实际图像

这是我的代码:

import turtle
import math


s = turtle.Screen()
t = turtle.Turtle()

def jump(t,x,y):
    'makes turtle t jump to coordinates (x,y)'
    t.penup()
    t.goto(x,y)
    t.pendown()

def planets(t):

    #mercury
    jump(t,0,-58)
    t.circle(58,337.5)

    #venus
    jump(t,0,-108)
    t.circle(108,135)

#   earth
    jump(t,0,-150)
    t.circle(150,90)

#   mars
    jump(t,0,-228)
    t.circle(228,45)



planets(t)
turtle.done()

所以基本上,方向正在改变。如何获得所需的输出?如何阻止extent论点改变圆的方向?

4

1 回答 1

1

问题不在于它的extent论点,circle()而是你在乌龟完成前一个轨道时以任意方向开始每个新轨道。在绘制每个轨道之前,您需要将海龟设置为已知方向:

from turtle import Screen, Turtle

def jump(t, x, y):
    ''' makes turtle t jump to coordinates (x, y) '''

    t.penup()
    t.goto(x, y)
    t.pendown()

def planets(t):

    # mercury
    t.setheading(0)
    jump(t, 0, -58)
    t.circle(58, 337.5)
    t.stamp()

    # venus
    t.setheading(0)
    jump(t, 0, -108)
    t.circle(108, 135)
    t.stamp()

    # earth
    t.setheading(0)
    jump(t, 0, -150)
    t.circle(150, 90)
    t.stamp()

    # mars
    t.setheading(0)
    jump(t, 0, -228)
    t.circle(228, 45)
    t.stamp()

turtle = Turtle()
turtle.shape('circle')
turtle.shapesize(0.5)
turtle.hideturtle()

planets(turtle)

screen = Screen()
screen.exitonclick()

在此处输入图像描述

于 2020-05-01T21:53:57.657 回答