Skip to content

Instantly share code, notes, and snippets.

@NightSling
Last active April 17, 2025 04:04
Show Gist options
  • Save NightSling/3d377bf204aba866bebee6a306de280b to your computer and use it in GitHub Desktop.
Save NightSling/3d377bf204aba866bebee6a306de280b to your computer and use it in GitHub Desktop.
Grid Generation POC for a grid word finding game.
import copy
import random
import string
def create_grid(size):
return [[" " for _ in range(size)] for _ in range(size)]
def print_grid(grid):
for row in grid:
print(" ".join(row))
def word_fits(grid, word, row, col, d_row, d_col):
size = len(grid)
if row + d_row * (len(word) - 1) < 0 or row + d_row * (len(word) - 1) >= size:
return False
if col + d_col * (len(word) - 1) < 0 or col + d_col * (len(word) - 1) >= size:
return False
for i in range(len(word)):
if grid[row + i * d_row][col + i * d_col] not in (" ", word[i]):
return False
return True
def place_word(grid, word):
size = len(grid)
directions = [
(0, 1),
(1, 0),
(1, 1),
(-1, 1),
] # horizontal, vertical, diagonal down, diagonal up
attempts = 0
while attempts < 100:
d_row, d_col = random.choice(directions)
row = random.randint(0, size - 1)
col = random.randint(0, size - 1)
if word_fits(grid, word, row, col, d_row, d_col):
for i, letter in enumerate(word):
grid[row + i * d_row][col + i * d_col] = letter
return True
attempts += 1
return False
def fill_empty_spaces(soln):
grid = copy.deepcopy(soln)
for i in range(len(grid)):
for j in range(len(grid)):
if grid[i][j] == " ":
grid[i][j] = random.choice(string.ascii_uppercase)
print(soln)
return grid
def calculate_min_grid_size(words):
return max(len(max(words, key=len)), int(len("".join(words)) ** 0.5))
def create_word_search(words, size):
solution = create_grid(size)
for word in words:
word = word.upper()
if not place_word(solution, word):
print(f"Couldn't place word: {word}")
else:
place_word(solution, word)
grid = fill_empty_spaces(solution)
return grid, solution
def main():
print("Welcome to the Word Search Generator!")
words_input = input("Enter words separated by commas: ")
words = [word.strip() for word in words_input.split(",")]
min_size = calculate_min_grid_size(words)
print(f"\nMinimum grid size needed: {min_size}x{min_size}")
size_input = input(
f"Enter desired grid size (press Enter for minimum size {min_size}, or enter a larger number): "
)
size = max(min_size, int(size_input)) if size_input.strip() else min_size
puzzle, solution = create_word_search(words, size)
print(f"\nHere's your {size}x{size} word search puzzle:")
print_grid(puzzle)
print("\nWords to find:", ", ".join(words))
print("\nHere's the solution:")
print_grid(solution)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment