-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproj.py
More file actions
86 lines (62 loc) · 2.39 KB
/
Copy pathproj.py
File metadata and controls
86 lines (62 loc) · 2.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
"""
CodeAlpha Python Programming Internship
Task 1: Hangman Game
A simple text-based Hangman game where the player guesses a word
one letter at a time.
Key Concepts Used: random, while loop, if-else, strings, lists
"""
import random
# A small list of 5 predefined words
WORDS = ["python", "hangman", "developer", "internship", "programming"]
MAX_ATTEMPTS = 6
def choose_word():
"""Randomly pick a word from the predefined list."""
return random.choice(WORDS)
def display_word(word, guessed_letters):
"""Show the word with guessed letters revealed and others as underscores."""
return " ".join(letter if letter in guessed_letters else "_" for letter in word)
def play_hangman():
word = choose_word()
guessed_letters = []
wrong_attempts = 0
print("=" * 40)
print("Welcome to Hangman!")
print(f"You have {MAX_ATTEMPTS} incorrect guesses allowed.")
print("=" * 40)
while wrong_attempts < MAX_ATTEMPTS:
print("\nWord: " + display_word(word, guessed_letters))
print(f"Wrong attempts: {wrong_attempts}/{MAX_ATTEMPTS}")
print(f"Guessed letters: {', '.join(guessed_letters) if guessed_letters else 'None'}")
guess = input("Guess a letter: ").lower().strip()
# Basic input validation
if len(guess) != 1 or not guess.isalpha():
print("Please enter a single valid letter.")
continue
if guess in guessed_letters:
print(f"You already guessed '{guess}'. Try a different letter.")
continue
guessed_letters.append(guess)
if guess in word:
print(f"Good guess! '{guess}' is in the word.")
else:
wrong_attempts += 1
print(f"Wrong guess! '{guess}' is not in the word.")
# Check win condition
if all(letter in guessed_letters for letter in word):
print("\n" + "=" * 40)
print(f"Congratulations! You guessed the word: {word}")
print("=" * 40)
return
# Loss condition
print("\n" + "=" * 40)
print("Game Over! You've run out of attempts.")
print(f"The word was: {word}")
print("=" * 40)
def main():
play_again = "y"
while play_again == "y":
play_hangman()
play_again = input("\nPlay again? (y/n): ").lower().strip()
print("Thanks for playing Hangman! Goodbye.")
if __name__ == "__main__":
main()