python實(shí)現(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
- python實(shí)現(xiàn)的簡單猜數(shù)字游戲
- python實(shí)現(xiàn)猜數(shù)字游戲
- python實(shí)現(xiàn)猜拳小游戲
- python3.3使用tkinter開發(fā)猜數(shù)字游戲示例
- python實(shí)現(xiàn)猜數(shù)字小游戲
- Python實(shí)現(xiàn)的搖骰子猜大小功能小游戲示例
- python實(shí)現(xiàn)猜單詞小游戲
- python簡單猜數(shù)游戲?qū)嵗?/a>
- Python實(shí)現(xiàn)簡單猜數(shù)字游戲
- 利用python實(shí)現(xiàn)你說我猜游戲的完整實(shí)例
相關(guān)文章
Python使用collections模塊實(shí)現(xiàn)擴(kuò)展數(shù)據(jù)類
Python?標(biāo)準(zhǔn)庫提供了一個?collections?模塊,里面提供了很多的數(shù)據(jù)類,在工作中使用這些類能夠簡化我們的開發(fā),本文就來看看collections是如何實(shí)現(xiàn)擴(kuò)展數(shù)據(jù)類的吧2023-06-06
python3+PyQt5使用數(shù)據(jù)庫窗口視圖
這篇文章主要為大家詳細(xì)介紹了python3+PyQt5使用數(shù)據(jù)庫窗口視圖,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-04-04
django中的自定義分頁器的實(shí)現(xiàn)示例
本文主要介紹了django中的自定義分頁器的實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08
Python實(shí)現(xiàn)獲取操作系統(tǒng)版本信息方法
這篇文章主要介紹了Python實(shí)現(xiàn)獲取操作系統(tǒng)版本信息方法,本文在命令行中獲取操作系統(tǒng)信息,介紹了platform模塊的使用,需要的朋友可以參考下2015-04-04
MacOS(M1芯片 arm架構(gòu))下安裝PyTorch的詳細(xì)過程
這篇文章主要介紹了MacOS(M1芯片 arm架構(gòu))下安裝PyTorch的詳細(xì)過程,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-02-02

