
Python 猜数字小游戏开发 🎮
欢迎来到今天的博客!我们将一起开发一个简单而有趣的Python猜数字小游戏。这个小游戏不仅适合编程新手学习基础概念,还能让你体验到编程的乐趣。通过本教程,你将学会如何使用Python处理用户输入、生成随机数、实现循环和条件判断等核心编程技能。准备好了吗?让我们开始吧!🚀
游戏概述
猜数字游戏的核心规则非常简单:程序会随机生成一个数字,玩家需要尝试猜测这个数字。每次猜测后,程序会给出提示,告诉玩家猜的数字是太大了还是太小了,直到玩家猜中为止。我们将逐步构建这个游戏,并添加一些额外的功能来提升用户体验。
开发环境设置
首先,确保你已经安装了Python。推荐使用Python 3.6或更高版本。你可以从Python官方网站下载并安装最新版本。安装完成后,打开你的代码编辑器(如VS Code、PyCharm或任何你喜欢的编辑器),创建一个新的Python文件,命名为guess_the_number.py。
基础版本:猜数字游戏
让我们从最基础的版本开始。这个版本会生成一个1到100之间的随机数,并允许玩家反复猜测,直到猜中为止。
import random
def guess_the_number():
number = random.randint(1, 100)
attempts = 0
print("欢迎来到猜数字游戏!我已经想了一个1到100之间的数字,试试猜出来吧!😊")
while True:
try:
guess = int(input("请输入你的猜测: "))
attempts += 1
if guess < number:
print("太小了!再试一次。⬇️")
elif guess > number:
print("太大了!再试一次。⬆️")
else:
print(f"恭喜你!你猜对了!🎉 你用了{attempts}次尝试。")
break
except ValueError:
print("请输入一个有效的整数!⚠️")
if __name__ == "__main__":
guess_the_number()
这个基础版本包含了游戏的核心逻辑。我们使用random.randint来生成随机数,用一个while循环持续接受用户输入,并通过条件判断给出反馈。异常处理确保如果用户输入非数字内容,程序不会崩溃,而是提示用户重新输入。
添加游戏难度选择
为了让游戏更有趣,我们可以添加难度选择功能,允许玩家选择不同的数字范围,从而改变游戏的挑战性。我们将提供三个难度级别:简单(1-50)、中等(1-100)和困难(1-200)。
import random
def choose_difficulty():
print("请选择难度级别:")
print("1: 简单 (1-50) 🌱")
print("2: 中等 (1-100) 🌿")
print("3: 困难 (1-200) 🌳")
while True:
try:
choice = int(input("输入数字选择(1/2/3): "))
if choice == 1:
return 1, 50
elif choice == 2:
return 1, 100
elif choice == 3:
return 1, 200
else:
print("无效选择,请重新输入。")
except ValueError:
print("请输入一个有效的整数!")
def guess_the_number():
low, high = choose_difficulty()
number = random.randint(low, high)
attempts = 0
print(f"游戏开始!我想了一个{low}到{high}之间的数字。")
while True:
try:
guess = int(input("你的猜测: "))
attempts += 1
if guess < number:
print("太小了!⬇️")
elif guess > number:
print("太大了!⬆️")
else:
print(f"太棒了!你猜对了!🎉 尝试次数: {attempts}")
break
except ValueError:
print("请输入数字!⚠️")
if __name__ == "__main__":
guess_the_number()
现在,玩家可以在游戏开始前选择难度,这通过choose_difficulty函数实现。该函数返回所选难度的数字范围下限和上限,用于生成随机数和提示玩家。
添加猜测次数限制
为了增加挑战性,我们可以为每个难度级别设置猜测次数限制。如果玩家在限定次数内没有猜中,游戏结束。
import random
def choose_difficulty():
print("请选择难度级别:")
print("1: 简单 (1-50, 最多10次尝试) 🌱")
print("2: 中等 (1-100, 最多7次尝试) 🌿")
print("3: 困难 (1-200, 最多5次尝试) 🌳")
while True:
try:
choice = int(input("输入数字选择(1/2/3): "))
if choice == 1:
return 1, 50, 10
elif choice == 2:
return 1, 100, 7
elif choice == 3:
return 1, 200, 5
else:
print("无效选择,请重新输入。")
except ValueError:
print("请输入一个有效的整数!")
def guess_the_number():
low, high, max_attempts = choose_difficulty()
number = random.randint(low, high)
attempts = 0
print(f"游戏开始!我想了一个{low}到{high}之间的数字。你有{max_attempts}次尝试机会。")
while attempts < max_attempts:
try:
guess = int(input("你的猜测: "))
attempts += 1
if guess < number:
print("太小了!⬇️")
elif guess > number:
print("太大了!⬆️")
else:
print(f"恭喜!你猜对了!🎉 用了{attempts}次尝试。")
return
remaining = max_attempts - attempts
if remaining > 0:
print(f"还剩{remaining}次尝试。")
else:
print("没有尝试次数了!")
except ValueError:
print("请输入数字!⚠️")
print(f"游戏结束!数字是{number}。下次好运!😢")
if __name__ == "__main__":
guess_the_number()
在这个版本中,我们为每个难度级别设置了最大尝试次数。游戏会在玩家用尽尝试次数后结束,并揭示正确答案。这通过修改while循环条件和添加剩余次数提示来实现。
使用Mermaid图表可视化游戏流程
为了更清晰地展示游戏的逻辑流程,下面使用Mermaid绘制一个流程图。这有助于理解游戏中的各个步骤和决策点。
这个流程图概括了游戏的主要步骤:从开始到选择难度,生成随机数,然后循环处理猜测,直到猜中或尝试次数用尽。每个决策点(如猜测是否正确或大小)都引导至相应的操作。
添加得分系统
让我们进一步扩展游戏,添加一个简单的得分系统。得分基于尝试次数和难度级别:尝试次数越少,难度越高,得分就越高。
import random
def choose_difficulty():
print("请选择难度级别:")
print("1: 简单 (1-50, 最多10次尝试) 🌱")
print("2: 中等 (1-100, 最多7次尝试) 🌿")
print("3: 困难 (1-200, 最多5次尝试) 🌳")
while True:
try:
choice = int(input("输入数字选择(1/2/3): "))
if choice == 1:
return 1, 50, 10, 1
elif choice == 2:
return 1, 100, 7, 2
elif choice == 3:
return 1, 200, 5, 3
else:
print("无效选择,请重新输入。")
except ValueError:
print("请输入一个有效的整数!")
def calculate_score(attempts, max_attempts, difficulty_factor):
base_score = (max_attempts - attempts + 1) * 10
return base_score * difficulty_factor
def guess_the_number():
low, high, max_attempts, difficulty_factor = choose_difficulty()
number = random.randint(low, high)
attempts = 0
print(f"游戏开始!数字范围: {low}到{high}. 最大尝试次数: {max_attempts}.")
while attempts < max_attempts:
try:
guess = int(input("你的猜测: "))
attempts += 1
if guess < number:
print("太小了!⬇️")
elif guess > number:
print("太大了!⬆️")
else:
score = calculate_score(attempts, max_attempts, difficulty_factor)
print(f"太棒了!猜对了!🎉 尝试次数: {attempts}. 得分: {score}")
return
remaining = max_attempts - attempts
if remaining > 0:
print(f"还剩{remaining}次尝试。")
except ValueError:
print("请输入数字!⚠️")
print(f"游戏结束!数字是{number}. 得分: 0 😢")
if __name__ == "__main__":
guess_the_number()
在这里,choose_difficulty现在返回一个难度因子(1 for easy, 2 for medium, 3 for hard)。calculate_score函数根据尝试次数、最大尝试次数和难度因子计算得分。得分公式鼓励玩家用更少的尝试完成更高难度的游戏。
添加游戏循环和多次游玩
最后,我们可以让玩家在单次游戏结束后选择是否再玩一次,从而持续享受游戏乐趣。
import random
def choose_difficulty():
print("请选择难度级别:")
print("1: 简单 (1-50, 最多10次尝试) 🌱")
print("2: 中等 (1-100, 最多7次尝试) 🌿")
print("3: 困难 (1-200, 最多5次尝试) 🌳")
while True:
try:
choice = int(input("输入数字选择(1/2/3): "))
if choice == 1:
return 1, 50, 10, 1
elif choice == 2:
return 1, 100, 7, 2
elif choice == 3:
return 1, 200, 5, 3
else:
print("无效选择,请重新输入。")
except ValueError:
print("请输入一个有效的整数!")
def calculate_score(attempts, max_attempts, difficulty_factor):
base_score = (max_attempts - attempts + 1) * 10
return base_score * difficulty_factor
def play_game():
low, high, max_attempts, difficulty_factor = choose_difficulty()
number = random.randint(low, high)
attempts = 0
print(f"游戏开始!数字范围: {low}到{high}. 最大尝试次数: {max_attempts}.")
while attempts < max_attempts:
try:
guess = int(input("你的猜测: "))
attempts += 1
if guess < number:
print("太小了!⬇️")
elif guess > number:
print("太大了!⬆️")
else:
score = calculate_score(attempts, max_attempts, difficulty_factor)
print(f"恭喜!猜对了!🎉 尝试次数: {attempts}. 得分: {score}")
return score
remaining = max_attempts - attempts
if remaining > 0:
print(f"还剩{remaining}次尝试。")
except ValueError:
print("请输入数字!⚠️")
print(f"游戏结束!数字是{number}. 得分: 0 😢")
return 0
def main():
total_score = 0
games_played = 0
print("欢迎来到猜数字游戏!")
while True:
score = play_game()
total_score += score
games_played += 1
print(f"当前总得分: {total_score} after {games_played} games.")
play_again = input("想再玩一次吗?(y/n): ").lower()
if play_again != 'y':
print("谢谢游玩!再见!👋")
break
if __name__ == "__main__":
main()
现在,游戏包含一个main函数,它管理游戏循环、累计总分和游戏次数。每次游戏后,玩家可以选择继续或退出。这通过一个外部while循环和用户输入处理实现。
总结
通过这个项目,我们一步步构建了一个功能丰富的猜数字游戏。我们从基础版本开始,逐步添加了难度选择、尝试次数限制、得分系统和游戏循环。在这个过程中,你学习了Python的随机数生成、用户输入处理、循环、条件语句、函数定义和简单算法。
编程就像这个游戏一样:从简单开始,逐步挑战更复杂的问题,每次迭代都带来新的乐趣和成就感。希望这个教程激发了你的编程兴趣!如果你对Python入门有更多兴趣,可以参考Python官方文档或在线教程网站如Real Python。
继续编码,保持好奇,享受创造的过程!💻✨

983

被折叠的 条评论
为什么被折叠?



