Skip to content

Commit b552370

Browse files
authored
refactored to class
1 parent b2a0eb6 commit b552370

File tree

1 file changed

+113
-83
lines changed

1 file changed

+113
-83
lines changed

number_guessing.py

Lines changed: 113 additions & 83 deletions
Original file line numberDiff line numberDiff line change
@@ -1,99 +1,129 @@
11
import random
22
import validation
3+
import utility
34

4-
def GenerateRandomNumber(lowValue, highValue):
5+
class NumberGuessingGame:
56
"""
6-
Generates a random integer between the specified low and high values (inclusive).
7+
A class that implements a number guessing game.
78
8-
Args:
9-
lowValue (int): The lower bound of the range.
10-
highValue (int): The upper bound of the range.
11-
12-
Returns:
13-
int: A random integer between lowValue and highValue.
9+
The game generates a random number within a specified range,
10+
and the player has a limited number of turns to guess the number.
11+
The game provides feedback on whether the guess is too high or too low.
1412
"""
15-
return random.randint(lowValue, highValue)
13+
def __init__(self):
14+
self.__number_to_guess=0
15+
self.__max_turns=10
16+
self.__game_history=[]
17+
self.__low_range=1
18+
self.__high_range=100
19+
self.GameIntro()
1620

17-
def SetNumberRange():
18-
"""
19-
Allows the user to set the range of numbers for the guessing game.
21+
def GameIntro(self):
22+
"""Displays introductory message to player when launching game for the first time"""
23+
24+
print("Welcome to the number guessing game!")
25+
print(f"I will generate a random number between a range and you will have {self.__max_turns} turns to guess it.")
26+
print("The default range will be from 1 to 100.")
27+
28+
def SetNumberRange(self):
29+
"""
30+
Allows the player to manually set the number range for the guessing game.
2031
21-
If the user chooses to set the range manually, they are prompted to enter
22-
a low value and a high value. Input is validated to ensure the high value
23-
is greater than the low value.
32+
If the player chooses to set the range manually, they are prompted to enter
33+
the low and high values for the range. Input validation is performed to
34+
ensure that the high value is greater than the low value. If the player
35+
chooses not to set the range manually, the default range of 1 to 100 is used.
36+
"""
37+
38+
manualRange = validation.ValidateUserInput("Would you like to set the number range? If not, range will be 1-100 (y/n): ",('y','n'))
39+
lowValue=1
40+
highValue=0
41+
42+
if manualRange=='y':
43+
while lowValue > highValue:
44+
lowValue=validation.GetIntValue("Enter number for the low value: ",max=100000)
45+
highValue=validation.GetIntValue("Enter number for the high value: ",min=lowValue+1,max=1000000)
2446

25-
If the user chooses not to set the range manually, the range defaults to 1-100.
47+
if highValue < lowValue:
48+
print("The high value must be greater than the low value.")
49+
else:
50+
lowValue=1
51+
highValue=100
2652

27-
Returns:
28-
tuple: A tuple containing the low value and high value of the number range.
29-
"""
30-
manualRange = validation.ValidateUserInput("Would you like to set the number range? If not, range will be 1-100 (y/n): ",('y','n'))
31-
lowValue=0
32-
highValue=-1
53+
self.__low_range=lowValue
54+
self.__high_range=highValue
55+
56+
def GenerateRandomNumber(self):
57+
"""
58+
Generates a random integer between the specified low and high values (inclusive).
59+
"""
60+
self.__number_to_guess=random.randint(self.__low_range, self.__high_range)
3361

34-
if manualRange=='y':
35-
while lowValue > highValue:
36-
lowValue=validation.GetIntValue("Enter number for the low value: ")
37-
highValue=validation.GetIntValue("Enter number for the high value: ")
62+
def PlayRound(self):
63+
"""
64+
Initiates and manages a single round of the number guessing game.
3865
39-
if highValue < lowValue:
40-
print("The high value must be greater than the low value.")
41-
else:
42-
lowValue=1
43-
highValue=100
66+
The player is prompted to enter their guess, and the game provides
67+
feedback on whether the guess is too high or too low. The number of
68+
attempts is tracked, and the game continues until the player guesses
69+
the correct number or runs out of turns.
70+
"""
71+
72+
count=0
73+
maxTurns=self.__max_turns
74+
while maxTurns > 0:
75+
if maxTurns == 1:
76+
print("This is your last guess!")
77+
else:
78+
print(f"You have {maxTurns} guesses remaining")
79+
userGuess=validation.GetIntValue("What is your guess? ")
80+
count += 1
81+
if userGuess == self.__number_to_guess:
82+
print(f"You got it! The number was {self.__number_to_guess}")
83+
print(f"You guessed the number in {count} attempts.")
84+
self.__game_history.append(count)
85+
break
86+
maxTurns -= 1
87+
if maxTurns == 0:
88+
print(f"Oh no! You ran out of guesses. The correct number was {self.__number_to_guess}")
89+
break
90+
if userGuess < self.__number_to_guess:
91+
print("Too low! Try again")
92+
else:
93+
print("Too high! Try again")
4494

45-
return (lowValue, highValue)
95+
def PlayGame(self):
96+
"""
97+
This method contains the core game logic for the number guessing game.
4698
47-
def PlayGame(numberToGuess, maxTurns, gameHistory):
48-
"""
49-
Plays a number guessing game with the user.
50-
51-
The function takes the number to guess, the maximum number of turns allowed,
52-
and a list to store the game history. It prompts the user for guesses,
53-
provides feedback on whether the guess is too high or too low, and tracks
54-
the number of attempts. The game continues until the user guesses correctly
55-
or runs out of turns.
56-
57-
Args:
58-
numberToGuess (int): The secret number the user is trying to guess.
59-
maxTurns (int): The maximum number of guesses the user is allowed.
60-
gameHistory (list): A list to store the number of attempts taken in each game.
61-
"""
62-
count=0
63-
while maxTurns > 0:
64-
if maxTurns == 1:
65-
print("This is your last guess!")
99+
It sets the number range, generates a random number, and manages the
100+
game rounds until the player chooses to stop playing. After each game,
101+
it displays statistics to the player.
102+
"""
103+
104+
play_again='y'
105+
while play_again=='y':
106+
self.SetNumberRange()
107+
self.GenerateRandomNumber()
108+
self.PlayRound()
109+
play_again=validation.ValidateUserInput("Would you like to play again? (y/n): ",('y','n'))
110+
utility.clear_console()
66111
else:
67-
print(f"You have {maxTurns} guesses remaining")
68-
userGuess=validation.GetIntValue("What is your guess? ")
69-
count += 1
70-
if userGuess == numberToGuess:
71-
print(f"You got it! The number was {numberToGuess}")
72-
print(f"You guessed the number in {count} attempts.")
73-
gameHistory.append(count)
74-
break
75-
maxTurns -= 1
76-
if maxTurns == 0:
77-
print(f"Oh no! You ran out of guesses. The correct number was {numberToGuess}")
78-
break
79-
if userGuess < numberToGuess:
80-
print("Too low! Try again")
81-
else:
82-
print("Too high! Try again")
83-
84-
gameHistory=[]
85-
maxTurns=10
86-
playAgain='y'
87-
while playAgain=='y':
88-
low,high=SetNumberRange()
89-
numberToGuess=GenerateRandomNumber(low, high)
90-
PlayGame(numberToGuess,maxTurns,gameHistory)
91-
playAgain=validation.ValidateUserInput("Would you like to play again? (y/n): ",('y','n'))
112+
self.DisplayStats()
92113

93-
print("Thanks for playing!")
94-
if len(gameHistory) == 1:
95-
endText="time"
96-
else:
97-
endText="times"
98-
print(f"You played {len(gameHistory)} {endText}.")
99-
print(f"Your best attempt was {min(gameHistory)} guesses.")
114+
def DisplayStats(self):
115+
"""
116+
Displays game statistics to the player, including the number of times played
117+
and the best (minimum) number of guesses achieved in a single game.
118+
"""
119+
120+
print("Thanks for playing!")
121+
if len(self.__game_history) == 1:
122+
endText="time"
123+
else:
124+
endText="times"
125+
print(f"You played {len(self.__game_history)} {endText}.")
126+
print(f"Your best attempt was {min(self.__game_history)} guesses.")
127+
128+
my_game=NumberGuessingGame()
129+
my_game.PlayGame()

0 commit comments

Comments
 (0)