选择具有长度标准的随机单词。怎么分解?

时间:2015-03-20 00:09:41

标签: python refactoring decomposition

这是我完成的游戏计划(可行)。我想在开始时添加一个难度级别。容易是六个字母的单词,中等是七个,硬的是八个或更多。它会去哪里?

Letters = set(string.ascii_lowercase)

def main():

    words = [line.strip() for line in open("E:\wordlist.txt")]
    correct_word = random.choice(words).strip().upper()
    letters = list(correct_word)
    random.shuffle(letters)
    word = ""
    for i in range (len(letters)):
        word += letters[i]
    print("Welcome to my game, solve the puzzle.")

    print("Lets play")

1 个答案:

答案 0 :(得分:0)

(一般情况下,您会发现http://codereview.stackexchange.com比SO更适合我对如何实施或重构不完整代码的问题。)

好的,首先要提示用户提高难度级别,将其转换为相应的字长,字长,然后在单词选择和改组代码中使用。 这可以通过一些重构来完成,因为您需要传递一些数据,所以我使用setup()play()方法重构为一个类。 此外,您只想阅读一次单词列表(例如在课程__init__()方法中),而不是每个游戏。

注意使用dict level_to_wordlength中的元组赋值,以及 choose_random_word()

中紧凑的while循环习语
import random
import string

class Hangman(object):

    def __init__(self, wordlist = 'wordlist.txt'):
        self.words = [word.strip() for word in open(wordlist)] # store them uppercase
        #self.level = None
        #self.min_wordlength = None
        #self.max_wordlength = None
        self.correct_word = None
        self.letters_unused = None

    def select_difficulty(self):
        while True:
            level = raw_input("Choose difficulty: E(asy) M(edium) H(ard) : ")
            level = (level or " ")[0].upper()
            if level in 'EMH':
                return level
            print "Error: bad level"
        # or store it in self.level if needed

    def choose_random_word(self, min_wordlength, max_wordlength):
        word = ''
        while not( min_wordlength <= len(word) <= max_wordlength ): # note the idiom
            word = random.choice(self.words)
        self.correct_word = word

    def setup(self):
        level = self.select_difficulty()  # or store it in self.level if needed

        # Convert level to wordlength constraints...  we could use an if..elif ladder for simplicity,
        # but here's a neat idiomatic method using tuple assignment from a dict.
        level_to_wordlength =  {'E': (6,6), 'M': (7,7), 'H': (8,999)}
        min_wordlength, max_wordlength = level_to_wordlength[level]

        self.choose_random_word(min_wordlength, max_wordlength)

        self.letters_unused = set(string.ascii_uppercase)

    def play(self):
        letters = list(self.correct_word)
        random.shuffle(letters)
        word = ''.join(letters)

        print("Welcome to my game, solve the puzzle.")
        print("Let's play")
        # ... you do the rest ...

if __name__ == '__main__':

    game = Hangman()
    game.setup()
    game.play()