Create a word-guessing game in Python
PythonHere is an example to show you the basic game structure in Python. It is a simple word-guessing game in a command-line style. Command-line style games strip away graphical elements, allowing developers to concentrate on game logic and mechanics.
import random
def word_guessing_game():
"""Simulate a word guessing game."""
words = ["python", "programming", "simulation", "algorithm", "developer"]
secret_word = random.choice(words)
guessed_word = ["_"] * len(secret_word)
attempts = 5
print("Welcome to the Word Guessing Game!")
print(" ".join(guessed_word))
while attempts > 0:
guess = input("Guess a letter: ").lower()
if guess in secret_word:
for i, letter in enumerate(secret_word):
if letter == guess:
guessed_word[i] = guess
print("Correct!")
else:
attempts -= 1
print(f"Wrong! You have {attempts} attempts left.")
print(" ".join(guessed_word))
if "_" not in guessed_word:
print("Congratulations! You guessed the word!")
return
print(f"Game over! The word was: {secret_word}")
# Run the game
word_guessing_game()
Code Breakdown
1. Importing Required Modules
import random
- The
random
module is imported to randomly select a word from the list of words.
2. Defining the word_guessing_game
Function
def word_guessing_game():
- This function encapsulates the entire logic of the word-guessing game.
3. Setting Up the Game
words = ["python", "programming", "simulation", "algorithm", "developer"]
secret_word = random.choice(words)
guessed_word = ["_"] * len(secret_word)
attempts = 5
words
: A list of words from which the game randomly selects one.secret_word
: The word randomly chosen from the list usingrandom.choice(words)
.guessed_word
: A list of underscores (_
) representing the letters of thesecret_word
. The length of this list matches the length of thesecret_word
.attempts
: The number of attempts the player has to guess the word. Here, it’s set to 5.
4. Displaying the Initial Game State
print("Welcome to the Word Guessing Game!")
print(" ".join(guessed_word))
- A welcome message is displayed.
- The current state of the
guessed_word
is shown, with underscores representing unguessed letters. For example, if thesecret_word
is "python", the output will be:_ _ _ _ _ _
.
5. Game Loop
while attempts > 0:
- The game runs in a loop as long as the player has attempts remaining (
attempts > 0
).
6. Player Input
guess = input("Guess a letter: ").lower()
- The player is prompted to guess a letter.
- The input is converted to lowercase using
.lower()
to ensure case insensitivity.
7. Checking the Guess
if guess in secret_word:
for i, letter in enumerate(secret_word):
if letter == guess:
guessed_word[i] = guess
print("Correct!")
else:
attempts -= 1
print(f"Wrong! You have {attempts} attempts left.")
-
If the guessed letter is in the
secret_word
:- The code iterates through the
secret_word
usingenumerate
to find all positions where the guessed letter appears. - The corresponding underscores in
guessed_word
are replaced with the guessed letter. - A "Correct!" message is displayed.
- The code iterates through the
-
If the guessed letter is not in the
secret_word
:- The number of attempts is reduced by 1.
- A "Wrong!" message is displayed, along with the remaining attempts.
8. Displaying the Updated Game State
print(" ".join(guessed_word))
- The updated state of
guessed_word
is displayed, showing the correctly guessed letters and underscores for unguessed letters.
9. Checking for Win Condition
if "_" not in guessed_word:
print("Congratulations! You guessed the word!")
return
- If there are no more underscores (
_
) inguessed_word
, it means the player has guessed all the letters correctly. - A "Congratulations!" message is displayed, and the function exits using
return
.
10. Game Over Condition
print(f"Game over! The word was: {secret_word}")
- If the player runs out of attempts (
attempts == 0
), the game ends. - A "Game over!" message is displayed, revealing the
secret_word
.
11. Running the Game
word_guessing_game()
- The
word_guessing_game
function is called to start the game.
Example Gameplay
Scenario:
secret_word
= "algorithm"- Player has 5 attempts.
Gameplay:
Welcome to the Word Guessing Game!
_ _ _ _ _ _ _ _ _
Guess a letter: a
Correct!
a _ _ _ _ _ _ _ _
Guess a letter: l
Correct!
a l _ _ _ _ _ _ _
Guess a letter: g
Correct!
a l g _ _ _ _ _ _
Guess a letter: o
Correct!
a l g o _ _ _ _ _
Guess a letter: m
Correct!
a l g o _ _ _ _ m
Guess a letter: t
Correct!
a l g o _ _ t _ m
Guess a letter: h
Correct!
a l g o _ _ t h m
Guess a letter: i
Correct!
a l g o _ i t h m
Guess a letter: r
Correct!
a l g o r i t h m
Congratulations! You guessed the word!
Key Features of the Game
- Random Word Selection: The game randomly selects a word from a predefined list.
- Dynamic Display: The game updates the display of guessed letters and underscores in real-time.
- Attempts Counter: The player has a limited number of attempts to guess the word.
- Win/Loss Conditions: The game checks if the player has guessed the word or run out of attempts.
How to Customize the Game
- Add More Words: Expand the words list with more words.
- Change Attempts: Modify the attempts variable to increase or decrease the difficulty.
- Add Hints: Provide hints after a certain number of incorrect guesses.
- Case Insensitivity: The game already handles lowercase input, but you can modify it to accept uppercase letters as well.