-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathwordGuessing.py
More file actions
93 lines (68 loc) · 2.12 KB
/
wordGuessing.py
File metadata and controls
93 lines (68 loc) · 2.12 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
87
88
89
90
91
92
93
from random import choice
WRONG_LOSE = 6
def hideLetters(answer, guesses):
"""
Hides unguessed letters in the answer with '*', leaves punctuation and spaces visible.
Returns:
str: The answer with unguessed letters hidden.
"""
result = ""
for char in answer:
if char.upper() in guesses.upper() or not char.isalpha():
result += char # Show the letter or punctuation
else:
result += "*" # Hide the letter
return result
def askPlayer(clue, display, guesses, wrong):
"""
Asks the player for a letter and ensures valid input.
Returns:
str: A valid letter guessed by the player.
"""
while True:
print(f"Clue: {clue}")
print(f"Puzzle: {display}")
print(f"Guessed letters: {guesses}")
print(f"Wrong guesses: {wrong}/{WRONG_LOSE}")
guess = input("Guess a letter: ").strip().upper()
if len(guess) == 1 and guess.isalpha():
if guess in guesses.upper():
print(f"You already guessed '{guess}'. Try again.")
else:
return guess
else:
print("Invalid input. Please guess a single letter.")
def puzzle():
"""
Randomly choose a clue and answer for the puzzle.
Returns:
tuple: A tuple containing the clue and the answer.
"""
puzzles = [
("Sports Team", "TORONTO RAPTORS"),
("80's Movie", "RAIDERS OF THE LOST ARK"),
("Canadian City", "HALIFAX, NOVA SCOTIA")
]
return choice(puzzles)
def play():
# Initialize the game
clue, answer = puzzle()
guesses = ""
wrong = 0
display = hideLetters(answer, guesses)
# Letter guessing loop
while wrong < WRONG_LOSE and "*" in display:
letter = askPlayer(clue, display, guesses, wrong)
guesses += letter
if letter in answer:
display = hideLetters(answer, guesses)
else:
wrong += 1
# End the game
if wrong == WRONG_LOSE:
print("You lose!")
else:
print("You win!")
print(answer)
# Play the game!
play()