0
import random
words=["cat", "dog", "animal", "something", "whale", "crocodile", "lion", "summer", "boston", "seattle"]
the_word=random.choice(words)
#print(the_word)
a=len(the_word) #number of letter in the word
c=['_'for i in range(a)]#blanks seperated
blanks=" ".join(c)
print("This is a word with",a,"letter")
print("\t", blanks)
guess=0
while guess<3:
    answer=input("Please enter a letter: ")
    if answer in the_word:
        the_index=the_word.index(answer)#find the index
        c[the_index]=answer
        blanks=" ".join(c)
        print(blanks)
    else:
        guess=guess+1
        print("There is no",answer,"in the word.")

I have two problems:
1st I can't reveal 2 words, summer for example, if a user input 'm' it will reveal only the first letter 'm'
2nd when the user input more than one word the program still consider right answer. For example: The user input "nm" for the word "something" the program still consider it right, and the word turn out like this "somethinmg"

  • For 1, check the occurrence of the letter in the word first, and get all the indices. For 2, I tried to check "nm" in "something" but I got False. But you can have an if statement outside before your if statement to check if the length of the input is 1, if yes, proceed, if not, return error or let the user enters the value again. – TYZ Apr 02 '14 at 20:28

2 Answers2

0

You can check the length of answer via something like

if len(answer) != 1:
    print "Please enter just one letter"

Or you can simply take only the first letter of what they enter

letter = answer[0]

See How to find all occurrences of an element in a list? on how to find multiple indexes that match.

Community
  • 1
  • 1
alecbz
  • 6,292
  • 4
  • 30
  • 50
0

Okay first of all to do the display I would take the word, split it up into letters and then create a list with the same length containing all '_'. This way you could display the _ _ _ _ etc by calling ' '.join(substitutelist)....

To get multiple letter responses: each guess call

for letter in range(len(word)):
    if word[letter]==guess.lower():
        substitutelist[letter]=guess.lower()

Then every time a letter was called I would add it to a list titled something like "USED" and check each guess to make sure its not in zip(word, used) and if it is return a message error.

Here is an example hangman code I wrote to show the different functions...

import re, sys
from random import choice

def showmap(hangmanpic):
    """Will show the hangman pic after subtracting any
    characters holding the place of a future body part"""
    tempmap=''
    x=str(range(7))
    for i in hangmanpic:
        if i in x:
            tempmap+=' '
        else:
            tempmap+=i
    return tempmap

def addbodypart(remaining, hangmanmap):
    """takes the hangman map and substitutes in a body
    part when a wrong answer is chosen.  Returns the new
    hangmanmap"""
    bodyparts={'6':'(_)',
           '5':'|',
           '3':'\\\\',
           '2':'\\\\',
          '4':'/',
           '1':'/'
          }
    return re.sub(str(remaining), bodyparts[str(remaining)], hangmanmap)

def StartGame(hangmanmap, word):
    """Starts the game"""
    dashword, wrong=[], []
    remaining=6
    for i in word:
        dashword.append('_')
    while remaining>0:
        if '_' not in dashword:
            remaining=0
            continue
        for i in range(5):
            print ""
        print "Guesses Left = %d" %(remaining)
        print showmap(hangmanmap)
        print ""
        print "Used Letters: %s" %(', '.join(wrong))
        print "Word: %s"%(' '.join(dashword))
        guess=str(raw_input('Guess a letter:')).lower()
        if guess in str(wrong)+str(dashword):
            print ""
            print "Sorry but you have already guessed that letter.  Please guess again."
            print ""
            continue
        if guess not in word:
            hangmanmap=addbodypart(remaining, hangmanmap)
            remaining-=1
            wrong.append(guess)
        else:
            for i in range(0, len(word)):
                if word[i]==guess:
                    dashword[i]=guess
    if '_' not in dashword:
        for i in range(5):
            print ""
        print "You WIN!  Congrats"
        print "The word was %s" %(word)
        print showmap(hangmanmap)
        print "Used Letters: %s" %(', '.join(wrong))
        print "Word: %s"%(' '.join(dashword))
    else:
        for i in range(5):
            print ""
        print showmap(hangmanmap)
        print "Word: %s" %(word)
        print "Sorry but you've ran out of guesses! You Lose!  The correct word was %s" %(word)

def main():
    word=str(choice([line.strip() for line in open(sys.argv[1])])).lower()
    hangmanmap="""          _________
          |/      |
          |      6
          |      354
          |       5
          |      1 2
          |
       ___|___"""

    print "Welcome to AmazingReds Hangman Game!"
    print "6 wrong answers and YOU LOSE!  Good Luck."
    StartGame(hangmanmap, word)
if __name__ == '__main__':
    main()
Amazingred
  • 1,007
  • 6
  • 14