python猜数字游戏代码多次_python实现猜数字游戏(无重复数字)示例分享

摘要

这篇文章主要介绍了python实现猜数字游戏(无重复数字)示例,需要的朋友可以参考下

复制代码 代码如下:

import time, random

class GuessNum:

def __init__(self):

self._num = ''

self.input_num = []

self.count = 1 #猜对所用次数

self.sec = 0 #猜对所用时间

self._generate_num()

def _generate_num(self): #产生不重复的四个数字

seq_zton = list(range(10))

for i in range(0, 4):

a = str(random.choice(seq_zton)) #选出一个数字

self._num += a

seq_zton.remove(int(a)) #注意a的类型

self.sec = time.clock() #开始计时

def check_answer(self):

return self._num

def check_input(self):

num_pos, num_value = 0, 0 #位置对和数值对的分别的个数

tmp = input("Please input the number you guess(No repetition),or 'c' to check the answer:")

if tmp == 'c':

print(self.check_answer())

tof = self.check_input()

return tof

elif not tmp.isalnum or not len(tmp) == 4:

print("Wrong format!")

tof = self.check_input() #需要优化

return tof

self.input_num = list(tmp)

lst_temp = list(self._num)

if self.input_num == lst_temp: #猜对

self.prt_vic()

return True

for i in lst_temp:

if i in self.input_num:

if lst_temp.index(i) == self.input_num.index(i): #位置也相同

num_pos += 1

num_value += 1

else:

num_value += 1

self.prt_state(num_pos, num_value)

self.count += 1

return False

def prt_state(self, num_pos, num_value):

print("You've got %d numbers with the right position and %d numbers with the right value only" % (num_pos, num_value))

def prt_vic(self):

t = time.clock()

self.sec = t - self.sec

print("Congratulations!You have successfully got the right number!")

print("%d times and %.2f sec in total to get the right answer" % (self.count, self.sec))

gn = GuessNum()

while True:

ss = gn.check_input()

if ss:

b = input("Continue? y/n:")

if b == 'n':

break

else:

gn = GuessNum()

continue

微信

分享

article_wechat.jpg?1

相关标签:猜数字游戏

本文原创发布php教程 ,转载请注明出处,感谢您的尊重!上一篇:使用python解析xml成对应的html示例分享

下一篇:Python爬虫框架Scrapy安装使用步骤

相关文章

相关视频在Django框架中运行Python应用全攻略

在Python的Django框架中创建和使用模版

python获取元素在数组中索引号的方法

浅谈python中截取字符函数strip,lstr...

python实现猜数字游戏(无重复数字)示例分享断点查看模拟用户登录案例增强版加入猜数字游戏

网友评论

文明上网理性发言,请遵守 新闻评论服务协议

我要评论

立即提交

专题推荐

除非注明,否则均为@武汉蒲公英网络工作室原创文章,转载必须以链接形式标明本文链接

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值