В моем генераторе поиска слов используется только 1 слово из массива - PullRequest
0 голосов
/ 15 марта 2020

Я увидел учебник по поиску слов на youtube, который делал поиск слов в консоли python, и я попытался перенести это в tkinter. У меня это работает ... вроде. Проблема в том, что в графическом интерфейсе / программе используется только 1 слово из возможных 5. Это не проблема в консольной версии, поэтому я свяжу обе версии кода. Заранее благодарен за любую помощь!

Мой код:

import tkinter as tk
import random
import string

handle = open('dictionary.txt')
words = handle.readlines()
handle.close()

grid_size = 10

words = [ random.choice(words).upper().strip() \
            for _ in range(5) ]

print ("The words are:")
print(words)

grid = [ [ '_' for _ in range(grid_size) ] for _ in range(grid_size) ]

orientations = [ 'leftright', 'updown', 'diagonalup', 'diagonaldown' ]

class Label(tk.Label):
    def __init__(self, parent, **kwargs):
        super().__init__(parent, **kwargs, font=("Courier", 44))
        self.bind('<Button-1>', self.on_click)

class App(tk.Tk):
    def __init__(self):
        super().__init__()

        for row in range(grid_size):
            for column in range(grid_size):
                for word in words:
                    word_length = len(word)
                    placed = False
                while not placed:
                    orientation = random.choice(orientations)

                    if orientation == 'leftright':
                        step_x = 1
                        step_y = 0
                    if orientation == 'updown':
                        step_x = 0
                        step_y = 1
                    if orientation == 'diagonalup':
                        step_x = 1
                        step_y = -1
                    if orientation == 'diagonaldown':
                        step_x = 1
                        step_y = 1

                    x_position = random.randrange(grid_size)
                    y_position = random.randrange(grid_size)

                    ending_x = x_position + word_length*step_x
                    ending_y = y_position + word_length*step_y

                    if ending_x < 0 or ending_x >= grid_size: continue
                    if ending_y < 0 or ending_y >= grid_size: continue

                    failed = False


                    for i in range(word_length):
                        character = word[i]

                        new_position_x = x_position + i*step_x
                        new_position_y = y_position + i*step_y

                        character_at_new_position = grid[new_position_x][new_position_y]
                        if character_at_new_position != '_':
                            if character_at_new_position == character:
                                continue
                            else:
                                failed = True
                                break

                    if failed:
                        continue
                    else:
                        for i in range(word_length):
                            character = word[i]

                            new_position_x = x_position + i*step_x
                            new_position_y = y_position + i*step_y

                            grid[new_position_x][new_position_y] = character
                            if ( grid[row][column] == grid[new_position_x][new_position_y] ):
                                grid[row][column] = grid[new_position_x][new_position_y]
                                Label(self, text=character).grid(row=row, column=column)
                        placed = True
                if ( grid[row][column] == '_' ):
                    txt = random.SystemRandom().choice(string.ascii_uppercase)
                    Label(self, text=txt).grid(row=row, column=column)
if __name__ == '__main__':
    App().mainloop()

Оригинальный код консольной версии:

import random
import string

from pprint import pprint

def mainfunc():

    handle = open('dictionary.txt')
    words = handle.readlines()
    handle.close()

    words = [ random.choice(words).upper().strip() \
              for _ in range(5) ]

    grid_size = 20

    grid = [ [ '_' for _ in range(grid_size) ] for _ in range(grid_size) ]

    def print_grid():
        for x in range(grid_size):
            print ('\t' *3 + ' '.join( grid[x] ))

    orientations = [ 'leftright', 'updown', 'diagonalup', 'diagonaldown' ]

    for word in words:
        word_length = len(word)

        placed = False
        while not placed:
            orientation = random.choice(orientations)

            if orientation == 'leftright':
                step_x = 1
                step_y = 0
            if orientation == 'updown':
                step_x = 0
                step_y = 1
            if orientation == 'diagonalup':
                step_x = 1
                step_y = -1
            if orientation == 'diagonaldown':
                step_x = 1
                step_y = 1

            x_position = random.randrange(grid_size)
            y_position = random.randrange(grid_size)

            ending_x = x_position + word_length*step_x
            ending_y = y_position + word_length*step_y

            if ending_x < 0 or ending_x >= grid_size: continue
            if ending_y < 0 or ending_y >= grid_size: continue

            failed = False


            for i in range(word_length):
                character = word[i]

                new_position_x = x_position + i*step_x
                new_position_y = y_position + i*step_y

                character_at_new_position = grid[new_position_x][new_position_y]
                if character_at_new_position != '_':
                    if character_at_new_position == character:
                        continue
                    else:
                        failed = True
                        break

            if failed:
                continue
            else:
                for i in range(word_length):
                    character = word[i]

                    new_position_x = x_position + i*step_x
                    new_position_y = y_position + i*step_y

                    grid[new_position_x][new_position_y] = character

                placed = True

    for x in range(grid_size):
        for y in range(grid_size):
            if ( grid[x][y] == '_' ):
                grid[x][y] = random.SystemRandom().choice(string.ascii_uppercase)

    print_grid()

    print ("The words are:")
    pprint(words)

mainfunc()

Список слов для 'dictionary.txt': здесь

1 Ответ

0 голосов
/ 16 марта 2020

У вас есть небольшая проблема с отступом.

for word in words:
    word_length = len(word)
    placed = False
while not placed:
    <rest of the code>
    ....

Для l oop циклически повторяется каждое слово для ВСЕГО СПИСКА. Когда это сделано, word было назначено последнее слово в списке. Затем он продолжает код, используя только последнее слово в вашем списке.

Просто сделайте отступ в блоке кода, начинающемся с while not placed.

for word in words:
    word_length = len(word)
    placed = False
    while not placed:
        <rest of the code>
        ....

Если вы сравниваете его с консольной версией , вы можете видеть, что l oop правильно имеет отступ внутри для l oop, поэтому это работает правильно.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...