【问题标题】:Python hangman game. Python 3Python 刽子手游戏。蟒蛇 3
【发布时间】:2015-07-22 15:43:45
【问题描述】:

我正在尝试使用 Python 创建一个简单的 Hangman 游戏。我遇到了一个我无法解决的问题,希望能收到你们的一些建议。

好的,我将为您提供我的代码示例,在它下面,我将解释我的问题是什么:

# Here is my list of words
words = ['eight', 'nine', 'seven'...]
# Choosing a random word from the list
word = random.choice(words)

# Creating an empty list to store the result 
secret_word = []

# Creating a count variable which I will use later to determinate if the player wins
count = 1

for letter in word:
    secret_word.append('_')
secret_word[0] = word[0]

user_guess = input("Enter a letter: ")

# Here if the user guesses a letter
# We will place that letter on it's spot in our secret_word
while user_guess:
    if user_guess in word:
        print("Correct letter.")
        # adding 1 to count for every guessed letter
        count += 1
        # replacing the '_' with the letter
        for letter in range(len(word)):
            if user_guess == word[letter]:
                secret_word[letter] = word[letter]
        # here I am checking if the user has won
        if count == len(word):
            print("You Win!")

我只给了你程序的一部分,因为我认为不需要整个代码。

我的问题在于计数变量。正如你所看到的,每次当用户猜出正确的字母时,我都会在变量中添加 + 1,因此当 count 变量 = len(word) 时,我的小程序就会知道用户赢了。

无论如何,当一个字母在单词中出现两次时,例如单词 SEVEN 的字母 E 是我的计数变量的两倍,因此在这种情况下用户无法获胜。我完全不知道如何解决这个问题,很乐意收到一些提示。

谢谢,请原谅我糟糕的英语和编码技巧

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    每当您将下划线替换为正确的字母时,您都可以增加count。这样,count 将等于单词中到目前为止正确的字母数。

    为了更清楚,当您将下划线替换为实际字母时,将count += 1 移动到if 语句中。

    我看到的一个问题是你给玩家第一个字母并将count初始化为1。我不知道你为什么这样做,但如果第一个字母出现不止一次,它不会反映在单词中,无论如何玩家仍然需要猜测那个字母。

    【讨论】:

    • 没有 OP 不是。每次用户正确猜到一个字母时,他都会增加它。我建议他每次替换下划线时都增加它。
    【解决方案2】:

    将计数移动到要替换字母的位置。

    while user_guess:
        if user_guess in word:
            print("Correct letter.")
            # replacing the '_' with the letter
            for letter in range(len(word)):
                if user_guess == word[letter]:
                    # adding 1 to count for every guessed letter
                    count += 1
                    secret_word[letter] = word[letter]
            # here I am checking if the user has won
            if count == len(word):
                print("You Win!")
    

    【讨论】:

      猜你喜欢
      • 2014-10-19
      • 1970-01-01
      • 2015-05-29
      • 1970-01-01
      • 1970-01-01
      • 2019-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多