當前位置:首頁 » 編程語言 » 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
熱點內容
伺服器如何接入互聯網 發布:2025-07-04 11:01:08 瀏覽:475
網站伺服器資料庫伺服器 發布:2025-07-04 11:00:07 瀏覽:393
稀土開采需要哪些人員配置 發布:2025-07-04 10:59:57 瀏覽:460
少兒編程指引 發布:2025-07-04 10:59:05 瀏覽:619
安卓怎麼掃門禁卡 發布:2025-07-04 10:52:42 瀏覽:871
配置管理如何支持測試 發布:2025-07-04 10:38:53 瀏覽:656
雲伺服器2核4g3m什麼意思 發布:2025-07-04 10:23:34 瀏覽:241
蘋果手機如何往安卓手機導通訊錄 發布:2025-07-04 10:19:11 瀏覽:133
未來之役如何換伺服器 發布:2025-07-04 10:13:51 瀏覽:217
curlc上傳 發布:2025-07-04 09:59:35 瀏覽:882