我试图从字典中提取字符串,并想在wave函数中迭代它们。乌龟应该使用x和y的值制作正弦波。我也尝试了一个列表,但那并没有奏效。也许这是不可能的,我对这个问题的看法都是错误的。
import turtle, math
def createTurtle(count):
for x in range(count):
turtle_dict[x] = turtle.Turtle()
turtle_dict[x].shape("turtle")
turtle_dict[x].color(color_list[x])
turtle_dict[x].width(3)
return turtle_dict[x]
def wave(count):
for n in range(count):
amp = amp_list[n]
freq = freq_list[n]
createTurtle(n)
for x in range(361):
y_val = amp * math.sin(math.radians(x * freq))
turtle_dict.values().goto(x, y_val)
print(x, y_val)
num_waves = int(input("How many sine waves do you want to create? "))
amp_list = []
freq_list = []
turtle_dict = {1 : "alpha", 2 : "beta", 3 : "gamma", 4 : "delta", 5 : "omega"}
color_list = ["red", "blue", "green", "purple", "pink"]
counter = 1
for x in range(num_waves):
print("\nSine Wave #" , counter)
amp = int(input("Enter the amplitude of the sine wave: "))
freq = float(input("Enter the frequency of the sine wave: "))
amp_list.append(amp)
freq_list.append(freq)
counter += 1
print(amp_list)
print(freq_list)
print(turtle_dict)
amp_screen = max(amp_list) + 1
win = turtle.Screen()
win.bgcolor("lightyellow")
win.setworldcoordinates(0,-amp_screen, 500 ,amp_screen)
wave(counter-1)
win.exitonclick()
答案 0 :(得分:1)
我的分析是你可以用一个列表来做到这一点 - 你不需要字典 - 而且它不起作用的原因是你的代码非常错误。例如,createTurtle()
有一个缩进错误,导致它过早返回。并且它被调用的地方不正确,传递一个循环计数器而不是循环的范围。 turtle_dict
未正确使用,在海龟列表(goto()
)上调用.values()
而不是单个海龟。
我的工作是修复我发现的问题并调整代码风格:
import math
from turtle import Turtle, Screen
from itertools import cycle
color_list = ['red', 'blue', 'green', 'purple', 'pink']
def createTurtles(count):
turtles = []
colors = cycle(color_list)
for _ in range(count):
turtle = Turtle('turtle')
turtle.color(next(colors))
turtle.speed('fastest')
turtle.width(3)
turtles.append(turtle)
return turtles
def wave(count):
for n in range(count):
amp = amp_list[n]
freq = freq_list[n]
turtle = turtles_list[n]
turtle.penup()
for x in range(361):
y_val = amp * math.sin(math.radians(x * freq))
turtle.goto(x, y_val)
turtle.pendown()
num_waves = int(input('How many sine waves do you want to create? '))
amp_list = []
freq_list = []
counter = 1
for x in range(num_waves):
print('\nSine Wave #', counter)
amp = int(input('Enter the amplitude of the sine wave: '))
freq = float(input('Enter the frequency of the sine wave: '))
amp_list.append(amp)
freq_list.append(freq)
counter += 1
amp_screen = max(amp_list) + 1
screen = Screen()
screen.bgcolor('lightyellow')
screen.setworldcoordinates(0, -amp_screen, 400, amp_screen)
turtles_list = createTurtles(num_waves)
wave(counter - 1)
screen.exitonclick()