猜数字游戏介绍
猜数字游戏是编程初学者练习基础语法的经典项目。这个Python游戏会随机生成1到10之间的数字,玩家有3次机会猜出正确数字。
游戏规则:
- 程序随机生成1-10之间的整数
- 玩家有3次猜测机会
- 每次猜测后提示数字是太大还是太小
- 猜中数字则获胜,用完机会则游戏结束
代码实现步骤
1. 导入随机模块
首先导入Python的random模块来生成随机数:
import random
2. 生成随机数
使用randint函数生成1到10之间的随机整数:
secret_number = random.randint(1, 10)
3. 设置游戏参数
定义最大尝试次数和初始化计数器:
max_attempts = 3
attempts = 0
4. 创建游戏主循环
使用while循环控制游戏流程:
while attempts < max_attempts:
# 获取玩家输入
try:
guess = int(input(f"\n请输入1-10之间的数字(还剩{max_attempts - attempts}次机会): "))
except ValueError:
print("请输入有效的整数!")
continue
# 检查数字范围
if guess < 1 or guess > 10:
print("请输入1到10之间的数字!")
continue
attempts += 1
# 判断猜测结果
if guess == secret_number:
print(f"恭喜!你猜对了!数字就是{secret_number}!")
break
elif guess < secret_number:
print("猜小了,再试试!")
else:
print("猜大了,再试试!")
else:
print(f"\n游戏结束!正确数字是{secret_number}。")
完整游戏代码
下面是完整的猜数字游戏代码:
import random
print("欢迎来到猜数字游戏!")
print("我已经想好了一个1到10之间的整数,你有3次机会猜出它。")
secret_number = random.randint(1, 10)
max_attempts = 3
attempts = 0
while attempts < max_attempts:
try:
guess = int(input(f"\n请输入1-10之间的数字(还剩{max_attempts - attempts}次机会): "))
except ValueError:
print("请输入有效的整数!")
continue
if guess < 1 or guess > 10:
print("请输入1到10之间的数字!")
continue
attempts += 1
if guess == secret_number:
print(f"恭喜!你猜对了!数字就是{secret_number}!")
break
elif guess < secret_number:
print("猜小了,再试试!")
else:
print("猜大了,再试试!")
else:
print(f"\n很遗憾,你没有猜对。正确数字是{secret_number}。")
print("\n游戏结束,欢迎再来挑战!")
发表评论