2010-01-11

2010-01-11 Happy New Year!

In order to celebrate the new year properly, here is a python script to create an impossible triangle. Paste the code into a file (e.g. triangle.py), run it and pipe the result into an .svg file:
./triangle.py > triangle.svg





#!/usr/bin/env python

import math

w = 400
d = 40

class Point:
def __init__(self, x, y):
self.x = x
self.y = y

frac = d / math.sqrt(3)
origin = Point(0.5*frac, w*math.sqrt(3)/2-d/2)
current = origin
a1 = Point(frac, d)
b1 = Point(2*frac, 0)
c1 = Point(5*frac, d)
d1 = Point(6*frac, 2*d)
a2 = Point(w-6*frac, 2*d)
b2 = Point(w-4*frac, 2*d)
c2 = Point(w-2*frac, 0)
d2 = Point(w-frac, d)
a3 = Point(w/2-frac, w/2*math.sqrt(3)-d)
b3 = Point(w/2+frac, w/2*math.sqrt(3)-d)
c3 = Point(w/2-frac, w/2*math.sqrt(3)-3*d)
d3 = Point(w/2, w/2*math.sqrt(3)-4*d)

def path(color, lineWidth, points):
global current
current = origin
path = ''
for p in points:
path += '%f,%f ' % (p.x-current.x, -p.y+current.y)
current = p
return '<path style="fill: %s; stroke: #000000; stroke-width: %ipx; stroke-linecap: butt; stroke-linejoin: miter; stroke-opacity: 1" d="m %s z"/>' % (color, lineWidth, path)

print '<?xml version="1.0" standalone="no"?>'
print '<svg xmlns="http://www.w3.org/2000/svg" width="%i" height="%i" id="svg2" version="1.1">' % (w, w*math.sqrt(3)/2)
print path('#FF7F7F', 1, (b1, c2, d2, c1, d3, c3))
print path('#7FFF7F', 1, (d2, b3, a3, b2, d1, c1))
print path('#7F7FFF', 1, (a3, a1, b1, c3, a2, b2))
print path('none', 2, (b1, c2, d2, b3, a3 ,a1))
print '</svg>'





This is what it looks like:

2 comments:

Working Title said...

Oh, and by the way: w and d change the size and thickness, respectively.
Also, replacing both "butt" and "miter" by "round" would probably make it even prettier.

College Term Papers said...

I really like this blog, It's always nice when you can not only be informed, but also get knowledge, from these type of blog, nice entry. Thanks