we moved to building a Number Guessing Game. 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, such as 1–20 for easy, 1–50 for medium, and 1–100 for hard.
Another important concept was randomness. Computers do not generate truly random numbers; they use pseudo-random algorithms based on a seed value. If the seed is the same, the generated sequence will also be the same. Usually, system time is used as the seed to make it appear random.
We also handled user input carefully by converting it into the correct type and validating it to avoid errors. Then we introduced a leaderboard system to store and display player performance.
Below is the implementation of the Number Guessing Game with a simple leaderboard and sorting:
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()
Finally, we touched on security. Communication between systems happens over HTTPS using encryption, ensuring that data cannot be intercepted by attackers.
Overall, this session showed how a simple game can help us understand important concepts like concurrency, locking, database design, randomness, and security. It made me realize that even small programs can build a strong foundation for understanding real-world systems.
Top comments (0)