-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumber guessing Game (project) .py
More file actions
194 lines (167 loc) · 6.69 KB
/
Number guessing Game (project) .py
File metadata and controls
194 lines (167 loc) · 6.69 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
import math
from datetime import datetime
# User class to handle signup and login
class User:
def __init__(self, username):
self.username = username
@staticmethod
def signup():
print("\n--- Signup Time! Let's make you official! ---")
while True:
username = input("Pick a cool username: ").strip()
if User._user_exists(username):
print("Oops! That username’s taken. Try another one!")
else:
password = input("Set a secret password: ").strip()
with open("users.txt", "a") as f:
f.write(f"{username},{password}\n")
print(f"Sweet! Account created for {username}.\n")
return User(username)
@staticmethod
def login():
print("\n--- Welcome back! Time to prove who you are! ---")
while True:
username = input("Username: ").strip()
password = input("Password: ").strip()
if User._validate_credentials(username, password):
print(f"Alright {username}, you’re in!\n")
return User(username)
else:
print("Nope! Wrong username or password. Try again.\n")
@staticmethod
def _user_exists(username):
try:
with open("users.txt", "r") as f:
for line in f:
if line.strip().split(",")[0] == username:
return True
except FileNotFoundError:
return False
return False
@staticmethod
def _validate_credentials(username, password):
try:
with open("users.txt", "r") as f:
for line in f:
u, p = line.strip().split(",")
if u == username and p == password:
return True
except FileNotFoundError:
return False
return False
# Leaderboard class to save and show scores
class Leaderboard:
def __init__(self):
self.scores = self._load_scores()
def _load_scores(self):
scores = {}
try:
with open("leaderboard.txt", "r") as f:
for line in f:
username, score, timestamp = line.strip().split(",")
if username in scores:
scores[username].append((int(score), timestamp))
else:
scores[username] = [(int(score), timestamp)]
except FileNotFoundError:
pass
return scores
def add_score(self, username, score):
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open("leaderboard.txt", "a") as f:
f.write(f"{username},{score},{timestamp}\n")
if username in self.scores:
self.scores[username].append((score, timestamp))
else:
self.scores[username] = [(score, timestamp)]
def display(self):
print("\n--- Leaderboard Time! Who’s the champ? ---")
if not self.scores:
print("No scores yet. Time to make your mark!")
return
for user, records in self.scores.items():
total_score = sum(score for score, _ in records)
rounds = len(records)
print(f"{user}: Total Score = {total_score}, Rounds Played = {rounds}")
print()
# Game class with guessing logic
class NumberGuessingGame:
def __init__(self, user, leaderboard):
self.user = user
self.leaderboard = leaderboard
def play(self):
while True:
print("\n--- Set Your Game! Let’s get those numbers right! ---")
while True:
try:
minimum = int(input("Enter the smallest number you want to guess: "))
maximum = int(input("Enter the biggest number you want to guess: "))
if minimum >= maximum:
print("Hey! Smallest number has to be less than the biggest. Try again.")
continue
break
except ValueError:
print("Oops! That’s not a number. Try again.")
while True:
try:
total_attempts = int(input("How many tries do you want? Make it count! "))
if total_attempts <= 0:
print("You gotta have at least one try, duh!")
continue
break
except ValueError:
print("Numbers only, please!")
random_number = random.randint(minimum, maximum)
total_entries = 0
wrong_guess_count = 0
print(f"\nGame on! You’ve got {total_attempts} attempts. Don’t mess it up!")
while total_attempts > 0:
try:
guess = int(input(f"Your guess (between {minimum} and {maximum}): "))
except ValueError:
print("Numbers, please!")
continue
total_entries += 1
if guess > random_number:
print("Too high!")
wrong_guess_count += 1
elif guess < random_number:
print("Too low!")
wrong_guess_count += 1
else:
print("Boom! You nailed it!")
break
total_attempts -= 1
if guess != random_number:
print(f"Game over! The magic number was {random_number}.")
score = math.ceil(total_entries - wrong_guess_count + (maximum - minimum)/10)
print("\n--- Round Recap ---")
print(f"Total guesses: {total_entries}")
print(f"Wrong guesses: {wrong_guess_count}")
print(f"Score this round: {score}")
self.leaderboard.add_score(self.user.username, score)
self.leaderboard.display()
again = input("Wanna play again? (yes/no): ").lower()
if again != 'yes':
print("Thanks for playing! You rocked it!")
break
else:
print("Alright, another round coming up!\n")
# Entry point
def main():
print("Welcome to the Number Guessing Game! Let’s get started!")
user = None
while not user:
action = input("Login or signup? (login/signup): ").lower()
if action == "login":
user = User.login()
elif action == "signup":
user = User.signup()
else:
print("Please type 'login' or 'signup' to continue.")
leaderboard = Leaderboard()
game = NumberGuessingGame(user, leaderboard)
game.play()
if __name__ == "__main__":
main()