猜数游戏(Python)

一、实验要求:

(1)在游戏开始时,随机生成一个1~100之间的整数。

(2)在游戏中,玩家有10次机会猜数。如果10次都没有猜中,则游戏失败;否则,游戏成功。

(3)在每一次猜数之后,如果未猜中,应提示猜大了还是猜小了,并提示下一次猜数的上下限。

二、测试用例:

|------------|-------------|------------|
| 测试用例编号 | 测试 | 预期测试结果 |
| 用例1 | 在9次之内猜中 | 游戏成功 |
| 用例2 | 在第10次猜中 | 游戏成功 |
| 用例3 | 猜范围外的数字 | 提示范围 |
| 用例4 | 猜范围内的数字 | 游戏失败 |

三、程序代码:

python 复制代码
import random

def starts_zero(s):
    # 判断该输入是否为以0为开头,避免输入八进制数
    s = str(s)
    if len(s) > 0 and s[0] == '0':
        return False
    else:
        return True

def guess_number_game():
    # 随机生成一个1~100之间的整数
    number_to_guess = random.randint(1, 100)
    print(number_to_guess) 
    attempts = 0
    lower_bound = 1
    upper_bound = 100
    print("欢迎来到猜数游戏!")
    print("我已经想好了一个1到100之间的数字,你有10次机会来猜。")
    
    while attempts < 10:
        attempts += 1
        try:
            
            # 获取用户的猜测
            print("Please enter a number between {0} and {1}:".format(lower_bound,upper_bound),end = ' ')
            gueess = input()
            guess = int(gueess)
            '''attempts += 1'''
            if guess > 0 and guess < 101 and guess <= upper_bound and guess >= lower_bound and starts_zero(gueess):
            # 检查猜测是否正确
                if guess < number_to_guess:
                    print("猜小了!")
                    lower_bound = guess + 1
                elif guess > number_to_guess:
                    print("猜大了!")
                    upper_bound = guess - 1
                else:
                    print("恭喜你,猜对了!你用了{}次机会。".format(attempts))
                    return True  # 游戏成功
            else:
                continue
                
        except ValueError:
            '''print("输入无效,请输入一个整数!")'''
        '''attempts += 1'''# 如果在这里计数的话那么整数和字符两个输入不能同时计数    
    # 如果10次都没有猜中,则游戏失败
    print("很遗憾,你没有在10次机会内猜中数字。")
    return False

# 运行游戏
if guess_number_game():
    print("游戏成功!")
else:
    print("游戏失败。")

四、测试结果:

九次猜中

刚好在第十次猜中

猜范围之外的数字

猜范围内的数字

十次回车

以0为开头

含有英文字母

英文,汉字,数字,回车

含小数点

++如果有其他需求可以留言,博主看到后会更新并解决问题。++

相关推荐
小趴蔡ha2 小时前
02 Anaconda、Python 与机器学习开发环境入门
python·机器学习·anaconda
2401_868534782 小时前
RTOS之RT-Thread & Linux:线程/进程管理与调度核心差异分析
c++·python
zzzll11112 小时前
Claude Code离线安装方案揭秘
开发语言·php
数字化转型分享点滴3 小时前
富士康、蓝思科技为何选择四化信息?MES制造执行系统的实践
python·科技
wling03013 小时前
vasp虚频计算-python脚本
开发语言·windows·python·vasp计算
魔镜前的帅比3 小时前
(开源项目)x-claw(总)
python·ai·rust·开源
郝学胜-神的一滴3 小时前
Qt 高级编程 040:按钮悬浮弹出滑块弹窗的完整攻略
开发语言·c++·qt·软件工程·用户界面
xrandzj4 小时前
Python面向对象编程入门:类、实例、初始化与封装实践
开发语言·python
DLYSB_5 小时前
API 网关流量洪峰与突发 CC 攻击:我用 Go 写了个“现场物理防御哨兵”,把故障响应压缩到秒级
开发语言·后端·golang·报警灯
matlabgoodboy6 小时前
计算机毕设代做|Java Python Matlab APP 全套开发设计
java·python·课程设计