0

我正在尝试构建自己的 Wordle 版本,但我被困在这里。这部分代码的意思是,当它与秘密单词的位置和字母匹配时,将相应的字符着色为绿色,当它与字母匹配时,将其着色为黄色,而不是位置。未包含在密语中的字符不着色。

from termcolor import colored
secret = "widow"

def color(word):
    if word[0] == secret[0]:
        word = word.replace(word[0], colored(word[0], 'green'))
    if word[0] == secret[1] or secret[2] or secret[3] or secret[4]:
        word = word.replace(word[0], colored(word[0], 'yellow'))
    if word[1] == secret[1]:
        word = word.replace(word[1], colored(word[1], 'green'))
    if word[1] == secret[0] or secret[2] or secret[3] or secret[4]:
        word = word.replace(word[1], colored(word[1], 'yellow'))
    if word[2] == secret[2]:
        word = word.replace(word[2], colored(word[2], 'green'))
    if word[2] == secret[1] or secret[0] or secret[3] or secret[4]:
        word = word.replace(word[2], colored(word[2], 'yellow'))
    if word[3] == secret[3]:
        word = word.replace(word[3], colored(word[3], 'green'))
    if word[3] == secret[1] or secret[2] or secret[0] or secret[4]:
        word = word.replace(word[3], colored(word[3], 'yellow'))
    if word[4] == secret[4]:
        word = word.replace(word[4], colored(word[4], 'green'))
    if word[4] == secret[1] or secret[2] or secret[3] or secret[0]:
        word = word.replace(word[4], colored(word[4], 'yellow'))
    return word

print(color("woiky"))

在这个例子中,我希望 "woiky" 以绿色 "w" 打印(因为 woiky 和 ​​widow 都以 "w" 开头)、黄色 "i" 和黄色 "o"(因为 "widow" 包含两者“i”和“o”,但不在这些位置),而是打印:[33m[[0m33m[33m[[0m[33m[[0m0m33m[33m[[0m33m[33m[[0m[33m[[0m0m[33m[[0m33m[33m[[0m[33m[[0m0m0m33m[33m[[0m33m [33m[[0m[33m[[0m0m33m[33m[[0m33m[33m[[0m[33m[[0m0m[33m[[0m33m[33m[[0m[33m[[0m0m0m0m[33m[[0m33m[33m[[0m [33m[[0m0m33m[33m[[0m33m[33m[[0m[33m[[0m0m[33m[[0m33m[33m[[0m[33m[[0m0m0m32mw[33m[[0m33m[33m[[0m[33m[[0m0m33m [33m[[0m33m[33m[[0m[33m[[0m0m[33m[[0m33m[33m[[0m[33m[[0m0m0m33m[33m[[0m33m[33m[[0m[33m[[0m0m33m[33m[[0m33m [33m[[0m[33m[[0m0m[33m[[0m33m[33m[[0m[33m[[0m0m0m0m[33m[[0m33m[33m[[0m[33m[[0m0m33m[33m[[0m33m[33m[[0m [33m[[0m0m[33m[[0m33m[33m[[0m[33m[[0m0m0m0moiky

所有的“[”字符都是黄色的。

4

1 回答 1

0

这应该以更聪明的方式做你想做的事。我不想下载termcolor,所以我提供了一个替代品。

#from termcolor import colored
secret = "widow"

def colored(a,b):
    return( f"<{b}>{a}</{b}>" )

def color(word):
    build = []
    for i,letter in enumerate(word):
        if letter == secret[i]:
            build.append( colored(letter, 'green'))
        elif letter in secret:
            build.append( colored(letter, 'yellow'))
        else:
            build.append( letter )
    return ''.join(build)

print(color("woiky"))
于 2022-02-28T01:10:44.333 回答