【问题标题】:Using the random function in Python for Evil Hangman在 Python 中为 Evil Hangman 使用随机函数
【发布时间】:2014-11-12 00:14:11
【问题描述】:

我想做的是将我原来的刽子手游戏改成所谓的邪恶刽子手。为了做到这一点,我需要首先生成一个随机长度的单词,然后从原始列表中取出该长度的所有单词。

这是我正在使用的代码:

def setUp():
"""shows instructions, reads file,and returns a list of words from the english dictionary"""
try:
    print(60*'*' +'''\n\t\tWelcome to Hangman!\n\t
I have selected a word from an english dictionary. \n\t
I will first show you the length of the secret word\n\t
as a series of dashes.\n\t
Your task is to guess the secret word one letter at a time.\n\t
If you guess a correct letter I will show you the guessed\n\t
letter(s) in the correct position.\n
You can only make 8 wrong guesses before you are hanged\n
\t\tGood luck\n''' + 60*'*')
    infile=open('dictionary.txt')
    l=infile.readlines()# list of words from which to choose
    infile.close()
    cleanList = []
    for word in l:
        cleanList.append(l[:-1])
    return(cleanList)
except IOError:
    print('There was a problem loading the dictionary file as is.')

def sort_dict_words_by_length(words):
    """Given a list containing words of different length, 
    sort those words based on their length."""

    d = defaultdict(list)
    for word in words:
        d[len(word)].append(word)
    return d

def pick_random_length_from_dictionary(diction):
    max_len, min_len = ( f(diction.keys()) for f in (max, min) )
    length = random.randint(min_len, max_len)
    return diction[length]

def playRound(w,g):
    """ It allows user to guess one letter. If right,places letter in correct positions in    current guess string g, and shows current guess to user
if not, increments w, number of wrongs. Returns current number of wrongs and current guess string"""
    print('You have ' + str(8 - w) + ' possible wrong guesses left.\n')
    newLetter = input('Please guess a letter of the secret word:\n')
    glist = list(g)#need to make changes to current guess string so need a mutable version of it
    if newLetter in secretWord:
        for j in range (0,len(secretWord)):
            if secretWord[j]==newLetter:
               glist[j] = newLetter
        g = ''.join(glist)#reassemble the guess as a string
        print('Your letter is indeed present in the secret word: ' +  ' '.join(g)+'\n')
    else:
        w += 1
        print('Sorry, there are no ' + newLetter + ' in the secret word. Try again.\n')
    return(w,g)

def endRound(wr, w,l):
"""determines whether user guessed secret word, in which case updates s[0], or failed after w=8 attempts, in s\which case it updates s[1]"""
    if wr == 8:
            l += 1
            print('Sorry, you have lost this game.\n\nThe secret word was '+secretWord +'\n')#minor violation of encapsulation
    else:
        w +=1
        print(15*'*' + 'You got it!' + 15*'*')
    return(w,l)

def askIfMore():
    """ask user if s/he wants to play another round of the game"""
    while True:
        more = input('Would you like to play another round?(y/n)')
        if more[0].upper() == 'Y' or more[0].upper()=='N':
            return more[0].upper()
        else:
            continue

def printStats(w,l):
    """prints final statistics"""
    wGames='games'
    lGames = 'games'
    if w == 1:
        wGames = 'game'
    if l ==1:
        lGames = 'game'
    print('''Thank you for playing with us!\nYou have won {} {} and lost {} {}.\nGoodbye.'''.format(w,wGames,l,lGames))

try:

    import random
    from collections import defaultdict
    words=setUp()#list of words from which to choose
    won, lost = 0,0 #accumulators for games won, and lost
    while True:
        wrongs=0 # accumulator for wrong guesses
        secretWord = random.choice(words)[:#eliminates '\n' at the end of each line
        print(secretWord) #for testing purposes
        guess= len(secretWord)*'_'
        print('Secret Word:' + ' '.join(guess))
        while wrongs < 8 and guess != secretWord:
            wrongs, guess = playRound(wrongs, guess)
        won, lost = endRound(wrongs,won,lost)
        if askIfMore()== 'N':
            break
    printStats(won, lost)
except:
    quit()

我想做的是生成一个随机数,下限是最短长度的单词,上限是最高长度的单词,然后使用该随机数创建一个新容器,其中包含只有该长度的单词,最后返回该容器以供游戏进一步使用。我尝试使用 min 和 max,但它似乎只返回列表的第一项和最后一项,而不是显示字符最多的单词。任何帮助表示赞赏。

【问题讨论】:

    标签: python-3.x random


    【解决方案1】:

    如果您的 'dictionary.txt' 每行有一个单词,您可以使用以下内容,这样可以提高速度,因为它只会遍历列表一次。但它会再次消耗您原始列表的内存。

    from collections import defaultdict
    import random
    
    def sort_dict_words_by_length(words):
        """Given a list containing words of different length, 
        sort those words based on their length."""
    
        d = defaultdict(list)
        for word in words:
            d[len(word)].append(word)
        return d
    
    def pick_random_length_from_dictionary(diction):
        max_len, min_len = ( f(diction.keys()) for f in (max, min) )
        length = random.randint(min_len, max_len)
        return diction[length]
    

    然后,您可以将setUp 的输出传递给sort_dict_words_by_length,然后将该输出传递给pick_random_length_from_dictionary

    如果您的记忆力有限,那么您应该首先检查单词列表中的所有单词,跟踪这些单词的最小和最大长度,然后重复该单词列表,仅附加所需长度的单词。上面的代码中提到了你需要的东西,只需要一些代码改组。我会把它留给你作为练习。

    【讨论】:

    • 我为上下文添加了完整的代码,并确保我正确地实现了这一点。因此,为了使用您的建议,我将从 setUp() 函数返回的 cleanList 传递给 sort dict 函数?实际上,setUp 函数的结果存储在变量 'words' 中,所以我会将其传递给 sort 函数?
    • 没关系,我玩过它并想通了。感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 2014-08-21
    • 1970-01-01
    • 2010-12-17
    • 2018-08-06
    • 2015-04-26
    • 2016-07-23
    • 1970-01-01
    • 2021-07-14
    相关资源
    最近更新 更多