from random import randint from PIL import Image, ImageDraw def width_at_height(width,height,i): return(width+2*height-2*(i+1)) def F(x,y,z): return((not y and z) or (y and not (x and z))) def rule110(width,height,initial=None): grid=[] for i in range(height): grid.append([False]*width_at_height(width,height,i)) if(initial!=None): if(len(initial)==width_at_height(width,height,0)): grid[0]=initial else: raise f"{initial} should have length {width_at_height(width,height,0)}" else: for j in range(width_at_height(width,height,0)): grid[0][j] = randint(0,1)==1 for i in range(1, height): for j in range(width_at_height(width,height,i)): grid[i][j] = F(grid[i-1][j],grid[i-1][j+1],grid[i-1][j+2]) return(grid) def draw_cells(grid,image_size, cell_size, true_color, false_color,output_file): """ Draws a grid on an image and saves it to a file. :param image_size: Tuple (width, height) of the image :param cell_size: Size of each grid cell (square cells) :param line_color: Color of the grid lines (e.g., 'black', (255, 0, 0)) :param output_file: Path to save the output image """ # Create a blank white image img = Image.new("RGB", (image_size[0]*cell_size,image_size[1]*cell_size), "white") draw = ImageDraw.Draw(img) width, height = image_size # Draw vertical lines for i in range(height): for j in range(width): fill = None if(grid[i][j+height-1-i]): fill = true_color else: fill = false_color draw.rectangle([j*cell_size,i*cell_size,(j+1)*cell_size-1,(i+1)*cell_size-1], fill=fill) # Draw horizontal lines #for y in range(0, height, cell_size): # draw.line([(0, y), (width, y)], fill=line_color) # Save the image img.save(output_file) print(f"Grid image saved to {output_file}") # Parameters width=2000 height=1000 cell_size = 1 # Cell size in pixels line_color = "black" # Line color for the grid true_color = "black" false_color ="white" output_file ="grid.png" # Output file name # Draw and save the grid #draw_grid(image_size, cell_size, line_color, output_file) initial = [False]*width_at_height(width,height,0) initial[width_at_height(width,height,0)-height]=True grid = rule110(width,height) draw_cells(grid,(width,height),cell_size,true_color,false_color,output_file)