#! /usr/bin/env python """Generate a word grid""" import sys, re from random import randrange, seed, choice from string import ascii_uppercase def placeHor(word, x, y): """Attempt to place word horizontally at position x/y""" if x + len(word) >= width: return False for i in range(len(word)): check = grid[y][x + i] if check != " " and check != word[i]: return False for i in range(len(word)): grid[y][x + i] = word[i] return True def placeVert(word, x, y): """Attempt to place word vertically at position x/y""" if y + len(word) >= height: return False for i in range(len(word)): check = grid[y+i][x] if check != " " and check != word[i]: return False for i in range(len(word)): grid[y+i][x] = word[i] return True # Setup try: width = int(sys.argv[1]) height = int(sys.argv[2]) wordfile = sys.argv[3] seed() except ValueError: print(f"Could not parse {', '.join(sys.argv[1:3])} as integers") sys.exit(1) except IndexError: print(f"Usage: {sys.argv[0]} ") sys.exit(2) # Place a bunch of words on the grid grid = [list(" " * width) for _ in range(height)] try: with open(wordfile) as wordlist: lines = wordlist.read().splitlines() misses = 0 maxtries = 200 while misses < maxtries: word = choice(lines).strip().upper() if len(word) < 3 or not re.match("^[A-Z]*$", word): continue direction = choice([placeHor, placeVert]) if direction(word, randrange(0,width), randrange(0,height)): # Word successfully placed misses = 0 else: misses += 1 except FileNotFoundError: print(f"Could not open file {sys.argv[3]}") sys.exit(3) # Fill all empty cells with random letters for y in range(height): for x in range(width): if grid[y][x] == ' ': grid[y][x] = choice(ascii_uppercase) for line in grid: print("".join(line))