Python学习笔记17 -- 猜数字小游戏2

目录

一、功能函数

1、说明函数 -- 对游戏玩法及设置进行说明

2、答案函数 -- 生成答案

3、猜测函数 -- 让玩家进行猜测

4、对照函数 -- 将答案和猜测进行对照

4.1 A函数

4.2 B函数

5、结果函数 -- 判断得到结果或继续猜测

6、时间函数 -- 判断一局游戏所用时间

7、打印函数 -- 显示每局的成绩

8、下局函数 -- 是否进行下一局游戏

9、测试函数 -- 测试对照函数的正确性

二、主程序 -- 两个while循环


一、功能函数

1、说明函数 -- 对游戏玩法及设置进行说明

def notification():"""write some information about the game -- tell the player how to play:return: none"""print("Guess the number from 1000 to 9999~")print("A means the number of the data and its location which are correct")print("B means the number of the data is correct but the location is wrong")print("for example, the right answer is 1234, your guess is 1245, then it will show 2A1B")print(("Give you another example:9527 and 9572 : 2A2B"))print("Let's begin the game! \n")

2、答案函数 -- 生成答案

def generate_answer():"""create a random answer from 1000 to 9999:return: the answer of the game"""return random.randint(1000,9999)

3、猜测函数 -- 让玩家进行猜测

def make_guess():"""input the guess:return: the player's guess answer"""return int(input('Plz input your guess:'))

4、对照函数 -- 将答案和猜测进行对照

def check_guess(answer, guess):"""Get the result -- how many numbers and locations are right:param answer: The right answer which was created by the function of generate_answer:param guess: The input of player:return: (number)A(number)B -- for example -- 4A0B -- you got the right answerA means both the number and location are correctB means only the number is correct(despite the A)"""a_num = check_a(answer, guess)b_num = check_b(answer, guess)result = f'{a_num}A, {b_num}B'print(result)return result

4.1 A函数

def check_a(answer, guess):"""check the right number and location -- for example, 9527 guess 9572, return 2:param answer: The right answer which was created by the function of generate_answer:param guess: The input of player:return: the number of A"""count = 0ansStr = str(answer)gueStr = str(guess)for index, char in enumerate(gueStr):if (ansStr[index] == char):count += 1return count

4.2 B函数

一开始想直接用if char in ansstr指令,但想到有9527和9522得到1b的情况。 ---

因此引入了aIndex变量,使用guestr.index(char) not in aIndex作为额外补充条件,但出现了答案为1333和猜测3833出现3B的情况。 --

经过检查发现,index函数只能查到字符串中某字符出现的第一个位置,相当于,无论是第一个3还是第二个3还是第三个三,使用guestr.index(char)指令只能获得第一个3所在的位置,因此,三个三使程序运行了三次第一个三不在aindex位置的代码。

为了解决这种情况,想到在一开始检测A的情况时,就将答案和猜测中A的位置上的数字替换成别的字母,这样在检测B的个数时,免受A位置的干扰。为了防止1333和3833出现3b的情况,在第一个3出现的时候,就先计算一次,再将这个3替换成别的字母,这样,在第二个3出现的时候,由于第一个三已经被替换成了字母,使用index函数时,第二个3的位置就可以被检测到。

def check_b(answer, guess):"""check the number:if the number is correct but the location is wrong, then the num of b add 1only can be compared with those not belong to A:param answer: The right answer which was created by the function of generate_answer:param guess: The input of player:return: the number of B"""count = 0ansStr = str(answer)gueStr = str(guess)aIndex = [] # save the index of Arepeat = []for index, char in enumerate(ansStr):if (gueStr[index] == char):"""remove the number of A"""aIndex.append(index)gueStr = gueStr[:index] + str.replace(gueStr[index], char, 'a') + gueStr[index + 1:]ansStr = ansStr[:index] + str.replace(ansStr[index], char, 'b') + ansStr[index + 1:]for char in ansStr:"""if the number is in the B -- if the index of the number is not in A's indexthe number of B add 1and replace the number to "a" (because the function 'index' always count the location of the first char)"""if(char in gueStr):gIndex = gueStr.index(char)count += 1gueStr = gueStr[:gIndex] + str.replace(gueStr[gIndex],char, 'a') + gueStr[gIndex+1 : ]return count

5、结果函数 -- 判断得到结果或继续猜测

def process_result(guess_count,guess,result):"""Handle the result:if win(4A0B), return True, or return False:param guess_count: the guess chances the player has used:param guess: the answer of the player(guess):param result: (number)A(number)B:return: True or False"""print(f'Round {guess_count}, Your guess is: {guess}, And the result is: {result}')if result == '4A, 0B':print('Yeah, you win!!!~~~~')return Trueelse:print('Try again!')return False

6、时间函数 -- 判断一局游戏所用时间

def checkTime(begin_time):"""Record the time of guessing -- from beginning until the right answer:param begin_time: when the player began a new game:return: the time the player used in one game (seconds)"""finish_time = time.time()Time = finish_time - begin_timereturn Time

7、打印函数 -- 显示每局的成绩

def show_score(score):"""print the score(the round of the game, how many chances the player used to guess the right answer, and the total time):param score: the score the player got:return: none, just for printing the score"""print('===========================================')print('ROUND'.ljust(10), 'CHANCE'.ljust(10), 'TIME'.ljust(10))for sc in score:cycle = str(sc[0]).ljust(10)guess = str(sc[1]).ljust(10)time = str(sc[2]).ljust(10)print(cycle,guess,time)

8、下局函数 -- 是否进行下一局游戏

def should_continue():"""ask for continue -- if y or Y, then begin a new game, or end the running:return: True or False"""con = input("Do you wanna start a new game? if yes, input y or Y")if(con == 'y' or con == 'Y'):print("Thank u for another game, hope you can enjoy!")return Trueelse:print('Thank u for playing, have a nice day! Goodbye~~~~')return False

9、测试函数 -- 测试对照函数的正确性

if __name__ == '__main__':"""only when testing the gueFun, the function will runfor checking if the logic is correct"""# auto judgement == a numberassert (check_a(9527, 9522) == 3)assert (check_a(9572, 9527) == 2)assert (check_a(9527, 9342) == 1)assert (check_a(1234, 5678) == 0)assert (check_a(1111, 1211) == 3)assert (check_b(1234, 4321) == 4)assert (check_b(9527, 5923) == 2)assert (check_b(9527, 9522) == 0)assert (check_b(1333, 3833) == 1)assert (check_b(1111, 1311) == 0)assert (check_b(9269, 6266) == 0)# if wanna know the functions' function, then use this:
# print(bmi.__doc__)

二、主程序 -- 两个while循环

第一个while循环控制是否进行下一局游戏

        包括对一局游戏的变量初始化,记录开始时间,及在游戏结束后打印战绩

第二个while循环控制一局游戏的全部操作

        生成随机答案,输入猜测,判断猜测是否正确,给出提示,生成结果

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/web/36779.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

开源项目-商城管理系统

哈喽,大家好,今天主要给大家带来一个开源项目-商城管理系统 商城管理系统分前后端两部分。前端主要有商品展示,我的订单,个人中心等内容;后端的主要功能包括产品管理,门店管理,会员管理,订单管理等模块 移动端页面

深入理解深度神经网络(DNN)

深入理解深度神经网络(DNN) 大家好,我是免费搭建查券返利机器人省钱赚佣金就用微赚淘客系统3.0的小编,也是冬天不穿秋裤,天冷也要风度的程序猿! 什么是深度神经网络(DNN)&#xff…

力扣第216题“组合总和 III”

在本篇文章中,我们将详细解读力扣第216题“组合总和 III”。通过学习本篇文章,读者将掌握如何使用回溯法来解决这一问题,并了解相关的复杂度分析和模拟面试问答。每种方法都将配以详细的解释,以便于理解。 问题描述 力扣第216题…

[OtterCTF 2018]Name Game

Name Game 题目描述:我们知道这个帐号登录到了一个名为Lunar-3的频道。账户名是什么?猜想:既然登陆了游戏,我们尝试直接搜索镜像中的字符串 Lunar-3 。 直接搜索 Lunar-3 先把字符串 重定向到 txt文件里面去然后里面查找 Lunar-3…

什么是机器学习,机器学习与人工智能的区别是什么(一)?

人工智能和计算机游戏领域的先驱阿瑟塞缪尔(Arthur Samuel)创造了 "机器学习"一词。他将机器学习定义为 “一个让计算机无需明确编程即可学习的研究领域” 。通俗地说,机器学习(ML)可以解释为根据计算机的经…

【RT摩拳擦掌】RT云端测试之百度天工物接入构建(设备型)

【RT摩拳擦掌】RT云端测试之百度天工物接入构建(设备型) 一, 文档介绍二, 物接入IOT Hub物影子构建2.1 创建设备型项目2.2 创建物模型2.3 创建物影子 三, MQTT fx客户端连接云端3.1 MQTT fx配置3.2 MQTT fx订阅3.3 MQT…

003 SSM框架整合

文章目录 整合web.xmlapplicationContext-dao.xmlapplicationContext-service.xmlspringmvc.xmldb.propertieslog4j.propertiespom.xml 测试sqlItemController.javaItemMapper.javaItem.javaItemExample.javaItemService.javaItemServiceImpl.javaItemMapper.xml 整合 将工程的…

Linux 生产消费者模型

💓博主CSDN主页:麻辣韭菜💓   ⏩专栏分类:Linux初窥门径⏪   🚚代码仓库:Linux代码练习🚚   🌹关注我🫵带你学习更多Linux知识   🔝 前言 1. 生产消费者模型 1.1 什么是生产消…

二分查找:自定义 upper_bound、lower_bound

二分查找详细介绍可以看这篇文章&#xff0c;此篇文章介绍返回索引的 upper_bound 和 lower_bound 的 C 实现。 lower_bound 实现代码 #include <vector>int lower_bound_index(const std::vector<int>& vec, const int& target) {int left 0;int right…

AI复活亲人市场分析:技术、成本与伦理挑战

“起死回生”这种事&#xff0c;过去只存在于科幻电影里&#xff0c;但今年&#xff0c;被“复活”的案例却越来越多。 2月底&#xff0c;知名音乐人包晓柏利用AI“复活”了她的女儿&#xff0c;让她在妈妈生日时唱了一首生日歌&#xff1b;3月初&#xff0c;商汤科技的年会上…

grpc编译

1、cmake下载 Download CMakehttps://cmake.org/download/cmake老版本下载 Index of /fileshttps://cmake.org/files/2、gprc源码下载&#xff0c;发现CMAKE报错 3、使用git下载 1&#xff09;通过git打开一个目录&#xff1a;如下grpc将放在D盘src目录下 cd d: cd src2&am…

深入解析内容趋势:使用YouTube API获取视频数据信息

一、引言 YouTube&#xff0c;作为全球最大的视频分享平台之一&#xff0c;汇聚了无数优质的内容创作者和观众。从个人分享到专业制作&#xff0c;从教育科普到娱乐休闲&#xff0c;YouTube上的视频内容丰富多彩&#xff0c;满足了不同用户的需求。对于内容创作者、品牌以及希…

查看linux中libc库的位置

因为在linux中libc库是非常基础的库&#xff0c;因此随便编译一个简单的hello world程序&#xff0c;一般也会链接上这个库。可以通过ldd命令来查看编译成功的可执行程序&#xff0c;来查看链接哪些库&#xff0c;以及链接库的位置。 $ ldd hello | grep libc显示结果 libc.so…

第八节:学习@Bean和@ComponentScan以及@Autowired的区别(自学Spring boot 3.x的第二天)

大家好&#xff0c;我是网创有方&#xff0c;上篇学习了依赖注入。加上上节学习的Autowired和之前的Bean以及ComponentScan&#xff0c;目前已经有三种方式。那么该如何选择用哪一种方式呢&#xff1f;咱们这节来学习它们的区别在哪里&#xff1f; 第七节&#xff1a;如何浅显…

欧姆龙NJ/NX使用科伺伺服的PDO一般配置

选择单击左侧“配置和设置”&#xff0c;双击“EtherCAT”&#xff0c;选择从设备&#xff0c;单击“编辑PDO映射设置” 配置伺服所需PDO 选择单击左侧“配置和设置”下的“运动控制设置”&#xff0c;然后右键“轴设置”&#xff0c;添加“运动控制轴/单轴位置控制轴”&#x…

LeetCode:经典题之144、94、145、102题解及延伸|二叉树的遍历|前中后层序遍历|Morris算法

系列目录 88.合并两个有序数组 52.螺旋数组 567.字符串的排列 643.子数组最大平均数 150.逆波兰表达式 61.旋转链表 160.相交链表 83.删除排序链表中的重复元素 389.找不同 1491.去掉最低工资和最高工资后的工资平均值 896.单调序列 206.反转链表 92.反转链表II 141.环形链表 …

Linux 常用命令之 RZ和SZ 简介

一、引言 在Linux系统管理中&#xff0c;尤其是在远程操作时&#xff0c;文件的上传与下载是常见的需求。对于CentOS用户而言&#xff0c;rz和sz这两个命令提供了简单而高效的文件传输方式&#xff0c;尤其在SSH终端环境中更为便利。本文将详细介绍rz和sz命令的基本概念、如何…

【鸿蒙学习笔记】@Styles装饰器:定义组件重用样式

原文链接&#xff1a;Styles装饰器&#xff1a;定义组件重用样式 目录标题 [Q&A] Styles装饰器作用 [Q&A] Styles装饰器特点使用场景 [Q&A] Styles装饰器作用 Styles 表示公共样式&#xff0c;每个组件都可以复用。如果相同样式在各个组件里复制一遍&#xff0c;…

高效管理:在Postman中处理大型响应数据的策略与技巧

Postman是一款功能强大的API开发和测试工具&#xff0c;但在处理大型响应数据时&#xff0c;用户可能会遇到性能瓶颈或数据管理上的挑战。本文将详细探讨在Postman中处理大型响应数据的策略和技巧&#xff0c;包括数据查看、分析、预处理和性能优化等。 一、大型响应数据的挑战…

基于SpringBoot漫画网站系统设计和实现(源码+LW+调试文档+讲解等)

&#x1f497;博主介绍&#xff1a;✌全网粉丝10W,CSDN作者、博客专家、全栈领域优质创作者&#xff0c;博客之星、平台优质作者、专注于Java、小程序技术领域和毕业项目实战✌&#x1f497; &#x1f31f;文末获取源码数据库&#x1f31f; 感兴趣的可以先收藏起来&#xff0c;…