简体   繁体   English

Python 3 - 刽子手游戏 using.txt doc word bank

[英]Python 3 - Hangman game using .txt doc word bank

Im trying to make a hangman using a word bank stored on a.txt document but I'm so confused and just going round in circles.我试图使用存储在 a.txt 文档中的单词库来制作刽子手,但我很困惑,只能绕圈子。

Can anyone point me in the right direction?谁能指出我正确的方向? My code so far is below.到目前为止,我的代码如下。 Cheers!干杯!

#Word list
from random import choice

word = with open("words.txt") as f:
    word_list = f.read().splitlines()

#title
print("Welcome to Hangman! You have 7 lives to guess.")

#word generator
hidden_word = random.sample(words,1)

if(hidden_word[0]):
    print("The length of the word is: " , len(hidden_word[0]))

#parameters
guesses=0
guessed = []
word = []

#Game
for x in range(len(hidden_word[0])):
    word.append(' * ')

while guesses < 7:
    guess = input("Please enter your next guess: ""\n")

    if(guess in hidden_word[0]):
        print("The letter is correct.")
        for index, letter in enumerate(hidden_word[0]):
            if letter == guess:
                word[index] = guess
        guessed.append(guess)

    else:
            print("That letter is incorrect.")
            guesses=guesses+1
            guessed.append(guess)

    print("Please enter your next guess:")
    print("So far, you have answered - %s"%''.join(word))
    print()

    if ''.join(word) == hidden_word[0]:
        break

#Game finish
if guesses==7:
    print("You lose. The word was:" , hidden_word[0])
else:
    print("Congratulations, you won!")

Here is a tested working bit of code.这是一段经过测试的工作代码。 You'll find the main issues were with your import, an incorrect open statement, incorrect indexing of non-list variables... in many cases, you were indexing a string, which was clearly not what you wanted to be doing.您会发现主要问题在于您的导入、不正确的打开语句、不正确的非列表变量索引……在许多情况下,您正在索引一个字符串,这显然不是您想要做的。

import random

# note: get in the habit now of putting your code in a function and not polluting the global scope
# we can test the code using a test word in the event that a stackoverflow contributor doesn't have a words.txt file at hand :P
def main(test_word = "banana"):
    # if there is no words.txt, we will use the test word
    try:
        with open("words.txt") as f:
            word_list = f.read().splitlines()
    except IOError:
        word_list = [test_word]

    # we use random.choice, as we have a list and we want a random word from that list
    # we also want to make sure we put the word and our guesses into the same case, so here I chose lower case
    hidden_word = random.choice(word_list).lower()

    print("Welcome to Hangman! You have 7 lives to guess.")
    print("The length of the word is: " , len(hidden_word))

    failures    = 0
    guessed     = []
    # python is cool, and you can get repeat characters in a list by multiplying!!
    word        = ['*'] * len(hidden_word)

    while failures < 7:
        print("The word is: %s" % ''.join(word))

        try:
            guess = input("Please enter your next guess: ""\n")[0].lower()
        except IndexError:
            # just hitting enter will allow us to break out of the program early
            break

        if guess in guessed:
            # ignore an already guessed letter
            continue
        elif guess in hidden_word:
            print("The letter is correct.")
            for index, letter in enumerate(hidden_word):
                if letter == guess:
                    word[index] = "%s" % guess
        else:
            print("That letter is incorrect.")
            failures += 1
        guessed.append(guess)

        if ''.join(word) == hidden_word:
            break

    if failures == 7:
        print("You lose. The word was:" , hidden_word)
    else:
        print("Indeed, the word is:", hidden_word)

# see https://stackoverflow.com/questions/419163/what-does-if-name-main-do for details on why we do this
if __name__ == "__main__":
    main()

Sample Usage示例使用

Welcome to Hangman! You have 7 lives to guess.
The length of the word is:  6
The word is: ******
Please enter your next guess: 
n
The letter is correct.
The word is: **n*n*
Please enter your next guess: 
b
The letter is correct.
The word is: b*n*n*
Please enter your next guess: 
a
The letter is correct.
Indeed, the word is: banana

Process finished with exit code 0

Yes, the file importing was a bit of a sticking point for me.是的,文件导入对我来说有点棘手。 Definitely need to have another look at this.绝对需要再看看这个。

Looking at your answers, it makes a lot of sense but a reread would be smart.看看你的答案,这很有意义,但重读会很聪明。

I think you have made some mistakes while importing random, and while you use with you should not declare it to a variable This should do it我认为你在导入随机数时犯了一些错误,当你使用时你不应该将它声明为变量 这应该这样做

import random

with open("words.txt") as f:
    word_list = f.read().splitlines()

#title
print("Welcome to Hangman! You have 7 lives to guess.")

#word generator
hidden_word = random.sample(word_list,1)

if(hidden_word[0]):
    print("The length of the word is: " , len(hidden_word[0]))

#parameters
guesses=0
guessed = []
word = []

#Game
for x in range(len(hidden_word[0])):
    word.append(' * ')

while guesses < 7:
    guess = input("Please enter your next guess: ""\n")

    if(guess in hidden_word[0]):
        print("The letter is correct.")
        for index, letter in enumerate(hidden_word[0]):
            if letter == guess:
                word[index] = guess
        guessed.append(guess)

    else:
            print("That letter is incorrect.")
            guesses=guesses+1
            guessed.append(guess)

    print("Please enter your next guess:")
    print("So far, you have answered - %s"%''.join(word))
    print()

    if ''.join(word) == hidden_word[0]:
        break

#Game finish
if guesses==7:
    print("You lose. The word was:" , hidden_word[0])
else:
    print("Congratulations, you won!")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM