当前位置:首页 » 编程语言 » python猜数字游戏代码

python猜数字游戏代码

发布时间: 2024-03-16 01:02:17

‘壹’ 用python写猜数字小游戏

核心代码给你,具体的功能还需要自己完善。

importtime,random
classGuessNum:
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))
foriinrange(0,4):
a=str(random.choice(seq_zton))#选出一个数字
self._num+=a
seq_zton.remove(int(a))#注意a的类型

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

defcheck_answer(self):
returnself._num

defcheck_input(self):
num_pos,num_value=0,0#位置对和数值对的分别的个数
tmp=input("Pleaseinputthenumberyouguess(Norepetition),or'c'tochecktheanswer:")
iftmp=='c':
print(self.check_answer())
tof=self.check_input()
returntof
elifnottmp.isalnumornotlen(tmp)==4:
print("Wrongformat!")
tof=self.check_input()#需要优化
returntof
self.input_num=list(tmp)
lst_temp=list(self._num)
ifself.input_num==lst_temp:#猜对
self.prt_vic()
returnTrue
foriinlst_temp:
ifiinself.input_num:
iflst_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
returnFalse

defprt_state(self,num_pos,num_value):
print("You'vegot%%dnumberswiththerightvalueonly"%(num_pos,num_value))

defprt_vic(self):
t=time.clock()
self.sec=t-self.sec
print("Congratulations!!")
print("%dtimesand%."%(self.count,self.sec))

gn=GuessNum()
whileTrue:
ss=gn.check_input()
ifss:
b=input("Continue?y/n:")
ifb=='n':
break
else:
gn=GuessNum()
continue
热点内容
java返回this 发布:2025-10-20 08:28:16 浏览:577
制作脚本网站 发布:2025-10-20 08:17:34 浏览:871
python中的init方法 发布:2025-10-20 08:17:33 浏览:566
图案密码什么意思 发布:2025-10-20 08:16:56 浏览:749
怎么清理微信视频缓存 发布:2025-10-20 08:12:37 浏览:668
c语言编译器怎么看执行过程 发布:2025-10-20 08:00:32 浏览:994
邮箱如何填写发信服务器 发布:2025-10-20 07:45:27 浏览:239
shell脚本入门案例 发布:2025-10-20 07:44:45 浏览:98
怎么上传照片浏览上传 发布:2025-10-20 07:44:03 浏览:790
python股票数据获取 发布:2025-10-20 07:39:44 浏览:696