-4

I'm currently using Python to create a hangman game but I can't quite figure out how to get it working. In the game, there is a list of fourteen words, and one word from the list will be selected at random to be the word that the player has to guess. The player will then have to keep entering letters until they get them all, or until they run out of guesses. At the start of the game, the word will be displayed with each letter represented by an underscore. But I have no idea how to get the letters to reveal themselves in place of the corresponding underscore as the player guesses them. This is the basic setup I have:

print(stage1)
if (mystery == "spongebob" or mystery == "squidward" or mystery == "pineapple" or      mystery == "jellyfish"):
print("_ _ _ _ _ _ _ _ _")
print("Your word has 9 letters in it")
elif (mystery == "plankton"):
print("_ _ _ _ _ _ _ _")
print("Your word has 8 letters in it")
elif (mystery == "patrick"):
print("_ _ _ _ _ _ _")
print("Your word has 7 letters in it")
elif (mystery == "island"):
print("_ _ _ _ _ _")
print("Your word has 6 letters in it")
elif (mystery == "sandy" or mystery == "larry" or mystery == "beach"):
print("_ _ _ _ _")
print("Your word has 5 letters in it")
elif (mystery == "gary" or mystery == "tiki" or mystery == "rock" or mystery == "sand"):
print("_ _ _ _")
print("Your word has 4 letters in it")
print(mystery)

letter = str(input("Enter a letter you'd like to guess: "))

So how do I get the underscores to be replaced by letters as they are guessed?

Kara
  • 6,115
  • 16
  • 50
  • 57
user3002784
  • 15
  • 1
  • 4

3 Answers3

1

By the way, don't keep writing print statements for each instance, just do this:

>>> mystery = 'hippopotamus'
>>> print '_ '*len(mystery)
_ _ _ _ _ _ _ _ _ _ _ _ 

But you also want to store the underscores in a variable, so that you can change and print them later. So do this:

>>> mystery = 'hippopotamus'
>>> fake = '_ '*len(mystery)
>>> print fake
_ _ _ _ _ _ _ _ _ _ _ _ 

Your next step is to take input. In my opinion, do not use str(input()), use raw_input. It is just a habit, because if you enter a number, it becomes '1', not 1.

>>> guess = raw_input("Enter a letter you'd like to guess: ")
Enter a letter you'd like to guess: p

Now to check if the letter is in the mystery. Do not use index to check, because if there is more than one instance with the letter, it will only iterate over the first instance. See this for more information.

>>> fake = list(fake)  #This will convert fake to a list, so that we can access and change it.
>>> for k in range(0, len(mystery)):  #For statement to loop over the answer (not really over the answer, but the numerical index of the answer)
...    if guess == mystery[k]  #If the guess is in the answer, 
...        fake[k] = guess    #change the fake to represent that, EACH TIME IT OCCURS
>>> print ''.join(fake)  #converts from list to string
_ _ p p _ p _ _ _ _ _ _
Community
  • 1
  • 1
A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76
1
n="no"
while 'no':
    n = input("do you want to play? ")
    if n.strip() == 'yes':
        break

    """Hangman
Standard game of Hangman. A word is chosen at random from a list and the
user must guess the word letter by letter before running out of attempts."""

import random

def main():
    welcome = ['Welcome to Hangman! A word will be chosen at random and',
               'you must try to guess the word correctly letter by letter',
               'before you run out of attempts and your execution is complete.. no pressure'
               ]

    for line in welcome:
        print(line, sep='\n')



    play_again = True

    while play_again:


        words = ["hangman", "chairs", "backpack", "bodywash", "clothing",
                 "computer", "python", "program", "glasses", "sweatshirt",
                 "sweatpants", "mattress", "friends", "clocks", "biology",
                 "algebra", "suitcase", "knives", "ninjas", "shampoo"
                 ]

        chosen_word = random.choice(words).lower()
        player_guess = None
        guessed_letters = [] 
        word_guessed = []
        for letter in chosen_word:
            word_guessed.append("-")
        joined_word = None

        HANGMAN = (
"""
-----
|   |
|
|
|
|
|
|
|
--------
""",
"""
-----
|   |
|   0
|
|
|
|
|
|
--------
""",
"""
-----
|   |
|   0
|  -+-
|
|
|
|
|
--------
""",
"""
-----
|   |
|   0
| /-+-
|
|
|
|
|
--------
""",
"""
-----
|   |
|   0
| /-+-\ 
|
|
|
|
|
--------
""",
"""
-----
|   |
|   0
| /-+-\ 
|   | 
|
|
|
|
--------
""",
"""
-----
|   |
|   0
| /-+-\ 
|   | 
|   | 
|
|
|
--------
""",
"""
-----
|   |
|   0
| /-+-\ 
|   | 
|   | 
|  |
|
|
--------
""",
"""
-----
|   |
|   0
| /-+-\ 
|   | 
|   | 
|  | 
|  | 
|
--------
""",
"""
-----
|   |
|   0
| /-+-\ 
|   | 
|   | 
|  | | 
|  | 
|
--------
""",
"""
-----
|   |
|   0
| /-+-\ 
|   | 
|   | 
|  | | 
|  | | 
|
--------
""")

        print(HANGMAN[0])
        attempts = len(HANGMAN) - 1


        while (attempts != 0 and "-" in word_guessed):
            print(("\nYou have {} attempts remaining").format(attempts))
            joined_word = "".join(word_guessed)
            print(joined_word)

            try:
                player_guess = str(input("\nPlease select a letter between A-Z" + "\n> ")).lower()
            except: # check valid input
                print("That is not valid input. Please try again.")
                continue                
            else: 
                if not player_guess.isalpha():
                    print("That is not a letter. Please try again.")
                    continue
                elif len(player_guess) > 1:
                    print("That is more than one letter. Please try again.")
                    continue
                elif player_guess in guessed_letters: # check it letter hasn't been guessed already
                    print("You have already guessed that letter. Please try again.")
                    continue
                else:
                    pass

            guessed_letters.append(player_guess)

            for letter in range(len(chosen_word)):
                if player_guess == chosen_word[letter]:
                    word_guessed[letter] = player_guess

            if player_guess not in chosen_word:
                attempts -= 1
                print(HANGMAN[(len(HANGMAN) - 1) - attempts])

        if "-" not in word_guessed:
            print(("\nCongratulations! {} was the word").format(chosen_word))
        else:
            print(("Unlucky! The word was {}.").format(chosen_word))

        print("Would you like to play again?")

        response = input("> ").lower()
        if response not in ("yes", "y"):
            play_again = False

if __name__ == "__main__":
    main()

This code plays a hangman game, feel free to change the words though. It took me ages to code this at school last year, it was part of my year 10 assessment.

Enjoy playing hangman.:)

Another way to get some codes is to look at other peoples. Their code can give you some inspiration and you can use several people's codes to create a program.

0

Here's something you could do, actually.

import random

print("Welcome to hangman!!")
words = []
with open('sowpods.txt', 'r') as f:
    line = f.readline().strip()
    words.append(line)
    while line:
        line = f.readline().strip()
        words.append(line)

random_index = random.randint(0, len(words))

word = words[random_index]
guessed = "_" * len(word)
word = list(word)
guessed = list(guessed)
lstGuessed = []
letter = input("guess letter: ")
while True:
    if letter.upper() in lstGuessed:
        letter = ''
        print("Already guessed!!")
    elif letter.upper() in word:
        index = word.index(letter.upper())
        guessed[index] = letter.upper()
        word[index] = '_'
    else:
        print(''.join(guessed))
        if letter is not '':
            lstGuessed.append(letter.upper())
        letter = input("guess letter: ")

    if '_' not in guessed:
        print("You won!!")
        break
ChrisF
  • 134,786
  • 31
  • 255
  • 325