用长度标准随机选择单词。如何分解?

2024-04-26 07:44:16 发布

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

这是我的游戏计划我完成(它的工作)。一开始我想增加一个难度等级。简单是六个字母的单词,中等是七个字母,难是八个或更多。它会去哪里?你知道吗

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")

Tags: in游戏for字母linerandom单词计划
1条回答
网友
1楼 · 发布于 2024-04-26 07:44:16

(一般来说,对于不完整代码的how-do-I-implement或重构问题,http://codereview.stackexchange.com更合适。)

好的,您首先要提示用户难度级别,将其转换为相应的字长,字长,然后在您的选词和洗牌代码中使用它们。 这一切都可以通过一点重构来完成,因为您需要传递一些数据,所以我用setup()play()方法重构成一个类。 而且你只想在你的单词列表中读一次(例如在类__init__()方法中),而不是每一个游戏。你知道吗

注意dictlevel_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()

相关问题 更多 >