Number Guessing Game
Source: Dev.to
Overview
We built a Number Guessing Game where the system generates a random number and the player tries to guess it with hints like “higher” or “lower.” Difficulty levels change the range of numbers:
- Easy: 1–20
- Medium: 1–50
- Hard: 1–100
The game also demonstrates concepts such as pseudo‑randomness (using a seed, typically the system time), careful user‑input handling, and a simple leaderboard that stores and displays player performance.
Implementation
import random
leaderboard = []
def get_difficulty():
print("1. Easy (1-20)")
print("2. Medium (1-50)")
print("3. Hard (1-100)")
while True:
try:
choice = int(input("Choose difficulty: "))
if choice == 1:
return "easy", 20, 10
elif choice == 2:
return "medium", 50, 8
elif choice == 3:
return "hard", 100, 5
else:
print("Invalid choice")
except:
print("Enter a valid number")
def play_game():
name = input("Enter your name: ")
difficulty, max_range, attempts = get_difficulty()
secret_number = random.randint(1, max_range)
print(f"\nGuess number between 1 and {max_range}")
for attempt in range(1, attempts + 1):
try:
guess = int(input(f"Attempt {attempt}: "))
except:
print("Invalid input")
continue
if guess == secret_number:
print("Correct!")
leaderboard.append({
"name": name,
"difficulty": difficulty,
"attempts": attempt
})
return
elif guess < secret_number:
print("Higher")
else:
print("Lower")
print(f"Game Over! Number was {secret_number}")
def view_leaderboard():
if not leaderboard:
print("No data yet")
return
difficulty_order = {"easy": 1, "medium": 2, "hard": 3}
sorted_data = sorted(
leaderboard,
key=lambda x: (difficulty_order[x["difficulty"]], x["attempts"])
)
print("\nLeaderboard:")
for p in sorted_data:
print(p["name"], p["difficulty"], p["attempts"])
def main():
while True:
print("\n1. Play Game")
print("2. View Leaderboard")
print("3. Exit")
choice = input("Enter choice: ")
if choice == "1":
play_game()
elif choice == "2":
view_leaderboard()
elif choice == "3":
break
else:
print("Invalid choice")
main()Security
Communication between systems occurs over HTTPS using encryption, ensuring that data cannot be intercepted by attackers.
Takeaways
This session showed how a simple game can help us understand important concepts such as concurrency, locking, database design, randomness, and security. Even small programs can lay a strong foundation for understanding real‑world systems.