please help with converting python code to gdscript, thanks.
import os
import sys
import random
def make_wordsearch(nrows, ncols, wordlist, allow_backwards_words=True):
grid = [['']*ncols for _ in range(nrows)]
def fill_empty_cells(grid):
for irow in range(nrows):
for icol in range(ncols):
if grid[irow][icol] == '':
grid[irow][icol] = random.choice(alphabet)
def is_word_fits(irow, icol, dx, dy, word):
for j in range(len(word)):
if grid[irow][icol] not in ('', word[j]):
return False
irow += dy
icol += dx
return True
def place_word(word):
dxdy_choices = [(0,1), (1,0), (1,1), (1,-1)] # Left, down, and the diagonals.
random.shuffle(dxdy_choices)
for (dx, dy) in dxdy_choices:
if allow_backwards_words and random.choice([True, False]):
word = word[::-1] # If backwards words are allowed, simply reverse word.
# Work out the minimum and maximum column and row indexes, given the word length.
n = len(word)
colmin = 0
colmax = ncols - n if dx else ncols - 1
rowmin = 0 if dy >= 0 else n - 1
rowmax = nrows - n if dy >= 0 else nrows - 1
if colmax - colmin < 0 or rowmax - rowmin < 0:
continue # No possible place for the word in this orientation.
# Build a list of candidate locations for the word.
candidates = []
for irow in range(rowmin, rowmax+1):
for icol in range(colmin, colmax+1):
if is_word_fits(irow, icol, dx, dy, word):
candidates.append((irow, icol))
# If we don't have any candidates, try the next orientation.
if not candidates:
continue
# Pick a random candidate location and place the word in this orientation.
loc = irow, icol = random.choice(candidates)
for j in range(n):
grid[irow][icol] = word[j]
irow += dy
icol += dx
break # We're done: no need to try any more orientations.
else:
return False # If we're here, it's because we tried all orientations but couldn't find anywhere to place the word. Oh dear.
return True
# Iterate over the word list and try to place each word (without spaces).
for word in wordlist:
word = word.replace(' ', '')
if not place_word(word):
return None # We failed to place word, so bail.
fill_empty_cells(grid)
return grid
def show_grid_text(grid):
"""Output a text version of the filled grid wordsearch."""
for irow in range(nrows):
print(' '.join(grid[irow]))
if __name__ == "__main__":
NATTEMPTS = 100
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
nrows, ncols = 7, 7
wordlist = sorted(["uranus","venus","earth","mars","mercury","jupiter","neptune","saturn"], key=lambda w: len(w), reverse=True)
for i in range(NATTEMPTS):
grid = make_wordsearch(nrows, ncols, wordlist)
if grid:
print('fitted after {} attempt(s)'.format(i + 1))
show_grid_text(grid)
break