Python Programming
 
Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
User Name:
Password:
Remember me

The Shed is going Social! Join us on FaceBook and Twitter and chime in on the conversation.

Go Back   Dev Shed ForumsProgramming LanguagesPython Programming

Reply
Add This Thread To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 
Thread Tools Search this Thread Rate Thread Display Modes
 
Unread Dev Shed Forums Sponsor:
  #1  
Old December 5th, 2012, 06:12 AM
rainbowStitch rainbowStitch is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Dec 2012
Posts: 2 rainbowStitch User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 36 m 49 sec
Reputation 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','N  UMBER','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()

Reply With Quote
  #2  
Old December 5th, 2012, 06:34 AM
leeuw01 leeuw01 is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Dec 2012
Posts: 16 leeuw01 User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 5 h 51 m 50 sec
Reputation Power: 0
http://inventwithpython.com/chapter9.html

Here you can find a complete tutorial on how to make a hangman game

Reply With Quote
  #3  
Old December 5th, 2012, 06:37 AM
rainbowStitch rainbowStitch is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Dec 2012
Posts: 2 rainbowStitch User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 36 m 49 sec
Reputation Power: 0
thanks

...

Reply With Quote
  #4  
Old December 5th, 2012, 07:06 AM
leeuw01 leeuw01 is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Dec 2012
Posts: 16 leeuw01 User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 5 h 51 m 50 sec
Reputation 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.

Reply With Quote
  #5  
Old December 5th, 2012, 11:14 AM
b49P23TIvg's Avatar
b49P23TIvg b49P23TIvg is offline
Contributing User
Dev Shed Loyal (3000 - 3499 posts)
 
Join Date: Aug 2011
Posts: 3,389 b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level) 
Time spent in forums: 1 Month 2 Weeks 3 Days 14 h 22 m 25 sec
Reputation Power: 383
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!

Reply With Quote
Reply

Viewing: Dev Shed ForumsProgramming LanguagesPython Programming > Can't get my hangman program to exit loop to win!

Developer Shed Advertisers and Affiliates



Thread Tools  Search this Thread 
Search this Thread:

Advanced Search
Display Modes  Rate This Thread 
Rate This Thread:


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
View Your Warnings | New Posts | Latest News | Latest Threads | Shoutbox
Forum Jump

Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
  
 


Powered by: vBulletin Version 3.0.5
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.

© 2003-2013 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap