当前位置: 首页 > news >正文

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循环控制一局游戏的全部操作

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

相关文章:

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

目录 一、功能函数 1、说明函数 -- 对游戏玩法及设置进行说明 2、答案函数 -- 生成答案 3、猜测函数 -- 让玩家进行猜测 4、对照函数 -- 将答案和猜测进行对照 4.1 A函数 4.2 B函数 5、结果函数 -- 判断得到结果或继续猜测 6、时间函数 -- 判断一局游戏所用时间 7、打…...

【系统架构设计师】七、信息安全技术基础知识(信息安全的概念|信息安全系统的组成框架|信息加解密技术)

目录 一、信息安全的概念 1.1 信息安全的基本要素和范围 1.2 信息存储安全 1.3 网络安全 二、信息安全系统的组成框架 2.1 技术体系 2.2 组织机构体系 2.3 管理体系 三、 信息加解密技术 3.1 数据加密 3.2 对称加密技术 3.3 非对称加密算法 3.4 数字信封 3.5 信…...

CMMM Plus+ Calculus Update 超级游戏大作 游戏说明

资源链接 Scratch超级生命模拟游戏:CMMMPlusCalculusUpdate.sb3资源-CSDN文库 关卡编辑器 ◽️使用 WASD 移动视图。 ◽️LMB 放置单元格。 ◽️Space LMB 删除单元格。Ctrl Space LMB 删除所有相同类型的单元格。 ◽️Q / E 旋转单元格。 ◽️Z / X 在单元格类…...

Java OA系统任务协作模块

以下是一篇关于构建高效且功能丰富的OA系统任务协作模块的博客文章,采用了Spring Boot、Spring Data JPA和React等主流技术。文章不仅展示了项目的基本实现,还介绍了如何优化代码和增加新的功能,以提升系统的性能和用户体验。 --- ## 构建高…...

深入解析Maven常用命令

目录 什么是 MavenMaven 的安装与配置Maven 项目结构Maven 常用命令 mvn cleanmvn compilemvn testmvn packagemvn installmvn deploymvn sitemvn dependencymvn help 总结 什么是 Maven Maven 是由 Apache 软件基金会开发的一个项目管理和构建工具。它基于项目对象模型&…...

【Docker】镜像

目录 1. 镜像拉取 2. 镜像查询 3. 镜像导出 4. 镜像上传 5. 镜像打标签 6. 镜像上推 7. 镜像删除 8. 镜像运行及修改 8.1 在registry 节点运行 mariadb 镜像,将宿主机 13306 端口作为容器3306 端口映射 8.2 查看容器ID 8.3 进入容器 8.4 创建数据库xd_d…...

力扣最新详解5道题:两数之和三数之和四数之和

目录 一、查找总价格为目标值的两个商品 题目 题解 方法一:暴力枚举 方法二:对撞指针 二、两数之和 题目 题解 方法一:暴力枚举 方法二:哈希表法 三、三数之和 题目 题解 方法一:排序暴力枚举set去重 …...

通讯:单片机串口和电脑通讯

目录 1.串口输出数据到电脑 硬件部分 串口输出数据到电脑的软件软件部分: 相关问题: 2.单片机串口--485--485转USB--电脑 串口,芯片,转换器,设备之间的通讯的接线,都是要TX--RX, RX--TX 交叉连接。 单…...

ubuntu22.04 设置双屏

一 概述 最近把ubuntu18.04 升级到 22.04 双屏显示出来问题,在此记录下解决问题方案。二 解决方案 1 使用命令查看能检测到显示器 xrandr根据输出的信息,我们可以知道 HDMI-0 与 DP-0 是connected 。检测到两个显示器 2 设置输出显示器分辨率 由于我…...

【FPGA-常见问题及解决方案】

1、VIVADO的License无法加载:license文件必须在英文路径; 2、例程代码路径不能过长,也不允许有中文路径!!! 3、明明加载了license,license也正确,例程无法完成综合:这种情…...

【第3章】MyBatis-Plus持久层接口之Service Interface(上)

文章目录 前言一、save1. 示例(save)2. 示例(saveBatch)3. 示例(saveBatch 指定批次大小) 二、saveOrUpdate1.示例(saveOrUpdate)2.示例(saveOrUpdateBatch)3…...

Nodemon的入门及使用

nodemon 是一个工具,通过在检测到目录中的文件更改时自动重新启动 Node.js 应用程序来帮助开发基于 Node.js 的应用程序。它非常适合在开发环境中使用。以前,我们开发一个 Node 后端服务时,每次更改文件,都需要手动重启服务才能生…...

cesium 实现三维无人机航拍过程实景效果

需求背景 需要实现一个动态的三维无人机航拍过程实景效果 代码开发中&#xff0c;迭代功能待续... 解决效果 cesium 实现三维无人机航拍过程实景效果 index.vue <template><div><el-button class"btn" click"start">开始</el-butt…...

Rust:使用 Warp 框架编写基于 HTTPS 的 RESTful API

在 Rust 中使用 Warp 框架编写基于 HTTPS 的 RESTful API&#xff0c;你需要首先设置好 TLS/SSL 证书以启用 HTTPS。以下是一个基本的步骤指南&#xff1a; 步骤 1: 安装 Rust 和 Cargo 确保你已经安装了 Rust 和 Cargo。你可以从 Rust 官网 下载并安装 Rust。 步骤 2: 创建…...

测试开发工程师需要掌握什么技能?

测试开发工程师是软件开发中至关重要的角色之一。他们负责编写、维护和执行自动化测试脚本、开发测试工具和框架&#xff0c;以确保软件的质量和稳定性。为了成为一名优秀的测试开发工程师&#xff0c;你需要掌握以下技能&#xff1a; 1. 编程技能&#xff1a; 作为测试开发工…...

SpelExpressionParser评估SpEL(Spring Expression Language)表达式的解析器

是Spring中用于解析和评估SpEL(Spring Expression Language)表达式的解析器,SpEL是一种强大且灵活的表达式语言,广泛用于Spring框架中,以便在运行时解析和评估表达式 主要功能 1.解析和评估表达式:spelExpressionParser可以解析复杂的表达式,并在运行时对其进行评估; 2.访问…...

C#学习系列之DataGrid无故添加空行

C#学习系列之DataGrid无故添加空行 前言解决前解决后总结 前言 采用别人的轮子&#xff0c;想在基础上改界面&#xff0c;但是copy后&#xff0c;无论怎么样都会有空行&#xff0c;实在是绑定数据的输入没有任何赋值。 解决前 绑定的数据中输入三组数据&#xff0c;但是没有第…...

详解Alibaba Cloud Linux 3.2104 LTS 64位镜像操作系统

Alibaba Cloud Linux 3.2104是阿里云推出的云原生Linux发行版Alibaba Cloud Linux 3版本&#xff0c;64位操作系统&#xff0c;由阿里云提供免费长期维护更新和漏洞修复&#xff0c;镜像Alibaba Cloud Linux 3.2104 LTS 64位操作系统性能很不错&#xff0c;针对ECS云服务器进行…...

springboot异常产生原因

DataIntegrityViolationException Cause: java.sql.SQLException: Field ‘id’ doesn’t have a default value org.springframework.dao.DataIntegrityViolationException: ### Error updating database. Cause: java.sql.SQLException: Field id doesnt have a default …...

Redis 7.x 系列【8】数据类型之哈希(Hash)

有道无术&#xff0c;术尚可求&#xff0c;有术无道&#xff0c;止于术。 本系列Redis 版本 7.2.5 源码地址&#xff1a;https://gitee.com/pearl-organization/study-redis-demo 文章目录 1. 概述2. 常用命令2.1 HSET2.2 HGET2.3 HDEL2.4 HEXISTS2.5 HGETALL2.6 HKEYS2.7 HLE…...

LBE-LEX系列工业语音播放器|预警播报器|喇叭蜂鸣器的上位机配置操作说明

LBE-LEX系列工业语音播放器|预警播报器|喇叭蜂鸣器专为工业环境精心打造&#xff0c;完美适配AGV和无人叉车。同时&#xff0c;集成以太网与语音合成技术&#xff0c;为各类高级系统&#xff08;如MES、调度系统、库位管理、立库等&#xff09;提供高效便捷的语音交互体验。 L…...

2025 后端自学UNIAPP【项目实战:旅游项目】6、我的收藏页面

代码框架视图 1、先添加一个获取收藏景点的列表请求 【在文件my_api.js文件中添加】 // 引入公共的请求封装 import http from ./my_http.js// 登录接口&#xff08;适配服务端返回 Token&#xff09; export const login async (code, avatar) > {const res await http…...

ETLCloud可能遇到的问题有哪些?常见坑位解析

数据集成平台ETLCloud&#xff0c;主要用于支持数据的抽取&#xff08;Extract&#xff09;、转换&#xff08;Transform&#xff09;和加载&#xff08;Load&#xff09;过程。提供了一个简洁直观的界面&#xff0c;以便用户可以在不同的数据源之间轻松地进行数据迁移和转换。…...

Neo4j 集群管理:原理、技术与最佳实践深度解析

Neo4j 的集群技术是其企业级高可用性、可扩展性和容错能力的核心。通过深入分析官方文档,本文将系统阐述其集群管理的核心原理、关键技术、实用技巧和行业最佳实践。 Neo4j 的 Causal Clustering 架构提供了一个强大而灵活的基石,用于构建高可用、可扩展且一致的图数据库服务…...

Java 加密常用的各种算法及其选择

在数字化时代&#xff0c;数据安全至关重要&#xff0c;Java 作为广泛应用的编程语言&#xff0c;提供了丰富的加密算法来保障数据的保密性、完整性和真实性。了解这些常用加密算法及其适用场景&#xff0c;有助于开发者在不同的业务需求中做出正确的选择。​ 一、对称加密算法…...

优选算法第十二讲:队列 + 宽搜 优先级队列

优选算法第十二讲&#xff1a;队列 宽搜 && 优先级队列 1.N叉树的层序遍历2.二叉树的锯齿型层序遍历3.二叉树最大宽度4.在每个树行中找最大值5.优先级队列 -- 最后一块石头的重量6.数据流中的第K大元素7.前K个高频单词8.数据流的中位数 1.N叉树的层序遍历 2.二叉树的锯…...

Reasoning over Uncertain Text by Generative Large Language Models

https://ojs.aaai.org/index.php/AAAI/article/view/34674/36829https://ojs.aaai.org/index.php/AAAI/article/view/34674/36829 1. 概述 文本中的不确定性在许多语境中传达,从日常对话到特定领域的文档(例如医学文档)(Heritage 2013;Landmark、Gulbrandsen 和 Svenevei…...

LeetCode - 199. 二叉树的右视图

题目 199. 二叉树的右视图 - 力扣&#xff08;LeetCode&#xff09; 思路 右视图是指从树的右侧看&#xff0c;对于每一层&#xff0c;只能看到该层最右边的节点。实现思路是&#xff1a; 使用深度优先搜索(DFS)按照"根-右-左"的顺序遍历树记录每个节点的深度对于…...

DingDing机器人群消息推送

文章目录 1 新建机器人2 API文档说明3 代码编写 1 新建机器人 点击群设置 下滑到群管理的机器人&#xff0c;点击进入 添加机器人 选择自定义Webhook服务 点击添加 设置安全设置&#xff0c;详见说明文档 成功后&#xff0c;记录Webhook 2 API文档说明 点击设置说明 查看自…...

Golang——6、指针和结构体

指针和结构体 1、指针1.1、指针地址和指针类型1.2、指针取值1.3、new和make 2、结构体2.1、type关键字的使用2.2、结构体的定义和初始化2.3、结构体方法和接收者2.4、给任意类型添加方法2.5、结构体的匿名字段2.6、嵌套结构体2.7、嵌套匿名结构体2.8、结构体的继承 3、结构体与…...