【发布时间】:2016-01-17 04:08:52
【问题描述】:
下面的代码是 3 个函数和一个调用这些函数的 while 循环:
draw_rect():根据给定的参数绘制一个矩形
draw_circle():根据给定的参数画一个圆
draw_line():根据给定的参数画一条线
我的所有功能都可以正常工作,并且可以读取只有矩形、只有线条或只有圆形的文本文件。
我在底部的 while 循环是我遇到问题的地方。我有一个包含矩形和圆形的文件,最终成为 python 徽标。我无法弄清楚这个while循环需要做什么才能同时执行正确的功能。任何帮助将非常感激。我已经放了一个我正在使用的 txt 文件的样本。
蓝色
圆 -30 0 80
圆圈 0 30 80
黄色
圆圈 30 0 80
圆 0 -30 80
蓝色
直角 -84 55 60 110
直角 -84 55 25 120
直角 -30 80 88 82
黑色
圆 -20 -35 38
黄色
圈 -20 -35 32
黑色
直角 -58 -40 5 100
def draw_rect():
smart = turtle.Turtle()
i=0
while i < len(file_list):
if file_list[i] != "":
rect = file_list[i]
if rect[0] != 'rect':
return i
else:
color = str(rect[1])
x_coordinate = int(rect[2])
y_coordinate = int(rect[3])
width = int(rect[4])
height = int(rect[5])
smart.penup()
smart.fillcolor(color)
smart.begin_fill()
smart.goto(x_coordinate, y_coordinate)
smart.setheading(0)
smart.pendown()
smart.forward(width)
smart.right(90)
smart.forward(height)
smart.right(90)
smart.forward(width)
smart.right(90)
smart.forward(height)
smart.end_fill()
i += 1
return i
def draw_circle():
smart = turtle.Turtle()
i=0
while i < len(file_list):
if file_list[i] != "":
circ = file_list[i]
if circ[0] != 'circle':
return i
else:
color = str(circ[1])
x_coordinate = int(circ[2])
y_coordinate = int(circ[3])
radius = int(circ[4])
smart.penup()
smart.fillcolor(color)
smart.begin_fill()
smart.goto(x_coordinate, y_coordinate)
smart.setheading(0)
smart.pendown()
smart.circle(radius)
smart.end_fill()
i += 1
return i
def draw_line():
smart = turtle.Turtle()
i=0
while i < len(file_list):
if file_list[i] != "":
star = file_list[i]
if start[0] != 'line':
return i
else:
color = str(star[1])
x_coordinate = int(star[2])
y_coordinate = int(star[3])
angle = int(star[4])
line_length = int(star[5])
smart.penup()
smart.color(color)
smart.goto(x_coordinate, y_coordinate)
smart.setheading(angle)
smart.pendown()
smart.forward(line_length)
i += 1
return i
import turtle
turtle.speed(0)
file = input("What file would you like to execute?")
turtle.clearscreen()
with open(str(file),'r') as f:
file_list = []
for line in f:
if line == '\n':
continue
l = line.split()
if l[0].lower() == 'color':
color = l[1].lower()
else:
file_list.append([l[0].lower()] + [color] + l[1:])
print(file_list[0:])
n = 0
i = 0
while n < len(file_list):
n = n + i
while file_list[n] != "":
parameter = file_list[n]
print(parameter[0])
if parameter[0] != 'line' or parameter[0] != 'circle':
draw_rect()
elif parameter[0] != 'line' or parameter[0] != 'rect':
draw_circle()
elif parameter[0] != 'circle' or parameter[0] != 'rect':
draw_line()
print("Program complete")
【问题讨论】:
标签: python function while-loop turtle-graphics