hangman algorithm python code example
Example 1: python hangman
import random
word_list = ["insert", "your", "words", "in", "this", "python", "list"]
def get_word(word_list):
word = random.choice(word_list)
return word.upper()
def play(word):
word_completion = "_" * len(word)
guessed = False
guessed_letters = []
guessed_words = []
tries = 6
print("Let's play Hangman")
print(display_hangman(tries))
print(word_completion)
print("\n")
while not guessed and tries > 0:
guess = input("guess a letter or word: ").upper()
if len(guess) == 1 and guess.isalpha():
if guess in guessed_letters:
print("you already tried", guess, "!")
elif guess not in word:
print(guess, "isn't in the word :(")
tries -= 1
guessed_letters.append(guess)
else:
print("Nice one,", guess, "is in the word!")
guessed_letters.append(guess)
word_as_list = list(word_completion)
indices = [i for i, letter in enumerate(word) if letter == guess]
for index in indices:
word_as_list[index] = guess
word_completion = "".join(word_as_list)
if "_" not in word_completion:
guessed = True
elif len(guess) == len(word) and guess.isalpha():
if guess in guessed_words:
print("You already tried ", guess, "!")
elif guess != word:
print(guess, " ist nicht das Wort :(")
tries -= 1
guessed_words.append(guess)
else:
guessed = True
word_completion = word
else:
print("invalid input")
print(display_hangman(tries))
print(word_completion)
print("\n")
if guessed:
print("Good Job, you guessed the word!")
else:
print("I'm sorry, but you ran out of tries. The word was " + word + ". Maybe next time!")
def display_hangman(tries):
stages = [ """
--------
| |
| O
| \\|/
| |
| / \\
-
""",
"""
--------
| |
| O
| \\|/
| |
| /
-
""",
"""
--------
| |
| O
| \\|/
| |
|
-
""",
"""
--------
| |
| O
| \\|
| |
|
-
""",
"""
--------
| |
| O
| |
| |
|
-
""",
"""
--------
| |
| O
|
|
|
-
""",
"""
--------
| |
|
|
|
|
-
"""
]
return stages[tries]
def main():
word = get_word(word_list)
play(word)
while input("Again? (Y/N) ").upper() == "Y":
word = get_word(word_list)
play(word)
if __name__ == "__main__":
main()
Example 2: Write the program to implement Hangman game.
import time
name = input("What is your name? ")
print("Hello, " + name, "Time to play hangman!")
print("")
time.sleep(1)
print("Start guessing...")
time.sleep(0.5)
word = "secret"
guesses = ''
turns = 10
while turns > 0:
failed = 0
for char in word:
if char in guesses:
print(char)
else:
print("_")
failed += 1
if failed == 0:
print("You won")
break
print('')
guess = input("guess a character:")
guesses += guess
if guess not in word:
turns -= 1
print("Wrong")
print("You have", + turns, 'more guesses')
if turns == 0:
print("You Lose")