Justen
Justen

Reputation: 4869

Problem with my hangman game

I'm trying to learn python and I'm attempting a hangman game. But when I try and compare the user's guess to the 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

Upvotes: 0

Views: 782

Answers (2)

FireSwarm
FireSwarm

Reputation: 23

This is what i did for my hangman 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 the hidden word that the user is trying to guess. hidden letter contains the amount of "_" in the word: i.e. hiddenletter = " _ " * len(secretword)

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

Upvotes: 0

Laurence Gonsalves
Laurence Gonsalves

Reputation: 143154

In your "for word in wordlist" loop, each word will end in a newline. Try adding word = word.strip() as the next line.

By the way your last loop could be replaced with:

if guess in word:
    print ("Yessssh")

Bonus tip: when adding "debug prints", it's often a good idea to use repr (especially when dealing with strings). For example, your line:

print (guess) #for testing purposes

Might be more useful if you wrote:

print (repr(guess)) #for testing purposes

That way if there are weird characters in guess, you'll see them more easily in your debug output.

Upvotes: 8

Related Questions