Last active
December 8, 2022 21:15
-
-
Save ryandhubbard/736307a85fe434dae84733d668a5307f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from PIL import Image, ImageDraw, ImageFont | |
import random | |
def create_puzzle(): | |
base = 3 | |
side = base*base | |
# pattern for a baseline valid solution | |
def pattern(r,c): return (base*(r%base)+r//base+c)%side | |
# randomize rows, columns and numbers (of valid base pattern) | |
from random import sample | |
def shuffle(s): return sample(s,len(s)) | |
rBase = range(base) | |
rows = [ g*base + r for g in shuffle(rBase) for r in shuffle(rBase) ] | |
cols = [ g*base + c for g in shuffle(rBase) for c in shuffle(rBase) ] | |
nums = shuffle(range(1,base*base+1)) | |
# produce board using randomized baseline pattern | |
board = [ [nums[pattern(r,c)] for c in cols] for r in rows ] | |
# print(board) | |
# Remove some of the numbers to create the puzzle | |
for i in range(9): | |
for j in range(9): | |
if random.random() < 0.5: | |
board[i][j] = 0 | |
return board | |
def draw(puzzle): | |
# Create a new image with a white background | |
img = Image.new('RGB', (360, 360), color=(255, 255, 255)) | |
# Load a font | |
font = ImageFont.truetype('arial.ttf', 36) | |
# Get a drawing context | |
draw = ImageDraw.Draw(img) | |
# Draw the grid lines | |
for i in range(10): | |
# Vertical lines | |
x = 40 * i | |
y1 = 0 | |
y2 = 400 | |
if(i%3==0): | |
draw.line((x, y1, x, y2), fill=(0, 0, 0), width=6) | |
else: | |
draw.line((x, y1, x, y2), fill=(0, 0, 0), width=2) | |
# Horizontal lines | |
x1 = 0 | |
x2 = 400 | |
y = 40 * i | |
if(i%3==0): | |
draw.line((x1, y, x2, y), fill=(0, 0, 0), width=6) | |
else: | |
draw.line((x1, y, x2, y), fill=(0, 0, 0), width=2) | |
# Draw the numbers | |
for i in range(9): | |
for j in range(9): | |
# Get the center position of the cell | |
x = 41 * j + 5 | |
y = 40 * i + 5 | |
# Get the number to draw | |
n = puzzle[i][j] | |
# Draw the number | |
if n != 0: | |
draw.text((x, y), str(n), font=font, fill=(0, 0, 0)) | |
return img | |
# Declare how many puzzle you want to create | |
for i in range(4): | |
# Generate a random puzzle | |
puzzle = create_puzzle() | |
# Draw the puzzle | |
img = draw(puzzle) | |
# # Save the image to a file | |
img.save('sudoku_{}.png'.format(i)) |
Author
ryandhubbard
commented
Dec 8, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment