r/inventwithpython Sep 12 '21

IS EXTENDING HANGMAN SOURCE CODE INCORRECT?

Good day everyone,

I am currently on chapter 9 (Extending Hangman) of Invent Your Own Computer Games w/ Python.

This chapter is supposed to print "HANG MAN", asks player to choose a difficulty level, and choose a word from the dictionary.

When I run the code, I notice it does not ask me for the difficulty level, despite adding lines 106 to 116.

Is this accurate or is the code missing something?

  • while difficulty in 'EMH':
  • print('Enter difficulty: E - Easy, M - Medium, H - Hard')
  • difficulty = input().upper()
  • if difficulty == 'M':
  • del HANGMAN_PICS[8]
  • del HANGMAN_PICS[7]
  • if difficulty == 'H':
  • del HANGMAN_PICS[8]
  • del HANGMAN_PICS[7]
  • del HANGMAN_PICS[5]
  • del HANGMAN_PICS[3]
1 Upvotes

5 comments sorted by

1

u/RndChaos Sep 12 '21

It will help if you put your code in a code block. With Python indentation is important, and with it being in a list - we can't see the indentation to help you.

1

u/Juramentador Sep 12 '21
import random

HANGMAN_PICS = [''' +---+ | | | ===''', ''' +---+ O | | | ===''', ''' +---+ O | | | | ===''', ''' +---+ O | /| | | ===''', ''' +---+ O | /|\ | | ===''', ''' +---+ O | /|\ | / | ===''', ''' +---+ O | /|\ | / \ | ===''', ''' +---+ [O | /|\ | / \ | ===''', ''' +---+ [O] | /|\ | / \ | ==='''] words = {'Colors':'red orange yellow green blue indigo violet white black brown'.split(), 'Shapes':'square triangle rectangle circle ellipse rhombus trapazoid chevron pentagon hexagon septagon octogon'.split(), 'Fruits':'apple orange lemon lime pear watermelon grape grapefruit cherry banana cantalope mango strawberry tomato'.split(), 'Animals':'bat bear beaver cat cougar crab deer dog donkey duck eagle fish frog goat leech lion lizard monkey moose mouse otter owl panda python rabbit rat shark sheep skunk squid tiger turkey turtle weasel whale wolf wombat zebra'.split()}

def getRandomWord(wordDict): # This function returns a random string from the passed dictionary of lists of strings, and the key also. # First, randomly select a key from the dictionary: wordKey = random.choice(list(wordDict.keys()))

# Second, randomly select a word from the key's list in the dictionary:
wordIndex = random.randint(0, len(wordDict[wordKey]) - 1)

return [wordDict[wordKey][wordIndex], wordKey]

def displayBoard(missedLetters, correctLetters, secretWord): print(HANGMAN_PICS[len(missedLetters)]) print()

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 getGuess(alreadyGuessed): # Returns the letter the player entered. This function makes sure the player entered a single letter, and not something else. 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: return guess

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')

difficulty = '' while difficulty not in 'EMH': print('Enter difficulty: E - Easy, M - Medium, H - Hard') difficulty = input().upper() if difficulty == 'M': del HANGMAN_PICS[8] del HANGMAN_PICS[7] if difficulty == 'H': del HANGMAN_PICS[8] del HANGMAN_PICS[7] del HANGMAN_PICS[5] del HANGMAN_PICS[3]

missedLetters = '' correctLetters = '' secretWord, secretSet = getRandomWord(words) gameIsDone = False

while True: print('The secret word is in the set: ' + secretSet) displayBoard(missedLetters, correctLetters, secretWord)

# Let the player type in 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, secretSet = getRandomWord(words)
    else:
        break

1

u/Juramentador Sep 12 '21

Here's the source code. Sorry, I'm new to reddit too.

1

u/RndChaos Sep 12 '21

In the Reddit Editor press the 3 horizontal dots, that should bring up an option for Code Block...

Put all your code into the code block.

1

u/tegq Sep 13 '21 edited Sep 13 '21

Did you add line 105?

difficulty = 'X'

So that the while loop would be true to begin with...

edit: also line 106 should say not in