The problem with my hangman game

I am trying to learn python and I am trying to play hangman. But when I try to compare the user to a word, it doesn't work. What am I missing?

import sys
import codecs
import random

if __name__ == '__main__':
    try:
        wordlist = codecs.open("words.txt", "r")
    except Exception as ex:
        print (ex)
        print ("\n**Could not open file!**\n")
        sys.exit(0)

    rand = int(random.random()*5 + 1)
    i = 0

    for word in wordlist:
        i+=1
        if i == rand:
            print (word, end = '')
            break

    wordlist.close()

    guess = input("Guess a letter: ")
    print (guess) #for testing purposes

    for letters in word:
        if guess == letters:
            print ("Yessssh")

#guessing part and user interface here

      

0


a source to share


2 answers


In the " for word in wordlist

" loop, each word ends with a new line. Try adding word = word.strip()

in the next line.

By the way, your last loop can be replaced with:

if guess in word:
    print ("Yessssh")

      

Bonus tip: When adding debug fingerprints, it is often recommended to use the registry (especially when working with strings). For example your line:



print (guess) #for testing purposes

      

It might be helpful if you wrote:

print (repr(guess)) #for testing purposes

      

This way, if guess

there are strange characters in, you will see them more easily in your debug output.

+8


a source


This is what I did for my executioner game:

     for x in range(0, len(secretword)):
           if letter == secretword[x]:
                for x in range(len(secretword)):
                    if secretword[x] in letter:
                         hiddenletter = hiddenletter[:x] + secretword[x] +hiddenletter[x+1:]

     for letter in hiddenletter:
          print(letter, end=' ')

      



secretword is a hidden word that the user is trying to guess. the hidden letter contains the number of the word "_" in the word: i.e. hidden text = "_" * len (secret word)

this replaces spaces with correctly guessed letters and then shows underscores in letters in the correct places i did my best ...

0


a source







All Articles