I am creating a word search generator in Python, but i'm having a problem with the words appearing the grid. When the grid is made, the coordinates are there for one of the letters but not the whole word. I'm not sure which parts going wrong, any help would be much appreciated
import string
import random
width = 10
height = 10
def place_words(words, grid):
words = random.choice([words, words[::-1]])
direction = random.choice([[1,0], [0,1], [1,1]])
xstart = width if direction[0] == 0 else width - len(words)
ystart = height if direction[1] == 0 else height - len(words)
x = random.randrange(0, xstart)
y = random.randrange(0, ystart)
print([x, y])
for i in range(0, len(words)):
grid[y + direction[1]*i][x + direction[0]*i] = words[i]
return grid
grid = [[random.choice(string.ascii_uppercase) for i in range(0, width)]
for j in range(0, height)]
for words in ["HELLO"]:
place_words(words, grid)
print("\n".join(map(lambda row: " ".join(row), grid)))
this is the outcome of it and as you can see the word isnt there!
[3, 0]
R J E O K S Y U Q F
T E P U N B Y Z I O
J A Y N F D S V T Y
H G A M R W O T I M
O W J Q R G Q E D Q
W D J R T N N N Q N
K Z B X H V U Y J X
J F P D W F I C W U
C Z V B Q C Z R K X
E J A K R N J V S Y
The only major change you need is the indentation on the
return; as you noted, your code did place the first letter, but none of the rest. This is because thereturnis inside yourforloop, so it returns on the 1st iteration (after placing the 1st letter).I suggest a bit of work to flesh the idea out, because two words can overlap on the same grid (e.g. in the example below, the
DinDOORreplaced theOinHELLO). Also, in the directions matrix as written, the top-left to bottom-right diagonal direction is possible, but the top-right to bottom-left diagonal is not. Perhaps the ideas help. Below is some tweaked code: