簡體   English   中英

Python wordsearch 生成器重疊單詞

[英]Python wordsearch generator overlaps words

所以我一直在嘗試制作一個單詞搜索網格生成器,但是這段代碼有一個問題,我不知道如何解決。 此代碼生成單詞搜索網格並將列表中的單詞放入其中,但有時該單詞的某些字符會被另一個單詞覆蓋(因為位置分配是隨機的,並且不考慮先前生成的索引)。 我想解決這個問題,但我不知道如何...

import string
import random

height = 15
width = 15
def wordsearch(word,grid):
    word = random.choice([word])
    wordlength = len(word)

    direction = random.choice([[1,0],[0,1],[1,1]])
    xsize = width   if direction[0] == 0 else width  - wordlength
    ysize = height if direction[1] == 0 else height - wordlength

    x = random.randrange(0,xsize)
    y = random.randrange(0,ysize)

    print([x,y])

    for i in range(0,wordlength):
        grid[y + direction[1]*i][x + direction[0]*i] = word[i]
    return grid

grid = [[random.choice(string.ascii_lowercase) for i in range(0,width)] for j in range(0,height)]

for word in ['hello','red','yellow','green','blue','father','mother','sister','brother','food','drinks', 'cheese']:
    grid = wordsearch(word, grid)

print("\n".join(map(lambda row: " ".join(row), grid)))

例如,在 [1,0] 處,它向下生成“綠色”,但第一個“e”被在 [1,2] 處生成的單詞“藍色”替換。

[6, 1]
[12, 7]
[2, 4]
[1, 0]
[1, 2]
[7, 2]
[7, 4]
[11, 6]
[3, 9]
[7, 10]
[5, 0]
[6, 0]
t g n v x d c f y r s m d z o
t r f v j h r h l l o r e v e
y b y v w t w i e y v f r r m
z e l b w c e a n e y z c w j
a n y u l l o m z k s h u z d
u s i c e i z h o a s e c j r
l c g n v y k e c t b s g q g
e f b c p s f r x e h i r t f
y q p r t h h a z e o s e z h
o l x b r o t h e r e t r z x
m f m m n u o f j d s e i e e
v z u d k x t k o v i r d o k
l s q o q w a l o o u n y y v
m q c u r v w i f d d d a p g
b a h c f o y g g n x e v z s

您應該檢查您隨機選擇的單詞位置是否與已選擇的任何位置“碰撞”(重疊)。 如果是,則丟棄該位置並生成一個新位置。

對於示例實現,我用元組表示單詞放置: (start_row, start_col, direction, length) ,然后可以像這樣檢查碰撞:

(這可能是一個非常低效的實現,但應該是直觀的;此外,對於小矩陣(<1000 行),它應該可以正常工作):

def get_points(word_placement):
    start_row, start_col, direction, length = word_placement 
    if direction == 'vertical': # column remains same
        return [(start_row+i, start_col) for i in range(length)]

    elif direction == 'horizontal': # row stays  same
        return [(start_row, start_col+i) for i in range(length)]

    elif direction == 'diagonal':
        return [(start_row+i, start_col+i) for i in range(length)]


def do_they_collide (wa, wb):
    points_a = get_points(wa)
    points_b = get_points(wb)
    if len(set(points_a).intersection(set(points_b))) > 0:
        return True
    else:
        return False

## Let's take an example
wa = (0, 1, 'vertical', 5)   # green
wb = (3, 0, 'horizontal', 4) # blue

do_they_collide(wa, wb)

暫無
暫無

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

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