A command-line guessing game with difficulty levels, a hint system, score tracking, and a high-score leaderboard saved to a file.
Pick a random number and let the player guess until they get it.
import random
def play(difficulty='medium'):
limits = {'easy': (1,20,10), 'medium': (1,100,7), 'hard': (1,500,5)}
low, high, max_guesses = limits.get(difficulty, limits['medium'])
secret = random.randint(low, high)
attempts = 0
print(f"\nGuess the number between {low} and {high}. You have {max_guesses} tries.\n")
while attempts < max_guesses:
remaining = max_guesses - attempts
try:
guess = int(input(f"Attempt {attempts+1}/{max_guesses} — Your guess: "))
except ValueError:
print("Enter a valid number.")
continue
attempts += 1
if guess == secret:
score = (max_guesses - attempts + 1) * 10
print(f"\n✅ Correct! You got it in {attempts} attempt(s). Score: {score}")
return score
elif abs(guess - secret) <= 10:
print("🔥 Very hot!" if guess < secret else "🔥 Very hot! Go lower.")
elif abs(guess - secret) <= 25:
direction = "higher" if guess < secret else "lower"
print(f"♨️ Warm — go {direction}.")
else:
direction = "higher" if guess < secret else "lower"
print(f"🧊 Cold — go {direction}.")
print(f"\n❌ Out of tries! The number was {secret}.")
return 0
play('medium')
Let the player choose difficulty and save high scores to a JSON file.
import json, os
SCORES_FILE = 'scores.json'
def load_scores():
if os.path.exists(SCORES_FILE):
with open(SCORES_FILE) as f:
return json.load(f)
return []
def save_score(name, score, difficulty):
scores = load_scores()
scores.append({'name': name, 'score': score, 'difficulty': difficulty})
scores.sort(key=lambda x: x['score'], reverse=True)
with open(SCORES_FILE, 'w') as f:
json.dump(scores[:10], f, indent=2) # keep top 10
def show_leaderboard():
scores = load_scores()
if not scores:
print("No scores yet!"); return
print("\n🏆 Leaderboard")
print(f"{'Rank':<5} {'Name':<15} {'Score':<8} Difficulty")
print("-" * 40)
for i, s in enumerate(scores[:10], 1):
print(f"{i:<5} {s['name']:<15} {s['score']:<8} {s['difficulty']}")
def main():
print("🎯 Number Guessing Game")
name = input("Your name: ").strip() or "Player"
print("Difficulty: 1) Easy 2) Medium 3) Hard")
choice = input("Choice (default 2): ").strip()
diff = {'1':'easy','3':'hard'}.get(choice, 'medium')
score = play(diff)
if score > 0:
save_score(name, score, diff)
print("Score saved!")
show_leaderboard()
main()
In 50 lines you covered random numbers, loops, conditionals, file I/O, JSON, and sorting — the foundation of almost every Python program.
Spotted a bug, broken code, or something that doesn't look right? Tell us what's off and we'll fix it.