import math import string class Turtle: def __init__(self, model, theta): self.model = model self.theta = theta self.margin = 0 self.x0 = 0 self.y0 = 0 self.alpha0 = 0 def draw(self, draw_line): x = self.x0 y = self.y0 alpha = self.alpha0 stack = [] for l in self.model: if l == "+": alpha += self.theta elif l == "-": alpha -= self.theta elif l in string.ascii_uppercase: x_new = x + math.cos(alpha) y_new = y + math.sin(alpha) draw_line((x, y), (x_new, y_new)) x = x_new y = y_new elif l in string.ascii_lowercase: x += math.cos(alpha) y += math.sin(alpha) elif l == "[": stack.append((x, y, alpha)) elif l == "]": x, y, alpha = stack.pop() def get_bounds(self): min = [0, 0] max = [0, 0] def update_bounds(p1, p2): def upd_bounds(p): x, y = p if x > max[0]: max[0] = x elif x < min[0]: min[0] = x if y > max[1]: max[1] = y elif y < min[1]: min[1] = y upd_bounds(p1) upd_bounds(p2) self.draw(update_bounds) return (min[0], min[1]), (max[0], max[1]) def get_scaling_fn(self, res): min_b, max_b = self.get_bounds() m2 = self.margin * 2 s = min((res[0] - m2) / (max_b[0] - min_b[0]), (res[1] - m2) / (max_b[1] - min_b[1])) x0 = -min_b[0] * s y0 = -min_b[1] * s def scaling_fn(p): x_scr = x0 + self.margin + p[0] * s y_scr = y0 + self.margin + p[1] * s return x_scr, y_scr return scaling_fn