首页 > 解决方案 > 如果从字符串中选择某个单词,如何仅使一段代码工作

问题描述

我正在尝试使用 Python 创建一个刽子手游戏。Though, when the word "sun" is picked, and if the word "tree" is inputted into the console as an answer by me, it says the answer is correct when it is not. 我已经尝试创建一个函数来解决这种情况,但是,它对我不起作用......

这是我的代码:

#hangman mini-project

import random
import string
import time

letters = string.ascii_letters
lettertree = ['a', 'b', 'c', 'd', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 's', 'u', 'v', 'w', 'x', 'y', 'z']
hangmanwords = ['tree','sun']
sunchoices = ['s _ _', '_ u _', '_ _ n']
treechoices = ['t _ _ _', '_ r _ _', ' _ _ e _', '_ _ _ e']
lettercount = [0]
gameWinTree = False
gameWinSun = False
limbCount = 5

hangmanword = random.choice(hangmanwords)
correct = hangmanword
if hangmanword == "sun":
    print (random.choice(sunchoices))
if hangmanword == "tree":
    print (random.choice(treechoices))
        
    
    if letters == "r":
        print("Nice! You guessed one letter from the word")
        if letters == "e":
            print("Wow! You guessed two letters from the word, if you wish, you can guess the word")
while True:
    letters = input("Please enter a letter to guess the word")
    if letters == "tree":
        input("Correct! The word was tree! Press enter to play again.")
        time.sleep(1)
        break
    if letters == "tree":
        gameWinTree == true
        if gameWinTree == true:
            time.sleep(1)
        break
    print("The letter that you chose was " + letters)
    if letters == "r":
        print("Nice! You guessed one letter from the word!\n t r _ _")
        
    if letters == "e":
        print("Wow! You guessed two letters from the word!\n t _ e e")
    if letters == "tree":
        print("Correct! The word was tree!")
    if letters == lettertree:
        print("Sorry, that's not a correct letter, feel free to try again.")
    limbCount -=1
    if limbCount == 0: 
        print("Unfortunately, you are out of tries, better luck next time!")
        time.sleep(1)
        exit()
       

基本上,如果选择了“太阳”这个词,我希望这个词树的代码不起作用。如果我的代码草率,也很抱歉,尝试快速创建它!谢谢

标签: pythonstring

解决方案


专门针对您的问题

在您当前的代码中,您正在检查用户是否无论如何都猜到了“树”,而实际上您只想检查所选单词是否为“树”。因此,在您的 if 语句中,您可以添加一个“and”并额外检查正确的单词。

if letters == "tree" and correct == "tree":

更笼统

正如已经指出的那样,无论选择哪个单词作为正确单词,在您的游戏循环中,您总是在寻找猜测“树”。

您已经使用正确的单词保存了一个变量来检查,所以使用它而不是检查“树”:

if letters == "tree":

应该是:

if letters == correct:

然后让代码编写正确的消息连接打印中的字符串:

input("Correct! The word was " + correct + " Press enter to play again.")

推荐阅读