#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    2
    Rep Power
    0

    Can't get my hangman program to exit loop to win!


    Here's my code, I just can't figure out how to make it recognize that the whole word has been guessed.
    Code:
    import random
    dictionary=['ABRUPT','BLITZ','BUCCANEER','CROISSANT','BEFUDDLE','GIZMO','HAIKU','JOVIAL','NUMB','SQUAWK','THE','MAGIC','ARTIST','TRAVEL','NOWADAYS','ITALIAN','MOUSTACHE','GLOOMY','STARTLED','AMBIGUOUS','GREEN','NUMBER','HANDYMAN','RATCHET','BOILED','ENCRUSTED','AROUND','CHIMPANZEE','PARAKEET','BOOTSTRAPS']
    difficulty=str(input("would you like an easy, medium, or hard word?"))
    for word in dictionary:
        if difficulty == "easy":
            word=random.choice(dictionary[21:31])
        elif difficulty=="medium":
            word=random.choice(dictionary[11:21])
        elif difficulty=="hard":
            word=random.choice(dictionary[0:11])
    wordLength=len(word)
    wrongGuesses=''
    rightGuesses=''
    numGuesses=0
    guesses=wordLength*[' _ ']
    alreadyGuessed=''
    maxWrong=6
    gamePoints=rightGuesses
    gameOver=numGuesses>=maxWrong
    
    
    
    def whatLevel(difficulty):
        if difficulty == "easy":
            print(word)
        elif difficulty == "medium":
            print(word)
        elif difficulty == "hard":
             print(word)
            
        else:
            print("Error: Please try again and type in 'easy', 'medium', or 'hard' for your difficulty level:")
    
    def printRules(maxWrong, wordLength):
        wordLength=1
        print("Guess the word in 7 tries!")
        return
    def getGuess():
        print
        guess=input("Guess a CAPITAL letter: ")
        guess.strip()
        guess.upper()
        print()
        return guess
      
    
    printRules(maxWrong, wordLength)
    
    
    def nextGame():
        playAgainResponse=input('Play Again?')
        if input==("Yes"):
            difficulty
            wrongGuesses=''
            rightGuesses=''
            gamePoints=gamePoints+rightGuesses
        
    
    
    while not gameOver:
        letter=getGuess()
        if len(letter)==1 and letter in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
            if alreadyGuessed.find(letter)!= -1:
                print ("You already picked", letter)
            else:
                alreadyGuessed=alreadyGuessed+letter
                firsttryWord=word.find(letter)
                if firsttryWord==-1:
                    wrongGuesses=wrongGuesses+letter
                    print("Oops! ",letter,"is not in the word.")
                else:
                    print("Yes! ",letter,"is in the word!")
                    rightGuesses=rightGuesses+letter
                    for instances in range(wordLength):
                        if letter == word[instances]:
                            guesses[instances]=letter
                    
                        
        else:
            print("Please guess a single alphabetical letter!")
        print(''.join(guesses))
        print ("Missed Letters: ", wrongGuesses)
        if len(wrongGuesses)==maxWrong:
            print ("You lose!")
            print("The word was "+word)
            print("You have "+gamePoints+" points!")
            gameOver
            nextGame()
    
    if letter in word:
            rightGuesses= rightGuesses+letter
            if word == letter:
                allLettersFound=True
    for i in range(wordLength):
            if word not in rightGuesses:
                allLettersFound=False
                break
            if allLettersFound:
                print("You win!")
                print("The word was", word, "You have",gamePoints,"points!")
                gameOver
                nextGame()
                break
    
                
    
    getGuess()
    nextGame()
  2. #2
  3. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    16
    Rep Power
    0
    http://inventwithpython.com/chapter9.html

    Here you can find a complete tutorial on how to make a hangman game
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    2
    Rep Power
    0

    thanks


    ...
  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    16
    Rep Power
    0
    Code:
    while not gameOver:
        letter=getGuess()
    
    
    def getGuess():
        print
        guess=input("Guess a CAPITAL letter: ")
        guess.strip()
        guess.upper()
        print()
        return guess
    
    
    if letter in word:
            rightGuesses= rightGuesses+letter
            if word == letter:
                allLettersFound=True
    I'm no expert in python, but how I see it word will never == letter, because no word only consist of one letter. This causes allLetterFound never to be True.
  8. #5
  9. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,931
    Rep Power
    481

    please read comments of this working version


    Code:
    # python 3
    
    # re-implement with sets.  Many of the hangman algorithmic needs are mathematically set operations.
    
    from sys import version, exit
    assert '3' == version[0]
    from random import choice
    from string import ascii_uppercase
    
    dictionary=['ABRUPT','BLITZ','BUCCANEER','CROISSANT','BEFUDDLE','GIZMO','HAIKU','JOVIAL','NUMB','SQUAWK','THE','  MAGIC','ARTIST','TRAVEL','NOWADAYS','ITALIAN','MOUSTACHE','GLOOMY','STARTLED','AMBIGUOUS','GREEN','N  UMBER','HANDYMAN','RATCHET','BOILED','ENCRUSTED','AROUND','CHIMPANZEE','PARAKEET','BOOTSTRAPS']
    
    difficulty=str(input("would you like an easy, medium, or hard word?  "))
    
    # REMOVED LOOP
    if difficulty == "easy":
        word = choice(dictionary[21:31])
    elif difficulty=="medium":
        word = choice(dictionary[11:21])
    elif difficulty=="hard":
        word = choice(dictionary[0:11])
    else:                                     # INSERTED ERROR TRAP
        print('run the program again, next time choose one of easy medium hard .')
        exit(1)
    
    wordLength=len(word)
    wrongGuesses=''                           # should be a set
    rightGuesses=''                           # should be a set
    guesses=wordLength*[' _ ']
    alreadyGuessed=''                         # should be a set
    maxWrong=6
    # DISCARDED GAMEPOINTS
    
    def lost(mistakes,maxWrong):
        return maxWrong <= len(mistakes)
    
    def won(rightGuesses,word):
        return set(rightGuesses) == set(word)
    
    # YOU HAD USED gameOver AS IF ... NEVER MIND.  LEARN TO DEFINE AND CALL FUNCTIONS
    def gameOver(rightGuesses,word,mistakes,maxWrong):
        '''
            return lost or won.  How simple.
        '''
        return lost(mistakes,maxWrong) or won(rightGuesses,word)
    
    # REMOVED UNUSED DEFINITION
    # whatLevel(difficulty):
    
    def printRules(maxWrong, wordLength):  # IMPROVED
        print('Guess the',wordLength,'letter word,')
        print('one letter at a time.  Guess the word')
        print('before making',maxWrong,'erros to win.')
    
    def getGuess():
        # print   # REMOVED INEFFECTIVE PYTHON 3 STATEMENT
        guess = input("Guess a letter: ")  # REPAIRED PROMPT
        # REMOVED INEFFECTIVE STATEMENTS
        # guess.strip() # str.strip() returns a new value, does not change the immutable string
        # guess.upper() # str.upper() same as .strip()
        print()
        return guess   .strip().upper()  # INSERTED YOUR INTENT
    
    printRules(maxWrong, wordLength)
    
    # REMOVED NEXT GAME OPTION.
    
    while not gameOver(rightGuesses,word,wrongGuesses,maxWrong):  # CALL THIS FUNCTION
        letter = getGuess()
        if len(letter)==1 and letter in ascii_uppercase:
            if alreadyGuessed.find(letter) != -1:
                print ("You already picked", letter)
            else:
                alreadyGuessed += letter
                firsttryWord = word.find(letter)
                if firsttryWord == -1:
                    wrongGuesses += letter
                    print("Oops! ",letter,"is not in the word.")
                else:
                    print("Yes! ",letter,"is in the word!")
                    rightGuesses += letter
                    for instances in range(wordLength):
                        if letter == word[instances]:
                            guesses[instances]=letter
        else:
            print("Please guess a single alphabetical letter!")
        print(''.join(guesses))
        print ("Missed Letters: ", wrongGuesses)
    
    if won(rightGuesses,word):
        print('You win!')
    else:
        print ("You lose!")
        print("The word was "+word)
    
    # REMAINDER OF PROGRAM REMOVED
    
    # To program for multiple games encapsulate this into a function,
    # which returns a score or whatever,
    # and call the function in a loop.
    [code]Code tags[/code] are essential for python code and Makefiles!

IMN logo majestic logo threadwatch logo seochat tools logo