1. Introduction
This tutorial will walk you through creating a simple Hangman game in Python. Hangman is a word-guessing game in which a player tries to guess a word by suggesting letters within a certain number of guesses. This game is a fun way to practice Python basics such as loops, conditionals, and working with strings and lists.
2. Program Steps
1. Define a list of words for the player to guess.
2. Select a word randomly for the player to guess.
3. Take the player's guess input.
4. Check if the guess is correct and reveal the letter if it is.
5. Keep track of the number of tries and end the game if the player runs out of guesses or guesses the word.
3. Code Program
import random
# Step 1: Define a list of words
words = ['python', 'java', 'kotlin', 'javascript']
# Step 2: Randomly select a word
word = random.choice(words)
guessed = "_" * len(word)
word_list = list(guessed)
tries = 6
print("H A N G M A N\n")
while tries > 0 and "_" in word_list:
print("".join(word_list))
guess = input("Input a letter: ")
# Step 3: Process the player's guess
if guess in word:
# Step 4: Reveal the letter if the guess is correct
for i in range(len(word)):
if word[i] == guess:
word_list[i] = guess
else:
print("That letter doesn't appear in the word.")
tries -= 1
if "_" not in word_list:
print("You guessed the word!")
print("You survived!")
else:
print("You lost!")
Output:
H A N G M A N ______ Input a letter: p p_____ Input a letter: y py___n Input a letter: t pyt__n Input a letter: h python You guessed the word! You survived!
Explanation:
1. The game starts by defining a list of words, one of which will be randomly selected for the player to guess.
2. The selected word is kept secret, and a variable guessed is used to display its current guessed state. Initially, all underscores represent each letter.
3. The player is prompted to input a letter as their guess for the word.
4. If the guessed letter is in the word, the script reveals it by updating the guessed variable to show the correctly guessed letters in their correct positions.
5. The player has a limited number of tries (6 in this example) to guess all the letters in the word. Each incorrect guess reduces the number of tries by one.
6. The game continues until the player either guesses all the letters of the word or runs out of tries. If all the letters are guessed before the tries run out, the player wins. If the player runs out of tries before guessing the word, they lose.
Comments
Post a Comment
Leave Comment