This is a wordhunt generator I'm building as an exercise. This function is supposed to place a new word on the matrix on a random position, without crossing the words that are already there.
So in this case the word "GAME" is supposed to be placed horizontally on the list, replacing the 'x' letters, without crossing any of the 'W' letters. Example:
Correct:
x G A M E x
x x W x x x
x x x W x x
x x x x W x
x x x x x W
x x x x x x
Incorrect
x x x x x x
x x W x x x
x x G W M E
x x x x W x
x x x x x W
x x x x x x
This is how I tried to buld the code:
from random import randint
word = 'GAME'
def place_word():
wordhunt = [['x', 'x', 'x', 'x', 'x', 'x'],
['x', 'x', 'W', 'x', 'x', 'x'],
['x', 'x', 'x', 'W', 'x', 'x'],
['x', 'x', 'x', 'x', 'W', 'x'],
['x', 'x', 'x', 'x', 'x', 'W'],
['x', 'x', 'x', 'x', 'x', 'x']]
#generate the initial position of the word on the matrix
line = randint(0, 5)
column = randint(0, 2)
#iterator to place the new letters
for i in range(0,4,1):
#Check if the position is allowed
if wordhunt[line][column+i] == 'x':
wordhunt[line][column+i] = word[i]
#if i reaches 3 the placement is complete
if i == 3:
return wordhunt
#if it tries to place a letter on a forbidden position, it runs the function again
else:
place_word()
new_wordhunt = place_word()
for i in range(0, 6, 1):
for j in range(0, 6, 1):
print(new_wordhunt[i][j], end=' ')
print()
In this case sometimes it generates expected results like the one bellow:
x x x x x x
x x W x x x
x x x W x x
x x x x W x
x x x x x W
G A M E x x
But sometimes it generates incorrect results like this one:
x x x x x x
x x W x x x
x G A W E x
x x x x W x
x x x x x W
x x x x x x
I've run a thousand testes but I just can't find out what is wrong with it.
Thank you for your help!