Python实现破解猜数游戏实例详解


本文摘自php中文网,作者巴扎黑,侵删。

这篇文章主要介绍了Python实现破解猜数游戏算法,简单描述了猜数游戏的原理,并结合具体实例形式分析了Python破解猜数游戏的相关实现技巧,需要的朋友可以参考下

本文实例讲述了Python实现破解猜数游戏算法。分享给大家供大家参考,具体如下:

QQ群里的聊天机器人会发起猜数小游戏. 玩法如下:

1. 用户发 #猜数 到群里
2. 机器人响应: 猜数已经开始, 范围是1-10000之间的某个数
3. 你发送 #猜数[123] 到群里
4. 机器人响应: 大了或者小了, 或者恭喜你猜中了
5. 你根据刚才猜的123, 和返回, 猜一个更小或更大的数, 发送 #猜数[111] , 即返回第2步

那么最好的猜测方法肯定是找居中的数了, 由于心算耗时, 所以直接上python脚本破解这个:


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

#!/usr/bin/env python

# -*- coding: utf-8 -*-

__author__ = 'huhu, <huyoo353@126.com>'

def find_middle(start, end):

  #print start, end

  return round((start+end)/2.0)

if __name__ == '__main__':

  start, end = '',''

  text = raw_input(u"> 输入猜数的范围(如:421-499 或者421 499 或者421,499):").decode('gb18030')

  spliters = '-, '

  for c in spliters:

    if text.find(c) != -1:

      num_list = text.split(c)

      if ''.join(num_list).isdigit():

        start, end = num_list[0],num_list[1]

        break

  if start == '' or end == '':

    print u'范围不正确'

  else:

    start = int(start)

    end  = int(end)

    count = 1

    last_guess = find_middle(start,end)

    while 1:

      result = raw_input(u"放弃猜测直接回车, 等于输入=, 小了输入1, 大了请输入2\n>>> #猜数[%d] ,对吗?> " % last_guess ).decode('gb18030')

      #print type(text)

      if result in ['q','e','exit','quit','bye',u'退出']:

        print 'Bye!'

        break

      else:

        result=result.strip()

        if result == '1':

          start = last_guess

          last_guess = find_middle(last_guess,end)

        elif result == '2':

          end = last_guess

          last_guess = find_middle(start,last_guess)

        elif result == '=':

          print u'恭喜猜中, 共猜了%d次' % count

          print u'#猜数[%d]' % last_guess

          break

        else: #

          continue

        count += 1

以上就是Python实现破解猜数游戏实例详解的详细内容,更多文章请关注木庄网络博客!!

相关阅读 >>

Python怎么找出最大数

微信跳一跳Python辅助脚本实例分享

Python元组创建赋值以及更新删除操作的实例分析

str Python是什么意思

vscode下好用的Python插件及配置_Python

Python中socket模块详解

Python标准数据类型有哪些

Python 怎么调用百度地图api

Python安装库安装失败怎么解决

Python类变量和实例变量的区别

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...