Python Forum
Hangman Game Buy a Vowel
Thread Rating:
  • 1 Vote(s) - 4 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Hangman Game Buy a Vowel
#1
I created this code for a Hangman game where you can buy a Vowel, but for some reason it keeps subtracting from every letter even if you don't buy a vowel. I just want the players to have to spend 3 to buy a vowel with a bank of 10
import random
HANGMAN_PICS = ['''
   +---+
       |
       |
       |
      ===''', '''
   +---+
    O   |
        |
        |
       ===''', '''
    +---+
    O   |
    |   |
        |
       ===''', '''
    +---+
    O   |
   /|   |
        |
       ===''', '''
    +---+
    O   |
   /|\  |
        |
       ===''', '''
    +---+
    O   |
   /|\  |
   /    |
       ===''', '''
    +---+
    O   |
   /|\  |
   / \  |
       ===''']
words = 'ant baboon badger bat bear beaver camel cat clam cobra cougar coyote crow deer dog donkey duck eagle ferret fox frog goat goose hawk lion lizard llama mole monkey moose mouse mule newt otter owl panda parrot pigeon python rabbit ram rat raven rhino salmon seal shark sheep skunk sloth snake spider stork swan tiger toad trout turkey turtle weasel whale wolf wombat zebra'.split()

def getRandomWord(wordList):
     # This function returns a random string from the passed list of strings.
      wordIndex = random.randint(0, len(wordList) - 1)
      return wordList[wordIndex]
 
def displayBoard(missedLetters, correctLetters, secretWord):
     print(HANGMAN_PICS[len(missedLetters)])
     print()
     print("You can buy a vowel for $3 with a balance $10")
     print('Missed letters:', end=' ')
     for letter in missedLetters:
         print(letter, end=' ')
     print()
 
     blanks = '_' * len(secretWord)

     for i in range(len(secretWord)): # Replace blanks with correctly guessed letters.
         if secretWord[i] in correctLetters:
              blanks = blanks[:i] + secretWord[i] + blanks[i+1:]
 
     for letter in blanks: # Show the secret word with spaces in between each letter.
          print(letter, end=' ')
     print()
def money():
      if balance > 3:
            balance - 3
      #elif :
      
def getGuess(alreadyGuessed):
     # Returns the letter the player entered. This function makes sure the player entered a single letter and not something else.
      global balance
      while True:
            print('Guess a letter.')
            guess = input()
            guess = guess.lower()
            if len(guess) != 1:
                  print('Please enter a single letter.')
            elif guess in alreadyGuessed:
                  print('You have already guessed that letter. Choose again.')
            elif guess not in 'abcdefghijklmnopqrstuvwxyz':
                  print('Please enter a LETTER.')
            else:
                  if  ("a", "e","i","o","u"):
                        if balance > 3:
                              balance = balance - 3
                              print(balance)
                        return guess
                  else :
                        print('you lost')

def playAgain():
     # This function returns True if the player wants to play again; otherwise, it returns False.
     print('Do you want to play again? (yes or no)')
     return input().lower().startswith('y')


print('H A N G M A N')
missedLetters = ''
correctLetters = ''
secretWord = getRandomWord(words)
gameIsDone = False
balance = 10
while True:
     displayBoard(missedLetters, correctLetters, secretWord)
     # Let the player enter a letter.
     guess = getGuess(missedLetters + correctLetters)
     if guess in secretWord:
         correctLetters = correctLetters + guess
         # Check if the player has won.
         foundAllLetters = True
         for i in range(len(secretWord)):
             if secretWord[i] not in correctLetters:
                 foundAllLetters = False
                 break
         if foundAllLetters:
             print('Yes! The secret word is "' + secretWord +
                   '"! You have won!')
             gameIsDone = True
     else:
         missedLetters = missedLetters + guess
         # Check if player has guessed too many times and lost.
         if len(missedLetters) == len(HANGMAN_PICS) - 1:
             displayBoard(missedLetters, correctLetters, secretWord)
             print('You have run out of guesses!\nAfter ' +
                   str(len(missedLetters)) + ' missed guesses and ' +
                   str(len(correctLetters)) + ' correct guesses, the word was "' + secretWord + '"')
             gameIsDone = True
     # Ask the player if they want to play again (but only if the game is done).
     if gameIsDone:
         if playAgain():
             missedLetters = ''
             correctLetters = ''
             gameIsDone = False
             secretWord = getRandomWord(words)
         else:
             break
Please Help
Gribouillis write Feb-06-2025, 09:09 AM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Reply
#2
What is the logic for buying a vowel? Do you have to pay 3 for each vowel, or only if the vowel is not in the word? If you have to buy each vowel it makes cougar and pigeon very difficult words. One wrong vowel and you lose! If you only pay for a vowel that isn't in the word, that is no penalty at all.

if ("a", "e","i","o","u"): does not check if the letter is a vowel. The condition for the if statement is a non-empty tuple, so it will always evaluate to True, and the body of the if statement will always run. You want to test if guess in ‘aeiou’,

This is an error that prevents your code from running:
def money():
      if balance > 3:
            balance - 3
balance must be declared as a global variable in the function. Or delete the function since it isn’t used.

I would restructure the code for repeated game play. Put all the hangman game code in a function and the main code should call the play game and then ask if you want to play again.
def play_game()
    """Play game of hangman."""
    ...

while True:
    play_game()
    if not input('Play again (y/n)? ').lower().startswith('y'):
        break
Take a look at the random module. There are functions in random that can do this:
def getRandomWord(wordList):
     # This function returns a random string from the passed list of strings.
      wordIndex = random.randint(0, len(wordList) - 1)
      return wordList[wordIndex]
Don't write code that was already written for you.

Python coding convention is to use snake_case for variable and function names, not camelCase. Indenting should be 4 spaces not 5. 2 blank lines should follow your imports and each function.
Following conventions makes it easier for others to read your code. Learning the conventions will make it easier for you to read code that follows those conventions.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Homework Hangman Game jagr29 3 3,733 Jan-20-2022, 10:38 PM
Last Post: deanhystad
  Hangman game jsirota 2 4,500 Nov-06-2017, 06:39 PM
Last Post: gruntfutuk
  Hangman-Game (German code) .. Unkreatief 1 4,367 Mar-22-2017, 10:30 AM
Last Post: Kebap

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020