
# truchet.py
# Andrew Davison, ad@coe.psu.ac.th, April 2025
# https://en.wikipedia.org/wiki/Truchet_tiles
'''
  Display a 12x12 grid of randomly rotated Truchet
  tiles. The basic image can be a triangle (tri.png)
  or two quarter-circles (arc.png).

  The grid is created using a 12x12 grid of Matplotlib
  subplots, but it could be a single plot with the images
  positioned through translation.

'''

import random
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from matplotlib.transforms import Affine2D

numCols = 12
numRows = 12
dpi = 100

im = mpimg.imread('arc.png')   # tri.png or arc.png
height, width = im.shape[0], im.shape[1]

# Create a grid of subplots, one for each image
figWidth = (numCols * width) / dpi
figHeight = (numRows * height) / dpi
fig, axes = plt.subplots(numRows, numCols, 
           figsize=(figWidth, figHeight), dpi=dpi)

angles = [0, 90, 180, 270]  # possible rotations, chosen randomly

# Plot multiple randomly rotated image copies
for i in range(numRows * numCols):
  ax = axes[i//numCols][i % numCols]   # row, col
  ang = random.choice(angles)
  trans = Affine2D().translate(-width/2, -height/2). \
              rotate_deg(ang).translate(width/2, height/2)
  show = ax.imshow(im.copy())
  show.set_transform(trans + ax.transData)
  ax.axis('off')   # turn off axes on all subplots

# no space between subplots, so none between images
plt.subplots_adjust(wspace=0, hspace=0, 
                  left=0, right=1, top=1, bottom=0)
plt.show()
