簡體   English   中英

While Not Loop 運行次數超出預期

[英]While Not Loop running more times than intended

我在嘗試制作單詞搜索拼圖生成器時遇到了問題,並且一整天都遇到了多個問題。 (感謝這個社區,我已經解決了大部分問題!)

我現在有另一個問題,我有一個循環,應該找到一個位置來放置一個單詞,放置它,然后移動到下一個單詞。 相反,它是找到單詞可能存在的所有可能位置,並將該單詞放入所有位置。 我只希望每個單詞出現一次。 我認為while not placedplaced = true的線條placed = true會處理這個問題,但它不起作用。

在此先感謝您的幫助,這是我的代碼:

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)

    #def on_click(self, event):
        #w = event.widget
        #row, column = w.grid_info().get('row'), w.grid_info().get('column')
        #print('coord:{}'.format((row, column)))
        #w.destroy()

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()

我可以向您保證,您對while循環的期望是正確的。

In [1]: placed = False                                                                                                                                                                                             

In [2]: i = 0                                                                                                                                                                                                      

In [3]: while not placed: 
   ...:     i += 1 
   ...:     print(i) 
   ...:     if i == 5: 
   ...:         placed = True 
   ...:                                                                                                                                                                                                            
1
2
3
4
5

鑒於此,我懷疑您的代碼總是命中continue ,這意味着它永遠不會命中語句placed = True ,因此是無限循環。 所以,我建議你檢查你的病情continue如預期。

希望這可以幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM