python随机猜词程序

2024-04-26 05:28:21 发布

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

我正在用python编写一个猜字游戏,但是我在guess()函数中遇到了一些问题

当用户猜到一个正确的字母并用该字符替换时,空格(u3;)应该相应地消失。然而,仍然有一些徘徊甚至用户猜对了单词。如何调整格式以使其被猜测的字符替换

另一个问题是,程序给了我10次尝试,无论我得到的字是对还是错。我猜测在尝试时使用if语句或for循环。在我说对了词之后我该怎么让它停下来

谢谢

    def pick():
        print()
        f = open('words.txt', 'r')
        wlist = f.readlines()
        f.close()
        chosenword = random.choice(wlist)

        return(chosenword)

    def guess():
        #Determine length of chosen word and display number of blanks
        chosenword = pick()
        pH = '_ ' * (len(chosenword)-1)
        print()
        print (pH)
        print()

        #Number of failed attempts
        attempt = 0
        count = 10
        #Receive guess
        for i in range (0, 10):
            attempt += 1
            guess = input("Enter a letter for a guess : ")
            guess = guess.upper()

        #Check if guess is found in random word
            if guess in chosenword:
                for i in range (0,len(chosenword)):
                    if guess == chosenword[i]:
                        pH = pH[:i] + guess + pH[i+1:]
                print(pH)
            if guess not in chosenword:
                print(pH)
        if pH == chosenword:
            print ("You guessed the word - congrats!")
        else:
            print ("The word was ",chosenword)
            print ("Sorry - bettter luck next time.") 
    guess()
    pick()

Tags: of用户inforifdefrandom字符
1条回答
网友
1楼 · 发布于 2024-04-26 05:28:21

下面是一个使用指定列表的版本。您可以将其更改为从文件读取。我在代码中添加了注释以显示对代码的更正

import random

def pick():
        # You want to change this to load from file
        wlist = ['hello', 'today', 'monday', 'every', 'neighbor']
        chosenword = random.choice(wlist)

        return chosenword

def guess():
    #Determine length of chosen word and display number of blanks
    chosenword = pick().upper()  # Use upper case throughout

    pH = '_' * len(chosenword)    # don't subtract one from length and remove space
    print (pH)

    #Number of failed attempts
    attempt = 0
    count = 10
    #Receive guess
    for i in range (0, 10):
        attempt += 1
        guess = input("Enter a letter for a guess : ")
        guess = guess.upper()

        #Check if guess is found in random word
        if guess in chosenword:
            for i in range (0,len(chosenword)):
                if guess == chosenword[i]:
                    pH = pH[:i] + guess + pH[i+1:]  
            if pH == chosenword:
              break  # need to break from guessing when they have guess the right word
        if guess not in chosenword:
            print(pH)

    if pH == chosenword:
        print ("You guessed the word - congrats!")
        return  # need to break from funtion when they guess the right word
    else:
        print ("The word was ",chosenword)
        print ("Sorry - bettter luck next time.")

guess()

相关问题 更多 >