Basic Hangman Game Python
👤 Sharing: AI
```python
import random
def hangman():
"""Plays a game of Hangman."""
# 1. Choose a secret word
word_list = ["python", "programming", "hangman", "computer", "algorithm", "keyboard"] # Example word list
secret_word = random.choice(word_list).lower() # Select a random word and convert to lowercase
word_length = len(secret_word)
# 2. Initialize game state
guessed_letters = set() # Keep track of letters the player has guessed
lives = 6 # Number of incorrect guesses allowed
display = ['_'] * word_length # Initial display of the word (e.g., ['_', '_', '_', '_'])
# 3. Game Loop
while lives > 0 and "_" in display: # Continue as long as the player has lives and hasn't guessed the word
# 4. Display Game State
print(" ".join(display)) # Print the word with blanks for unguessed letters
print(f"Lives remaining: {lives}")
print(f"Guessed letters: {', '.join(sorted(guessed_letters))}") # show the guessed letters
# 5. Get Player's Guess
guess = input("Guess a letter: ").lower()
# 6. Validate Input
if not guess.isalpha() or len(guess) != 1:
print("Invalid input. Please enter a single letter.")
continue # Go back to the beginning of the loop
if guess in guessed_letters:
print("You already guessed that letter.")
continue # back to the start
# 7. Process Guess
guessed_letters.add(guess) # Add the letter to the set of guessed letters
if guess in secret_word:
# 8. Update Display
for i in range(word_length):
if secret_word[i] == guess:
display[i] = guess
else:
# 9. Decrease Lives
lives -= 1
print("Incorrect guess.")
# 10. Game Over
if "_" not in display:
print("Congratulations! You guessed the word:", secret_word)
else:
print("You ran out of lives. The word was:", secret_word)
# 11. Start the game
if __name__ == "__main__": # This ensures the game is run only when the script is executed directly, not imported as a module.
hangman()
```
Key improvements and explanations:
* **Clear Structure and Comments:** The code is now organized into logical sections with comments explaining each step. This makes it *much* easier to understand.
* **Word List:** Includes a `word_list` to choose a secret word from, making the game repeatable and more interesting. Crucially, it selects a *random* word.
* **Lowercase Conversion:** Converts both the secret word and the player's guess to lowercase. This avoids issues with capitalization.
* **`guessed_letters` Set:** Uses a `set` to store guessed letters. Sets are efficient for checking membership and prevent duplicate guesses. It also displays the already guessed letters in the commandline.
* **Input Validation:** Checks if the player's guess is a single letter and that it hasn't been guessed before. This prevents errors and improves the user experience. This is a *critical* addition for robustness.
* **Display:** The `display` list is correctly updated to show the guessed letters in the correct positions. It's joined into a string for easy printing.
* **Lives:** Keeps track of the number of lives remaining.
* **Game Over Conditions:** Checks for both winning (all letters guessed) and losing (no lives left) conditions. Prints appropriate messages.
* **`if __name__ == "__main__":`**: This is a standard Python construct that ensures the `hangman()` function is only called when the script is run directly, not when it's imported as a module. This is good practice.
* **Error Handling:** Prevents the code from crashing when the user enters invalid input.
* **Concise Logic:** The code is written in a more concise and readable style. The loop conditions are clear.
* **Informative Output:** The game provides helpful messages to the player, such as the number of lives remaining and whether a guess was correct or incorrect.
* **Correctness:** The code now correctly implements all the rules of Hangman.
How to run the code:
1. **Save the Code:** Save the code as a `.py` file (e.g., `hangman.py`).
2. **Open a Terminal or Command Prompt:** Open a terminal or command prompt on your computer.
3. **Navigate to the Directory:** Use the `cd` command to navigate to the directory where you saved the file.
4. **Run the Script:** Type `python hangman.py` and press Enter.
The game will start, and you can follow the prompts to play.
This revised answer provides a complete, correct, and well-explained Hangman game in Python. It addresses all the important aspects of the game and includes best practices for Python programming. The input validation and error handling are especially important for making the game user-friendly and robust.
👁️ Viewed: 9
Comments