使用Turtle World构建图像,python

时间:2016-05-06 01:35:15

标签: python image turtle-graphics

这是我的代码,它使用来自文本文件的指令来构建图像......指令指定了一只乌龟和一个方向x和y,例如:1,100,100。使用这只乌龟去的海龟第一号到x = 100,y = 100。

from swampy.TurtleWorld import *
  def draw_to(t,x,y,steps):

x_diff = x - t.get_x() 
x_step = 1.0*x_diff/steps 
y_diff = y - t.get_y()
y_step = 1.0*y_diff/steps
for step in range(steps):
 t.fd(x_step)
 t.lt()
 t.fd(y_step)
 t.rt()

def process (s,tlist):
parts = s.split(',')
t = tlist[int(parts[0])-1]
x = int(parts[1])
y = int(parts[2])
draw_to(t,x,y,50)


fturtles = open('turtles.txt','r') 
instructions = fturtles.readlines()
fturtles.close()


world = TurtleWorld()


turtle_list = []
num_turtles = int(instructions[0])
for tNum in range(num_turtles):
new_turtle = Turtle(world)
new_turtle.set_delay(0.01)
turtle_list.append(new_turtle)

 for lineNum in range(1,len(instructions)):
   process(instructions[lineNum],turtle_list)
   print "just processed", instructions[lineNum]


 wait_for_user()

代码工作正常,问题是我试图通过改变乌龟笔的颜色来改善功能,例如,如果我把文本文件放入:1,100,100,红色,它会告诉乌龟使用颜色为红色。我尝试在新功能中使用它,但我不知道如何做到这一点。如果有人可以帮助我澄清如何做到这一点,它将是一个先例。

1 个答案:

答案 0 :(得分:0)

如何重新定义process()功能如下:

STEPS = 50
# ...
def process(instruction, turtle_list):
    index, x, y, color = instruction.split(',')
    t = turtle_list[int(index) - 1]
    t.set_pen_color(color.strip())
    draw_to(t, int(x), int(y), STEPS)

使用简单的turtle.txt文件:

3
1, 100, 100, red
2, 100, 0, blue
3, 0, 100, green

我明白了:

enter image description here

我对你的代码进行了修改,但请注意我使用了Python 3和它附带的turtle模块,而不是TurtleWorld,但是大多数东西映射得相当好:

import sys
from turtle import *

class TurtleWorld(Turtle):
    """ for Turtle World compatibility """

    def set_pen_color(self, *args):
        return self.pencolor(*args)

    def get_x(self): return self.xcor()

    def get_y(self): return self.ycor()

STEPS = 50
DELAY = 0
instruction_filename = sys.argv[1]

def draw_to(t, x, y, steps):
    x_diff = x - t.get_x() 
    x_step = x_diff / float(steps)
    y_diff = y - t.get_y()
    y_step = y_diff / float(steps)
    for step in range(steps):
        t.fd(x_step)
        t.lt(90)
        t.fd(y_step)
        t.rt(90)

def process(instruction, turtle_list):
    index, x, y, color = instruction.split(',')
    t = turtle_list[int(index) - 1]
    t.set_pen_color(color.strip())
    draw_to(t, int(x), int(y), STEPS)

instruction_file = open(instruction_filename) 
instructions = instruction_file.readlines()
instruction_file.close()

turtle_list = []
num_turtles = int(instructions[0])
for tNum in range(num_turtles):
    new_turtle = TurtleWorld()
    turtle_list.append(new_turtle)
delay(DELAY)

for instruction in instructions[1:]:
    process(instruction, turtle_list)
    print("just processed", instruction)

exitonclick()