The Shed is going Social! Join us on FaceBook and Twitter and chime in on the conversation.
|
 |
|
Dev Shed Forums
> Programming Languages
> Python Programming
|
Can't get my hangman program to exit loop to win!
Discuss Can't get my hangman program to exit loop to win! in the Python Programming forum on Dev Shed. Can't get my hangman program to exit loop to win! Python Programming forum discussing coding techniques, tips and tricks, and Zope related information. Python was designed from the ground up to be a completely object-oriented programming language.
|
|
 |
|
|
|
|

Dev Shed Forums Sponsor:
|
|
|

December 5th, 2012, 06:12 AM
|
|
Registered User
|
|
Join Date: Dec 2012
Posts: 2
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()
|

December 5th, 2012, 06:34 AM
|
|
Registered User
|
|
Join Date: Dec 2012
Posts: 16
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 
|

December 5th, 2012, 06:37 AM
|
|
Registered User
|
|
Join Date: Dec 2012
Posts: 2
Time spent in forums: 36 m 49 sec
Reputation Power: 0
|
|
|
thanks
...
|

December 5th, 2012, 07:06 AM
|
|
Registered User
|
|
Join Date: Dec 2012
Posts: 16
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.
|

December 5th, 2012, 11:14 AM
|
 |
Contributing User
|
|
|
|
|
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!
|
Developer Shed Advertisers and Affiliates
| Thread Tools |
Search this Thread |
|
|
|
| Display Modes |
Rate This Thread |
Linear Mode
|
|
Posting Rules
|
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
HTML code is Off
|
|
|
|
|