Welcome, guest | Sign In | My Account | Store | Cart

Covers a plane with two types of tiles, (Perose tiles). The pattern is interesting as it is nonperiodic and has a five fold symetry

Python, 512 lines
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
# This progam creates a non periodic tiling of the plane using 'Penrose tiles',
# wich were invented by Roger Penrose.
# Each time it runs it will generate a new random pattern.
# There are an infinite number of them.
# Unlike a periodic tesselation the assembly requires forward planning and
# hence the program searches through various combinations of parts, often
# comming to a dead end and having to backtrack.
# The program has three phases, the first generating the initial layout with
# a simple sharks tooth design
# The second fills in the tiles completely
# The third phase reveals an inner fractal pattern by the process of deflation
# then deflating again over and over
# You must close the progam to stop it.
from __future__ import division
from Tkinter import * 
from math import cos, sin, atan2, sqrt, pi
from random import random, shuffle, seed
from numpy import array, dot, transpose
from copy import deepcopy
from sys import getrecursionlimit, setrecursionlimit

nW = 800.0 # change these to make the screen bigger or smaller
nH = 600.0
canvas = Canvas( width = nW, height = nH, bg = 'darkred')
canvas.pack(expand = YES, fill = BOTH)

# setrecursionlimit(10000)
nRecLim = getrecursionlimit()
nScale = 30.0 # sqrt(nW * nH / nRecLim) / nFib #25.0 # change this to make the tile bigger or smaller
nFib   = (1.0 + sqrt(5.0))/2.0 # Fibonacci's golden ratio
nSmall = 5 # the smallest possible gap should be 18`
n36    = 36.0 * pi / 180.0
nSin36 = sin(n36)
nCos36 = cos(n36)
n72    = 72.0 * pi / 180.0
nSin72 = sin(n72)
nCos72 = cos(n72)
nSelfX = nScale * nFib * nSin36
nSelfY = nScale * nFib * nCos36
nW2 = nW / 2
nH2 = nH / 2
nTag = 0
nRatioSmall = nScale * nFib / (nFib + 1)
nRatioBig   = nScale * nFib**2 / (nFib + 1)
lAlternate = False    
def NewTag():
    global nTag
    nTag += 1
    return "TAG%d" %(nTag)

def Scalar(midx, midy, nR, x0, y0):
    midx -= x0
    midy -= y0
    midR = sqrt(midx**2 + midy**2)
    if midR == 0:
        return [x0, y0]
    midx *= nR / midR
    midy *= nR / midR
    midx += x0
    midy += y0
    return [midx,midy]

def MidArc(p1, p2, p0, nR):
    x0 = p0[0]
    y0 = p0[1]
    x1 = p1[0] 
    y1 = p1[1] 
    x2 = p2[0] 
    y2 = p2[1] 
    midx = (x1 + x2) / 2
    midy = (y1 + y2) / 2
    return Scalar(midx, midy, nR, x0, y0)

def Perimeter(aP, lComplete = False):
    points = [] 
    for i in aP:
        points += (i[0], i[1])
    if lComplete:
        points += (aP[0][0], aP[0][1])
    return points    

def linearTranslation(a1, points, r, a2):
    nL = len(points)
    p1 = array([a1] * nL, 'f')
    q = points - p1
    q = transpose(q)
    q = dot(r, q)
    q = transpose( q)
    p2 = array([a2] * nL, 'f')
    q = q + p2
    return q
       
class shape:
    def GetPoints(self):
        pass
    def __init__(self, cTag = None):
        if cTag == None:
            cTag = NewTag()
        self.length = [2,1,1,2]
        self.GetPoints()
        self.points   = array(self.points, 'f')
        self.vertices = self.points
        self.tag = cTag
    def draw(self):
        v = Perimeter(self.vertices)
        v.append(v[0])
        v.append(v[1])
        canvas.create_line(v, fill = 'orange', tag = self.tag, width = 1)
    def drawOutline(self, x, y, n0, nC):
        cosTheta = cos(n0)
        sinTheta = sin(n0)
        r     = array([[cosTheta, -sinTheta],[sinTheta,cosTheta]], 'f')
        q     = linearTranslation(self.points[nC], self.points, r, [x, y])
        self.vertices = q
        self.draw()
    def drawFill(self):
        points = Perimeter(self.vertices) 
        canvas.create_polygon(points, fill = self.colour, tag = self.tag)
    def drawComplete(self):
        self.drawFill()
        self.redArc()
        self.blueArc()
    def alignWith(self, nodeobj, nCnr2):
        p1 = nodeobj.p1 
        p2 = nodeobj.p2 
        dx1 = p2[0] - p1[0]
        dy1 = p2[1] - p1[1]
        nTheta2 = atan2(dy1,dx1)
        q1 = self.vertices[nCnr2]
        q2 = self.vertices[(nCnr2 - 1)%4]
        dx2 = q2[0] - q1[0]
        dy2 = q2[1] - q1[1]
        nTheta1 = atan2(dy2,dx2)
        self.drawOutline(p1[0], p1[1], nTheta2 - nTheta1,nCnr2)

class kite(shape):
    def GetPoints(self, cColour = 'brown'):
       self.points  = [[0,0]
                      ,[nSelfX,nSelfY]
                      ,[0,nScale * nFib]
                      ,[-nSelfX,nSelfY]]
       self.colour = cColour
       self.angles = [72,72,144,72]
       self.type   = 'kite'
        # shape, corner
       self.viable = [[[dart,1],[kite, 0]]
                     ,[[dart,2],[kite, 3]]
                     ,[[dart,3],[kite, 2]]
                     ,[[dart,0],[kite, 1]]]
    def draw(self):
        pass
    def redArc(self):
        nR = nRatioBig
        p0 = self.vertices[0]
        p1 = Scalar(self.vertices[3][0],self.vertices[3][1], nR, p0[0],p0[1])
        p5 = Scalar(self.vertices[1][0],self.vertices[1][1], nR, p0[0],p0[1])
        p3 = MidArc(p1,p5,p0,nR)
        p2 = MidArc(p1,p3,p0,nR)
        p4 = MidArc(p3,p5,p0,nR)
        aR = Perimeter([p1,p2,p3,p4,p5])
        canvas.create_line(aR, fill = 'darkgrey', tag = self.tag, width = 1)        
    def blueArc(self):
        nR = 1 / (1 / nFib + 1) * nScale
        p0 = self.vertices[2]
        p1 = Scalar(self.vertices[3][0],self.vertices[3][1], nR, p0[0],p0[1])
        p9 = Scalar(self.vertices[1][0],self.vertices[1][1], nR, p0[0],p0[1])
        p5 = MidArc(p1,p9,p0,nR)
        p3 = MidArc(p1,p5,p0,nR)
        p7 = MidArc(p5,p9,p0,nR)
        p2 = MidArc(p1,p3,p0,nR)
        p4 = MidArc(p3,p5,p0,nR)
        p6 = MidArc(p5,p7,p0,nR)
        p8 = MidArc(p7,p9,p0,nR)
        aR = Perimeter([p1,p2,p3,p4,p5,p6,p7,p8,p9])
        canvas.create_line(aR, fill = 'cyan', tag = self.tag, width = 1)
    def subShapes(self):
        subs = []
        p0 = list(self.vertices[0])
        p1 = list(self.vertices[1])
        p2 = list(self.vertices[2])
        p3 = list(self.vertices[3])
        p4 = Scalar(p3[0],p3[1], nRatioSmall, p0[0],p0[1])
        p5 = Scalar(p1[0],p1[1], nRatioSmall, p0[0],p0[1])
        p6 = Scalar(p2[0],p2[1], nRatioBig  , p0[0],p0[1])
        subs.append(SubKiteRight(p3,p6,p2))
        subs.append(SubKiteLeft(p3,p6,p4))
        subs.append(SubKiteRight(p1,p6,p5))
        subs.append(SubKiteLeft(p1,p6,p2))
        subs.append(SubDartRight(p6,p0,p5))
        subs.append(SubDartLeft(p6,p0,p4))
        return subs
    
class dart(shape):
    def GetPoints(self, cColour = 'darkgreen'):
        self.points = [[0,0]
               ,[nSelfX,nSelfY]
               ,[0,nScale] 
               ,[-nSelfX,nSelfY]]
        self.angles = [72,36,216,36]
        self.type   = 'dart'
        self.viable = [[[dart, 0],[kite, 1]]
                     ,[[kite, 2]]
                     ,[[kite, 3]]
                     ,[[dart, 1],[kite, 0]]] 
        self.colour = cColour
    def redArc(self):
        nR = nRatioSmall
        p0 = self.vertices[0]
        p1 = Scalar(self.vertices[3][0],self.vertices[3][1], nR, p0[0],p0[1])
        p5 = Scalar(self.vertices[1][0],self.vertices[1][1], nR, p0[0],p0[1])
        p3 = MidArc(p1,p5,p0,nR)
        p2 = MidArc(p1,p3,p0,nR)
        p4 = MidArc(p3,p5,p0,nR)
        aR = Perimeter([p1,p2,p3,p4,p5])
        canvas.create_line(aR, fill = 'darkgrey', tag = self.tag, width = 1)        
    def blueArc(self):
        nR = 1 / nFib / (1 / nFib + 1) * nScale
        p0 = self.vertices[2]
        p1 = Scalar(self.vertices[3][0],self.vertices[3][1], nR, p0[0],p0[1])
        p9 = Scalar(self.vertices[1][0],self.vertices[1][1], nR, p0[0],p0[1])
        p5 = MidArc(p1,p9,p0,nR)
        p5[0] = 2 * p0[0] - p5[0] # great arc
        p5[1] = 2 * p0[1] - p5[1] # great arc
        p3 = MidArc(p1,p5,p0,nR)
        p7 = MidArc(p5,p9,p0,nR)
        p2 = MidArc(p1,p3,p0,nR)
        p4 = MidArc(p3,p5,p0,nR)
        p6 = MidArc(p5,p7,p0,nR)
        p8 = MidArc(p7,p9,p0,nR)
        aR = Perimeter([p1,p2,p3,p4,p5,p6,p7,p8,p9])
        canvas.create_line(aR, fill = 'cyan', tag = self.tag, width = 1)        
    def subShapes(self):
        subs = []
        p0 = list(self.vertices[0])
        p1 = list(self.vertices[1])
        p2 = list(self.vertices[2])
        p3 = list(self.vertices[3])
        p4 = Scalar(p3[0],p3[1], nRatioBig, p0[0],p0[1])
        p5 = Scalar(p1[0],p1[1], nRatioBig, p0[0],p0[1])
        subs.append(SubKiteRight(p0,p2,p4))
        subs.append(SubKiteLeft(p0,p2,p5))
        subs.append(SubDartRight(p2,p3,p4))
        subs.append(SubDartLeft(p2,p1,p5))
        return subs

def AlterBorder(aBorder, temp, nNook, nAligned, nDel, nIns):
    cnr1 = nNook
    cnr2 = nAligned
    if nDel < 3:
        # replacement
        ang1 = aBorder[cnr1].angle    
        aBorder[cnr1]= NodeObject(temp, cnr2)
        aBorder[cnr1].angle = ang1
        aBorder[cnr1].prioritise()
    if cnr1 == len(aBorder) - 1:
        lClocked = True
    else:
        lClocked = False
    # deletion
    cnr3 =(cnr1 + 1) % len(aBorder)
    nAdjust = 1
    for z in range(nDel):
        if cnr3 < len(aBorder) - 1:
           aBorder = aBorder[:cnr3] + aBorder[cnr3 + 1:]
        elif cnr3 == len(aBorder): # delete first element
           aBorder = aBorder[1:]  
        else: # around the clock
           aBorder = aBorder[:cnr3]
    # insertion
    for nD in range(nIns):
        cnr4 = (cnr1 + nD + nAdjust) % len(aBorder)
        if lClocked:
            cnr4 = nD
        node = NodeObject(temp, (cnr2 + nD + 1) % 4)
        aBorder.insert(cnr4, node)
    return aBorder    

def FitsBorder(aBorder, nNook, aV, temp):
    nAligned = aV[1]
    nL = len(aBorder)
    for nBack in range(4):
        btest = aBorder[(nNook - nBack) % nL]
        angle1 = temp.angles[(nAligned + nBack) % 4]
        t = btest.angle - angle1
        if t < -nSmall: # conflict
            return False
        elif t > nSmall: # still room
            break
        # tight angle fit, test lengths
        nTestBorder = (nNook - nBack - 1) % nL
        nTestShape  = (nAligned + nBack) % 4
        btest       = aBorder[nTestBorder]
        if btest.length <> temp.length[nTestShape]: # length mismatch
            return False
    for nForward in range(4):
        btest = aBorder[(nNook + nForward + 1) % nL]
        angle1 = temp.angles[(nAligned - nForward - 1) % 4]
        t = btest.angle - angle1
        if t < -nSmall: # conflict
            return False
        elif t > nSmall: # still room
            break
        # tight angle fit, test lengths
        nTestBorder = (nNook + nForward + 1) % nL
        nTestShape  = (nAligned - nForward - 2) % 4
        btest       = aBorder[nTestBorder]
        if btest.length <> temp.length[nTestShape]: # length mismatch
            return False
    aBorder[nNook].nBack    = nBack
    aBorder[nNook].nForward = nForward
    return True



def addToBorder(aBorder, nNook, node, aV, AddTile):
    nAligned = aV[1]
    nL = len(aBorder)
    AddTile.alignWith(node, nAligned)
    nBack    = aBorder[ nNook].nBack
    nForward = aBorder[ nNook].nForward
    del aBorder[ nNook].nBack
    del aBorder[ nNook].nForward
    nTest    = (nNook - nBack) % nL
    btest    = aBorder[ nTest]
    nAlign   = (nAligned + nBack) % 4
    angle1   = AddTile.angles[nAlign]
    btest.angle -= angle1
    btest.prioritise() 
    btest       = aBorder[(nNook + nForward + 1) % nL]
    angle1      = AddTile.angles[(nAligned - nForward - 1) % 4]
    btest.angle -= angle1
    btest.prioritise()
    nDel = min(nForward + nBack, 3)
    nIns = max(2 - nDel, 0)
    aBorder = AlterBorder(aBorder, AddTile, nTest, nAlign, nDel, nIns)
    return aBorder


class NodeObject:
    def __init__(self, shape, edge):
        self.angle  = 360 - shape.angles[edge]
        self.length = shape.length[edge]
        self.p1     = shape.vertices[edge]
        self.p2     = shape.vertices[(edge + 1) % 4]
        self.edge   = edge
        self.x      = shape.vertices[edge][0]
        self.y      = shape.vertices[edge][1]
        self.dist   = sqrt((nW2 - self.x)**2 + (nH2 -self.y)**2)
        self.viable = shape.viable[edge]
        self.prioritise()
        self.shape = shape
    def prioritise(self):
        self.priority = self.angle + self.dist / nW 

def PauseMessage(cText):
    global lFinished
    lFinished = True
    canvas.create_text(nW/2,20,text = cText,fill = 'white', tag = 'pause')
    raw_input()
    canvas.delete('pause')    
               
def FillPlane(aBorder, level):
    # a small delay allows the screen to show
    print level, ' of ', nRecLim # when level gets too high the stack will overload
    if level >= nRecLim - 50:
        print 'The stack has maxed out!'
        PauseMessage('The initial pattern is complete, press ENTER to advance.')
        return {}
    aBorderCopy = deepcopy(aBorder)
    nMin = 10000
    k    = 'all filled'
    j    = k
    for i in aBorderCopy:
        if i.x <  nW * 0.05 or i.x > nW * 0.95: # dont go off the screen
            continue
        elif  i.y <  nH * 0.1 or i.y > nH * 0.9:
            continue
        elif i.priority < nMin:
            j = i
            nMin = i.priority
    aAdded = []
    # by choosing the most sensible place to add to
    # there is not such a need for conflict testing.
    if  j == k: # no more space to fill
        print 'complete'
        PauseMessage('The initial pattern is complete, press ENTER to advance.')
        return {}
    b = j
    i = aBorderCopy.index(b)
    viable = b.viable
    shuffle(viable)
    while len(viable) > 0:
        v = viable[0]
        viable = viable[1:]
        attempt = v[0]()
        if FitsBorder(aBorderCopy, i, v, attempt):
            aAdded.append(attempt.tag)
            aBorderCopy = addToBorder(aBorderCopy, i, b, v, attempt)
            oShapesDict = FillPlane(aBorderCopy, level + 1)
            for idtag in aAdded:
                canvas.delete(idtag)
            if lFinished:
                for n in aBorder:
                    oShapesDict[n.shape.tag] = n.shape
                return oShapesDict
            # it might be more efficient to do some sort of clean up
            # but this is eaisier
            aBorderCopy = deepcopy(aBorder)

class SubShape:
    def draw(self):    
        points = Perimeter(self.vertices) 
        canvas.create_polygon(points, fill = self.colour, tag = cDefTag)

class SubKiteRight(SubShape):
    def __init__(self,p0,p1,p2):
        self.vertices = deepcopy([p0,p1,p2])
        self.colour = 'beige'
    def subShapes(self):
        subs = []
        p0 = self.vertices[0]
        p1 = self.vertices[1]
        p2 = self.vertices[2]
        p3 = Scalar(p2[0],p2[1], nRatioSmall, p0[0],p0[1])
        p4 = Scalar(p1[0],p1[1], nRatioBig  , p0[0],p0[1])
        subs.append(SubKiteRight(p2,p4,p1))
        subs.append(SubKiteLeft(p2,p4,p3))
        subs.append(SubDartLeft(p4,p0,p3))
        return subs
        
class SubKiteLeft(SubShape):
    global lAlternate
    def __init__(self,p0,p1,p2):
        self.vertices = deepcopy([p0,p1,p2])
        self.colour = 'tan'            

    def subShapes(self):        
        subs = []
        p0 = self.vertices[0]
        p1 = self.vertices[1]
        p2 = self.vertices[2]
        p3 = Scalar(p2[0],p2[1], nRatioSmall, p0[0],p0[1])
        p4 = Scalar(p1[0],p1[1], nRatioBig  , p0[0],p0[1])
        subs.append(SubKiteRight(p2,p4,p3))
        subs.append(SubKiteLeft(p2,p4,p1))
        subs.append(SubDartRight(p4,p0,p3))
        return subs

class SubDartRight(SubShape):
    def __init__(self,p0,p1,p2):
        self.vertices = deepcopy([p0,p1,p2])
        self.colour = 'darkgrey'            
        
    def subShapes(self):
        subs = []
        p0 = self.vertices[0]
        p1 = self.vertices[1]
        p2 = self.vertices[2]
        p3 = Scalar(p1[0],p1[1], nRatioSmall, p0[0],p0[1])
        subs.append(SubKiteRight(p1,p2,p3))
        subs.append(SubDartRight(p2,p0,p3))
        return subs
class SubDartLeft(SubShape):        
    def __init__(self,p0,p1,p2):
        self.vertices = deepcopy([p0,p1,p2])
        self.colour = 'grey'
        
    def subShapes(self):
        subs = []
        p0 = self.vertices[0]
        p1 = self.vertices[1]
        p2 = self.vertices[2]
        p3 = Scalar(p1[0],p1[1], nRatioSmall, p0[0],p0[1])
        subs.append(SubKiteLeft(p1,p2,p3))
        subs.append(SubDartLeft(p2,p0,p3))
        return subs

seed()
aBorder = []
lFinished = False
if random() > 0.5:
   temp = kite('first')
else:
   temp = dart('first')
temp.drawOutline(nW2, nH2, 0, 0)
for i in range(4):
    aBorder.append(NodeObject(temp, i))
oShapesDict = FillPlane(aBorder, 1)
canvas.delete('first')
cDefTag = NewTag()
aSubShapes  = []
for s in oShapesDict:
    print '#'
    oShape = oShapesDict[s]
    oShape.drawComplete()
    aSubShapes += oShape.subShapes()

while True:
    nRatioSmall *= nFib / (nFib + 1)
    nRatioBig   *= nFib / (nFib + 1)
    PauseMessage('press ENTER again to "DEFLATE" the pattern.')
    cLastTag = cDefTag
    cDefTag  = NewTag()
    aNewSubs = []
    for s in aSubShapes:
        s.draw()
        print '#'
        t = s.subShapes()
        aNewSubs += t
    canvas.delete(cLastTag)        
    lAlternate = True    
    aSubShapes = deepcopy(aNewSubs)

2 comments

Denis Barmenkov 11 years, 2 months ago  # | flag

You forgot link to Penrose tiles description: http://en.wikipedia.org/wiki/Penrose_tiles

FB36 11 years, 1 month ago  # | flag

There is a much simpler and general method to draw Penrose tilings by using L-System fractal definitions. You can download an old program called Fractint, select L-System, and load Penrose.l file which includes many Penrose tilings.

But still this is really good work!