Word search puzzle generator in Python

167 Views Asked by At

I am creating a word search puzzle generator, but I am a beginner in programming, so I´m having some trouble, like some words overlap, and I don't really know where is the problem. So i need a program that asks for the rows and columns, with that information it creates the grid and organize the word(key) given in the grid, in a vertical or horizontal direction. In addition, i need to make the grid of max 25x25. Any help would be apreciated.(also I'm not a native English speaker)

import string 
import random 

col = int(input("Indique cuantas columnas desea para la sopa de letras: "))#here I ask for the columns (aka width)
fil = int(input("Indique cuantas filas desea para la sopa de letras: "))#here is the rows (aka height )


def posicionPalabra(palabra,cuadricula, fil, col):
    palabra = random.choice([palabra, palabra[::-1]])

    direccion = random.choice([[1,0], [0,1]])
    print(f'La posicion de {palabra} en el orden {direccion}...')
    xComienzo = col if direccion[0] == 0 else col - len(palabra) - 1
    yComienzo = fil if direccion[1] == 0 else fil - len(palabra) - 1

    x = random.randrange(0, xComienzo)
    y = random.randrange(0, yComienzo)

    print([x, y])

    for i in range(len(palabra)):
        cuadricula[x + direccion[0]*i][y + direccion[1]*i] = palabra[i]
    return cuadricula

cuadricula = [[random.choice(string.ascii_uppercase) for a in range(col)] for h in range(fil)]

for palabra in ["Alemania","Belice","Cuba","Finlandia","Guatemala","Mexico"]:
    posicionPalabra(palabra,cuadricula,25,25)
    
print ("\n".join(map(lambda row: " ".join(row), cuadricula)))

I have tried with other grid sizes but it gives me this:

Indique cuantas columnas desea para la sopa de letras: 15
Indique cuantas filas desea para la sopa de letras: 18
La posicion de Alemania en el orden [1, 0]...
[3, 17]
Traceback (most recent call last):
  File "C:/Users/VictoriaBC/Desktop/de py/sopapaises.py", line 28, in <module>
    posicionPalabra(palabra,cuadricula,25,25)
  File "C:/Users/VictoriaBC/Desktop/de py/sopapaises.py", line 22, in posicionPalabra
    cuadricula[x + direccion[0]*i][y + direccion[1]*i] = palabra[i]
IndexError: list assignment index out of range

*I also need to ask the player for the words to find, but that is already done

1

There are 1 best solutions below

2
On

you try to get this [x + direccion[0]*i][y + direccion[1]*i] from this cuadricula 2D list,
but you cannot do this because in cuadricula there is not such indices
that are given by [x + direccion[0]*i][y + direccion[1]*i]
on some lvl of iteration of for i in range(len(palabra)):