當前位置:首頁 » 編程語言 » 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
熱點內容
android自定義命名空間 發布:2025-09-19 10:31:34 瀏覽:456
凱立德導航文件夾名稱 發布:2025-09-19 10:31:27 瀏覽:29
獅山編程 發布:2025-09-19 10:14:45 瀏覽:781
androidshape畫圓 發布:2025-09-19 10:13:21 瀏覽:833
c語言if復合語句 發布:2025-09-19 10:12:30 瀏覽:714
C語言有什麼特點 發布:2025-09-19 09:54:54 瀏覽:820
c語言strupr 發布:2025-09-19 09:47:52 瀏覽:683
路由器密碼是什麼啊 發布:2025-09-19 09:23:25 瀏覽:701
天蠍腳本輔助 發布:2025-09-19 09:22:31 瀏覽:256
官服光遇賬號和密碼在哪裡看 發布:2025-09-19 08:57:15 瀏覽:649