python實現(xiàn)猜數(shù)字游戲(無重復(fù)數(shù)字)示例分享
import time, random
class GuessNum:
def __init__(self):
self._num = ''
self.input_num = []
self.count = 1 #猜對所用次數(shù)
self.sec = 0 #猜對所用時間
self._generate_num()
def _generate_num(self): #產(chǎn)生不重復(fù)的四個數(shù)字
seq_zton = list(range(10))
for i in range(0, 4):
a = str(random.choice(seq_zton)) #選出一個數(shù)字
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 #位置對和數(shù)值對的分別的個數(shù)
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() #需要優(yōu)化
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
相關(guān)文章
python3 中的字符串(單引號、雙引號、三引號)以及字符串與數(shù)字的運算
這篇文章主要介紹了python3 中的字符串(單引號、雙引號、三引號)以及字符串與數(shù)字的運算,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07Python實現(xiàn)曲線擬合操作示例【基于numpy,scipy,matplotlib庫】
這篇文章主要介紹了Python實現(xiàn)曲線擬合操作,結(jié)合實例形式分析了Python基于numpy,scipy,matplotlib庫讀取csv數(shù)據(jù)、計算曲線擬合及圖形繪制相關(guān)操作技巧,需要的朋友可以參考下2018-07-07python批量將PDF文件轉(zhuǎn)換成圖片的實現(xiàn)代碼
這篇文章使用python編寫了一個小腳本,目的是為了實現(xiàn)批量將PDF文件轉(zhuǎn)換成圖片,文中有詳細(xì)的實現(xiàn)代碼,對我們的學(xué)習(xí)或工作有一定的幫助,感興趣的小伙伴可以參考閱讀一下2023-08-08python中Task封裝協(xié)程的知識點總結(jié)
在本篇內(nèi)容里小編給大家總結(jié)的是一篇關(guān)于python中Task封裝協(xié)程的知識點總結(jié)內(nèi)容,有興趣的朋友們可以跟著學(xué)習(xí)下。2021-07-07