Я пытаюсь заставить лепестки вращаться от оранжевого, желтого до оранжевого цвета в виде петли, но на четвертом лепесткеPython

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 Я пытаюсь заставить лепестки вращаться от оранжевого, желтого до оранжевого цвета в виде петли, но на четвертом лепестке

Сообщение Anonymous »

Я выполняю задание по изготовлению из черепах лепестков подсолнуха из пятиугольников. Все как и должно быть, кроме цвета лепестков. В нем строго указано, что цвета указанных пятиугольников должны чередоваться «оранжевый, желтый, оранжевый, желтый», и с этого момента это повторяется. Для этого нам нужно использовать функции, и, поскольку я вообще новичок в информатике, мне сложно выяснить причину того, почему четвертый лепесток подсолнуха в каждом тесте отображается черным, а не желтым.
Я попробовал определить термин «желтый» как «tur.pencolor('yellow') (tur — это имя черепахи в моей программе), и в результате ничего не изменилось. На данный момент, учитывая мои ограниченные знания в этой области, я в тупике и ищу здесь помощи, чтобы кто-нибудь спас мою шкуру и разобрался за меня с этой функциональной ситуацией!
Вот мой код на данный момент:
import turtle
# Define function draw_petal

def draw_petal(tur, speed, n_sided, radius):
"""
Draws a petal of a sunflower using turtle graphics.

Parameters:
- tur (turtle.Turtle): The turtle object used for drawing.
- speed (int): The drawing speed of the turtle. Accepts standard turtle speed inputs.
- n_sided (int): The number of sides of the petal, indicating its shape.
- radius (float): The radius of the petal, measured from the center to any vertex.

The function draws a petal as an n-sided polygon with the specified radius. The petal shape is
determined by the number of sides (n_sided) and its size by the radius.

Note: The turtle will start drawing from its current position and heading.
"""
# TODO: Remove pass and provide your own code below
angle = 360 / n_sided

for i in range(n_sided):
tur.forward(radius)
tur.left(angle)

# Define fuction draw_sunflower
def draw_sunflower(tur, speed, n_sided, radius, num_petal):
"""
Draws a sunflower using turtle graphics.

Parameters:
- tur (turtle.Turtle): The turtle object used for drawing.
- speed (int): The drawing speed of the turtle. Accepts standard turtle speed inputs.
- n_sided (int): The number of sides for each petal, indicating the shape of the petal.
- radius (float): The radius of each petal, measured from the center to any vertex.
- num_petal (int): The total number of petals to draw for the sunflower.

The function will alternate petal colors between 'orange' and 'yellow'. The heading angle and current
color of each petal are printed to the console during the drawing process for diagnostic purposes.

Note: This function assumes a helper function `draw_petal` is defined elsewhere to draw individual petals.
"""
# TODO: Remove pass and provide your own code below
tur.speed(speed)
angle_increment = 360 / num_petal
c = tur.color()

for i in range(num_petal):
draw_petal(tur, speed, n_sided, radius)
if(i % 2 == 0):
tur.color("yellow")
if(i % 2 == 1):
tur.color("orange")
# Diagnostic printout
print(f"Current color: {c}, heading angle {tur.heading()} degrees")

tur.left(angle_increment)

# Define the main() function for drawing sunflowers using turtle graphics.
#
# This function sets up a turtle environment and prompts the user
# for inputs to draw a sunflower. The user can choose the animation
# speed, the number of sides for a petal, the radius of petals, and
# the total number of petals.
#
# After drawing a sunflower based on the user's input, the program
# asks the user if they'd like to draw another sunflower. If the
# user enters "yes", the screen will be cleared and the user will be
# prompted for new input values. If the user enters "no", a message
# will be displayed prompting the user to click on the window to exit.
#
# If the user enters any other command, an error message is printed
# and the user is prompted again.
#
# The function concludes by waiting for the user to click on the turtle
# window, at which point it will close the window and exit the program.

def main():
screen = turtle.Screen()
screen.title("Sunflower Drawing")

tur = turtle.Turtle()

while True:
# User input
speed = int(input("Enter animation speed: "))
n_sided = int(input("Enter the number of sides of a petal: "))
radius = float(input("Enter the radius of petals: "))
num_petal = int(input("Enter the number of petals: "))

# Draw the sunflower
draw_sunflower(tur, speed, n_sided, radius, num_petal)

# Ask if the user wants to draw another sunflower
response = input("Draw Another Sunflower?" )

if response == "yes":
tur.clear()
tur.penup()
tur.home()
tur.pendown()
elif response == "no":
tur.penup()
tur.goto(0, -200)
tur.write("Click window to exit...", align="right", font=("Courier", 12, "normal"))
break
turtle.exitonclick()
else:
print("Invalid command! Please try again…")

screen.mainloop()

# Run the program
if __name__ == "__main__":
main()

# turtle.exitonclick()


Подробнее здесь: https://stackoverflow.com/questions/790 ... -orange-as
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Python»