import random
import time
import json
import os
import sys
# Animated text function
def type_text(text, delay=0.03):
for char in text:
print(char, end='', flush=True)
time.sleep(delay)
print()
# Loading animation
def loading_animation(duration=2):
chars = ['|', '/', '-', '\\']
end_time = time.time() + duration
idx = 0
while time.time() < end_time:
print(f"\rLoading {chars[idx % len(chars)]}", end='', flush=True)
time.sleep(0.2)
idx += 1
print('\r' + ' '*20, end='\r') # Clear the line after loading
# Countdown before guess
def countdown(seconds=3):
for i in range(seconds, 0, -1):
print(f"Get ready... {i}")
time.sleep(1)
print()
# Save/load leaderboard
LEADERBOARD_FILE = "leaderboard.json"
def load_leaderboard():
if os.path.exists(LEADERBOARD_FILE):
with open(LEADERBOARD_FILE, "r") as f:
return json.load(f)
return {}
def save_leaderboard(data):
with open(LEADERBOARD_FILE, "w") as f:
json.dump(data, f, indent=4)
def guess_the_number():
leaderboard = load_leaderboard()
type_text("🎮 Welcome to Guess the Number!", 0.05)
loading_animation()
name = input("Enter your name: ")
type_text("Choose difficulty: (1) Easy (2) Medium (3) Hard", 0.05)
difficulty = input("Enter 1, 2, or 3: ")
if difficulty == "1":
max_num = 10
attempts_allowed = 5
elif difficulty == "2":
max_num = 50
attempts_allowed = 7
elif difficulty == "3":
max_num = 100
attempts_allowed = 10
else:
type_text("Invalid choice, defaulting to Easy.", 0.05)
max_num = 10
attempts_allowed = 5
number = random.randint(1, max_num)
attempts = 0
type_text(f"Guess a number between 1 and {max_num}", 0.05)
while attempts < attempts_allowed:
countdown(2)
try:
guess = int(input(f"Attempt {attempts + 1}/{attempts_allowed}: "))
attempts += 1
if guess == number:
type_text(f"🎉 Correct! You got it in {attempts} tries.", 0.05)
leaderboard[name] = leaderboard.get(name, 0) + 1
save_leaderboard(leaderboard)
break
elif guess < number:
type_text("🔻 Too low! 📉", 0.05)
else:
type_text("🔺 Too high! 📈", 0.05)
except ValueError:
type_text("🚫 Please enter a valid number.", 0.05)
else:
type_text(f"❌ You're out of attempts! The number was {number}.", 0.05)
type_text("\n🏆 Leaderboard:", 0.05)
sorted_lb = sorted(leaderboard.items(), key=lambda x: x[1], reverse=True)
for player, score in sorted_lb[:5]:
print(f"{player}: {score} win(s)")
guess_the_number()