-2

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.

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!")
deadshot
  • 8,881
  • 4
  • 20
  • 39

3 Answers3

0

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
pyInTheSky
  • 1,459
  • 1
  • 9
  • 24
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.

-1

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!")
DaVinci
  • 868
  • 1
  • 7
  • 25