zl程序教程

您现在的位置是:首页 >  后端

当前栏目

python实现猜数字游戏(无重复数字)示例分享

Python游戏 实现 示例 分享 数字 重复
2023-06-13 09:15:24 时间

复制代码代码如下:


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%dnumberswiththerightpositionand%dnumberswiththerightvalueonly"%(num_pos,num_value))

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

gn=GuessNum()
whileTrue:
   ss=gn.check_input()
   ifss:
       b=input("Continue?y/n:")
       ifb=="n":
           break
       else:
           gn=GuessNum()
           continue