This article mainly introduces the example of using python to implement a guess digital game (without repeated numbers). For more information, see
The code is as follows:
Import time, random
Class GuessNum:
Def _ init _ (self ):
Self. _ num =''
Self. input_num = []
Self. count = 1 # number of guesses
Self. sec = 0 # time used to guess
Self. _ generate_num ()
Def _ generate_num (self): # Generate four numbers that are not repeated.
Seq_zton = list (range (10 ))
For I in range (0, 4 ):
A = str (random. choice (seq_zton) # select a number
Self. _ num + =
Seq_zton.remove (int (a) # note the type of
Self. sec = time. clock () # Start timing
Def check_answer (self ):
Return self. _ num
Def check_input (self ):
Num_pos, num_value = 0, 0 # number of positions and values respectively
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 () # optimization required
Return tof
Self. input_num = list (tmp)
Lst_temp = list (self. _ num)
If self. input_num = lst_temp: # guess
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): # The location is the same.
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