在Python中使用Evil Hangman的随机函数



我想做的是把我原来的刽子手游戏改成所谓的邪恶刽子手。为此,我需要首先生成一个单词的随机长度,并从原始列表中提取该长度的所有单词。

这是我正在使用的代码:

def setUp():
"""shows instructions, reads file,and returns a list of words from the english dictionary"""
try:
    print(60*'*' +'''nttWelcome to Hangman!nt
I have selected a word from an english dictionary. nt
I will first show you the length of the secret wordnt
as a series of dashes.nt
Your task is to guess the secret word one letter at a time.nt
If you guess a correct letter I will show you the guessednt
letter(s) in the correct position.n
You can only make 8 wrong guesses before you are hangedn
ttGood luckn''' + 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 swhich case it updates s[1]"""
    if wr == 8:
            l += 1
            print('Sorry, you have lost this game.nnThe 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,但它似乎只返回列表的第一项和最后一项,而不是显示字符最多的单词。任何帮助,不胜感激。

如果你的"字典.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

如果你的记忆有限,那么你应该首先遍历单词列表中的所有单词,跟踪这些单词的最小和最大长度,然后重复该单词列表,只附加那些所需长度的单词。您需要的内容在上面的代码中提到,只需要一些代码重新洗牌。我把它留给你作为练习。

最新更新