猜字游戏:尝试构建人工智能

2024-04-27 21:02:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创造一个小游戏。在

规则很简单:你给一个英语单词,计算机会逐字猜测这个单词。在

问题是,我想让电脑用一种聪明的方式来猜字母。让我给你举一个简单的例子来说明我正在尝试构建什么,这样你就可以理解:

  1. 你把“猫”这个词给电脑猜。

  2. 我的130K单词列表被缩小到只有3个字符的单词,最多只能有805个单词。从这个单词列表中,创建了一个字母表,它只包含25个字母(不是全部26个),因为新的805个单词列表包含了字母表中的所有字母,除了“z”。所以我们现在有一个包含25个(不同)字母的列表。

--因为我不能在这里上传任何东西,所以我们在这个例子中说,130K个单词的庞大列表是一个10个单词的列表(变量名为“fullDice”)--

If you try to run my code, pick a word from inside this list or else it's not going to work

  1. 计算机现在从这个25个字母的列表中随机猜测一个字母。

  2. 如果字母不在单词中,他什么也不做,从列表中重新猜出一个字母。

  3. 但如果字母在单词中,这就是事情变得更复杂的地方。假设计算机猜字母“c”。我希望计算机重新缩小可能的单词列表,只限于第一个字符中有“c”的单词。这样,805个单词的列表现在变成了只有36个单词的列表。因为只有36个单词是3个字符,以“c”开头,因此创建了一个新的字母表。新的字母表现在只由14个字母组成,这使得计算机更容易猜出下一个字母并对其进行正确的判断。直到他找到所有的信。

我被困在第五部分了。如果你试着在下面运行我的代码,你会发现单词表从来没有缩小过。这是我的问题。在

import time
from random import randint

fullDice = ["panda", "tiger", "cat", "elephant", "whale", "leopard", "gorilla", "fish", "snake", "eagle"]

askForWord = input("Please enter an english word:   ")

while True:

    updatedDice = []

    for k in range (0, len(fullDice)):
        if len(askForWord) == len(fullDice[k]):
            updatedDice += [fullDice[k]]

    alphabet = []

    for i in range (0, len(updatedDice)):
        for n in range (0, len(updatedDice[i])):
            if updatedDice[i][n] not in alphabet:
                alphabet += [updatedDice[i][n]]

    guessRandomLetter = alphabet[randint(0, len(alphabet) - 1)]

    print("I guess the letter:   " + guessRandomLetter)
    print("From this dice: " + str(len(updatedDice)))
    print("From this amount of letters: " + str(len(alphabet)) + "\n")

    time.sleep(0.75)

    guessedWordUnderlined = "_" * len(askForWord)

    if guessRandomLetter in askForWord:

        for m in range(0, len(askForWord)):
            if askForWord[m] == guessRandomLetter:  # CHECKING IF THE GUESSED LETTER IS INSIDE THE WORD
                guessedWordUnderlined = list(guessedWordUnderlined)
                guessedWordUnderlined[m] = guessRandomLetter

        guessedWordUnderlined = ''.join(map(str, guessedWordUnderlined))

        if guessedWordUnderlined == askForWord:  # CHECK IF USER HAS WON

            print("YOU WON")
            break

Tags: in列表forlenif计算机字母单词
3条回答

你刚刚问了一个包括代码的qs。 我试着让它只适用于你给出的单词表中可用的单词“python”。在

    from random import randint
    import random
    import time
    import datetime
    random.seed(datetime.datetime.now())

    wordOfTheUser = input("ENTER ENGLISH WORD HERE:  ")
    if wordOfTheUser in ("abracadabra", "python", "coding", "soup", "paper", "list", "leader", "program", "software", "eating","abcdefghigklmnopqrstuvwxyz"):
            pass
    else:
            print("your word is not on the list, still devlopping.")
            raise

    diceList1 = ["abracadabra", "python", "coding", "soup", "paper", "list", "leader", "program", "software", "eating","abcdefghigklmnopqrstuvwxyz"]

    diceList2 = []

    for k in range (0, len(diceList1) - 1):
        if len(diceList1[k]) == len(wordOfTheUser):
            diceList2 += [diceList1[k]]

    makeAlphabet = []

    for b in range (0, len(diceList2)):
        for x in range (0, len(diceList2[b])):
            if diceList2[b][x] not in makeAlphabet:
                makeAlphabet += [diceList2[b][x]]

    computerWordSize = "_" * int(len(wordOfTheUser))
    a= len(makeAlphabet)

    while True:

        try:
            randomIndex = randint(0, a)
        except ValueError:

            randomIndex = randint(0, a)
            pass

        try:
            letterChosenRandomly = makeAlphabet[randomIndex]

        except IndexError as e:
            try:
                randomIndex = randint(0, int(len(makeAlphabet)))
                letterChosenRandomly = makeAlphabet[randomIndex]
            except:
                pass

        print("I guess the letter -> " + letterChosenRandomly)

        diceList3 = []

        if letterChosenRandomly in wordOfTheUser:

            print("\n=== WON ===> " + letterChosenRandomly)
            print("=== ALPHABET ===> " + str(len(makeAlphabet)))
            print("=== HDW1 ===> " + str(len(diceList1)))
            print("=== hdw2 ===> " + str(len(diceList2)))
            print("=== hdw3 ===> " + str(len(diceList3)) + "\n\n")
            k=-1


            makeAlphabet = []


            for i in range (0, len(wordOfTheUser) ):
                if letterChosenRandomly == wordOfTheUser[i]:
                    computerWordSize = list(computerWordSize)
                    computerWordSize[i] = letterChosenRandomly

                    for l in range (0, len(diceList2)):
                        if computerWordSize[i] == diceList2[l][i]:
                            diceList3 += [diceList2[l]]

                    for d in range(0, len(diceList3)):
                        for h in range(0, len(diceList2[b])):
                            if diceList2[d][h] not in makeAlphabet:
                                makeAlphabet += [diceList2[d][h]]

            won = False

            computerWordSize = ''.join(map(str, computerWordSize))

            print(computerWordSize)

            if computerWordSize == wordOfTheUser:
                won = True

            if won is True:
                print("YOU WON")
                break

            time.sleep(1)

        else:

            print("\n=== LOOSE ===> " + letterChosenRandomly)
            print("=== ALPHABET ===> " + str(len(makeAlphabet)))
            print("=== HDW1 ===> " + str(len(diceList1)))
            print("== hdw2 ===> " + str(len(diceList2)))
            print("=== hdw3 ===> " + str(len(diceList3)) + "\n\n")
            try:
                makeAlphabet.remove(letterChosenRandomly)
            except:
                print ("Letters not in list")
                break
            k=0

            diceList3 = []

            for q in range (0, len(wordOfTheUser) - 1):
                for l in range(0, len(diceList2)):
                    if computerWordSize[q] == diceList2[l][q]:
                        diceList3 += [diceList2[l]]

            for d in range(0, len(diceList3)):
                for h in range(0, len(diceList2[b])):
                    try:
                        if diceList2[d][h] not in makeAlphabet:
                            makeAlphabet += [diceList2[d][h]]
                    except:
                        try:
                            for s in range(0, len(diceList3)):
                                for f in range(0, len(diceList2)):
                                    if diceList2[s][f] not in makeAlphabet:
                                        makeAlphabet += [diceList2[s][f]]
                        except:
                            ("your word is too short")
            time.sleep(1)

我相信问题是if guessedWordUnderlined in askForWord永远不会是真的。in运算符测试第一个运算符是否在第二个参数内,第二个参数是一个容器,例如列表或字符串。"_" * len(askForWord)guessedWordUnderlined的值是一个下划线字符串,您正在测试它是否在{}中。如果askForWord的值是cataskForWord可以被认为是["c", "a", "t"],因此in运算符将测试{},但没有一个是真的。这意味着它下面的代码永远不会执行,所以代码永远重复,随机猜测单词中的字母。我真的不知道这个if的功能是什么,因为你已经知道你可以选择的每个字母都在askForWord中,尽管我确信我遗漏了一些显而易见的东西。在

顺便说一句,您经常使用类似于for x in range(0, len(LIST): ... LIST[x]的结构,它可以更简洁、更明显地写成for x in LIST: ... x。例如,您的代码

for k in range (0, len(fullDice)):
    if len(askForWord) == len(fullDice[k]):
        updatedDice += [fullDice[k]]

alphabet = []

可以写成

^{pr2}$

这将帮助您的代码变得更具可读性。还有一些其他的编辑可以使你的代码更像python,但是除了这一行之外,我看不出它有什么功能上的错误。如果您共享这个if应该有什么帮助,那么在代码中查找其他错误可能会更容易一些。我希望这有帮助,祝你好运!在

再次检查代码后,我认为问题出在guessedWordUnderlined = "_" * len(askForWord)语句中。这将创建一个长度等于askFOrWord的下划线字符串。问题是在while True:循环的每次迭代中,都会有一个新的字符串。这意味着在每次迭代中,字符串都会变成一个带有一个正确字母的下划线列表,但在下一次迭代中,它将被重写。要解决这个问题,您应该将guessedWordUnderlined = "_" * len(askForWord)从其当前位置移动到askForWord = input("Please enter an english word: ")的正下方。这意味着它出现在全局范围而不是局部作用域中,这意味着它不会被覆盖。如果我没弄错的话,您还应该将global guessedWordUnderlined行放在while循环的开头。这可能需要您重新编写一些代码。希望这对你有用!在

相关问题 更多 >