-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
71 lines (54 loc) · 2.04 KB
/
Copy pathmain.py
File metadata and controls
71 lines (54 loc) · 2.04 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
from random import randint, sample
from math import log2, ceil
class NumberGame:
def __init__(self, start: int, end: int):
self.start = start
self.end = end
self._answer = randint(start, end)
self._chances = ceil(log2(abs(end - start)))
# log2 gives max guesses needed using binary search strategy
def guess(self, num: int) -> tuple[str, bool]:
"""Returns (message, keep_playing)."""
if num == self._answer:
return "Wow! You nailed it! 🎉", False
self._chances -= 1
if self._chances == 0:
return f"YOU LOST! The number was {self._answer}.", False
hint = "LOWER" if num > self._answer else "HIGHER"
return f"TRY AGAIN! Number is a bit {hint} than {num}. You have {self._chances} chances left...", True
def play_round():
while True:
try:
choice = input("Do you want to select the range or shall i choose for you? [Y = me]: ").lower()
if choice == 'y':
start, end = sorted(sample(range(0, 10000), 2))
else:
start = int(input("Start: "))
end = int(input("End: "))
if abs(end - start) < 4:
print("Range too small, Lets try again!")
continue
print(f"Guessing between {start} and {end}.")
break
except ValueError:
print("Numbers only please.")
game = NumberGame(start, end)
playing = True
while playing:
try:
num = int(input("Your guess: "))
except ValueError:
print("Enter a valid number.")
continue
if not (start <= num <= end):
print(f"Guessing out of the range, huh? Try within {start}–{end}!")
continue
message, playing = game.guess(num)
print(message)
if __name__ == "__main__":
while True:
play_round()
again = input("Wanna play again? [Y/N]: ").upper()
if again != 'Y':
break
print("Thanks for playing. BYE!")