数字猜谜游戏
发布: (2026年3月26日 GMT+8 12:41)
3 分钟阅读
原文: Dev.to
Source: Dev.to
概览
我们构建了一个数字猜谜游戏,系统会生成一个随机数,玩家通过“更大”或“更小”等提示来猜测。难度等级会改变数字的范围:
- 简单(Easy): 1–20
- 中等(Medium): 1–50
- 困难(Hard): 1–100
该游戏还演示了伪随机性(使用种子,通常是系统时间)、细致的用户输入处理以及一个简单的排行榜,用于存储和显示玩家的表现。
实现
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()安全性
系统之间的通信通过 HTTPS 使用加密进行,确保数据不会被攻击者拦截。
收获
本次示例展示了一个简单的游戏如何帮助我们理解重要概念,如并发、锁机制、数据库设计、随机性以及安全性。即使是小程序,也能为理解真实世界系统奠定坚实的基础。