当前位置:首页 » 编程语言 » 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
热点内容
取消电脑连接wifi密码怎么设置密码 发布:2025-07-04 19:31:32 浏览:506
电脑服务器市场 发布:2025-07-04 19:14:06 浏览:503
没签名只加密 发布:2025-07-04 18:54:38 浏览:255
红米手机存储问题 发布:2025-07-04 18:50:43 浏览:843
水电煤算法 发布:2025-07-04 18:36:44 浏览:330
天翼视讯缓存文件夹 发布:2025-07-04 18:36:43 浏览:97
unix网络编程第2卷 发布:2025-07-04 18:33:41 浏览:782
编译历史 发布:2025-07-04 18:23:01 浏览:852
空调压缩机种类 发布:2025-07-04 18:13:58 浏览:243
中国有ip6服务器吗 发布:2025-07-04 17:58:56 浏览:727