-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathguess_the_number.py
More file actions
194 lines (130 loc) · 5.5 KB
/
guess_the_number.py
File metadata and controls
194 lines (130 loc) · 5.5 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
import random
def welcome_user():
"""Ask the user to enter their username as part of welcoming
the user to the game.
This is repeated until the user has provided a username to the program.
Prints a greeting message along with the player's username.
"""
while True:
name = input("\n\nEnter your username: ")
if name != "":
print("\n\nWelcome to Guess The Number, " + name)
return name
else:
print("\nUsername Required!")
def validate_input(user_input):
"""Check the user input for a ValueError.
Prints a message when a ValueError occured.
"""
while True:
try:
return int(input(user_input))
except ValueError:
print("\n\nValue must be an integer. \n\nTry again.")
def get_upper_bound():
"""Ask the player to set the number that they want to guess up to.
They may find it difficult to win the game if they set their
upper bound to a larger number.
If they enter anything that is not an integer value,
then a warning message will appear.
The game will ask the user to set a number for their upper bound again.
This will be repeated until the user has entered a valid input.
"""
while True:
guess_number_maximum = validate_input(
"\n\nEnter a number for an upper bound: ")
if guess_number_maximum < 1:
print("\nYour upper bound must be greater than one.")
else:
return guess_number_maximum
def ask_user_yes_no(yes_no_question) -> bool:
"""Simplifies if/else to determine the correct answers from the user input.
Args:
yes_no_question: A string that asks user a yes or no question.
Returns:
True if the user's answer is in CHOICE_YES,
and False otherwise.
Prints a message to the user if their input are not similar
to the ones in CHOICE_YES and CHOICE_NO.
"""
CHOICE_YES = ("yes", 'y')
CHOICE_NO = ("no", 'n')
while True:
user_choice = input(yes_no_question).lower()
if user_choice in CHOICE_YES:
return True
elif user_choice in CHOICE_NO:
return False
else:
print("\nInvalid Input. Try again.")
# Indicate the number of times that the user can guess the number.
GUESS_LIMIT = 3
def play_game(upper_bound, player_name):
"""
Keep count of the number of times it takes the
user to get the correct number.
Increments it by 1 for each attempt by the user.
Sets the starting range of number to 1 with the ending range set
by the user from get_upper_bound function.
The guessing range of number is between 1 and up to the
number that the user has set.
Checks the user's guessed number and prints out a message
to indicate that the guessed number is either too high
or too low than the random number.
Returns True if the user won the game.
Returns False if the user lost the game.
Prints out a winning message once the user have
guessed the number or out of guesses.
"""
guess_count = 0
random_number = random.randint(1, upper_bound)
while True:
user_number = validate_input(
"\n\nGuess the number between 1 and " + str(upper_bound) + ": ")
guess_count += 1
if user_number == random_number:
print(f"\n\n\U0001F44F Congratulation, {player_name}, "
"you guessed the number!\U0001F44F")
count_guess_attempt(guess_count)
return True
elif user_number > random_number:
print("Your guessing number is too high. Try guessing lower.")
else:
print("Your guessing number is too low. Try guessing higher.")
if guess_count >= GUESS_LIMIT:
print(f"\n\nSorry, {player_name}, you lost the game. "
"You ran out of guesses. Better luck next time!")
return False
def count_guess_attempt(guess_attempt):
"""Count the number of times it takes the user to guess the number.
User can only guess the number 3 times.
Prints a message containing the number of times it
took the user to guessed the number.
"""
if guess_attempt == 1:
print(f"\nIt took you {guess_attempt} try to guess the number.\n")
elif guess_attempt == GUESS_LIMIT:
print("\nNice One! You guessed the number on your last try.")
else:
print(f"\nIt took you {guess_attempt} tries to guess the number.\n")
def should_play_again():
"""Call greet_user function to greet the user
when the program first executes.
Starts round of Guess The Number.
Asks the user if they want to play again.
Restarts the program if play_game returns True
and user wants to play again.
Lets the user guess the number again if play_game
returns False and user wants a try again.
Exits the program if the user does not want to continue with the program.
"""
user_name = welcome_user()
may_change_upper_limit = True
while True:
if may_change_upper_limit:
upper_limit = get_upper_bound()
may_change_upper_limit = play_game(upper_limit, user_name)
if not ask_user_yes_no("\n\nWould you like to play again? (Y/N): "):
print("\n\nExiting game...\n\n")
break
should_play_again()