文曲星上的經典“猜數字”遊戲,伴我度過了多少個無聊的時該,今天回想起來,依然心潮澎湃。前幾天將這個遊戲做到到Winodows Mobile上。今天趕上有空,又將它寫成了Python。哈哈,Python不愧為Python,只用到前者1/3左右的代碼就搞定了。
說一下遊戲規則吧,很簡單:程式隨機產生一個數字不重複的四位元(如1234),要求玩家在8次機會內猜出這個答案。每次競猜,程式會以“XAXB”的形式提示玩家,其中“A”表示數字和位置都正確,“B"表示位置不正確但數字正確,“X”表示相應的個數。如玩家猜“5678”,那麼提示為“0A0B”,猜“4321”則“0A4B”,當“4A0B”時,即4個數的位置的數字都正確了,才算勝利!
怎麼樣?你敢挑戰一下自己的智商嗎?以下是源碼:(歡迎協助改進,最好能改成PYS60上的)
import random
class Bingle:
"""
Generate a random answer,and record guess times,and judge it
"""
A,B=(0,0) #Match falg
AttemptTimes=8 #Geuss times
Answer=[0,0,0,0] #The Answer
def BuildAnswer(self):
random.seed()
while 1:
digit = random.randint(0, 9999)
self.Answer[0]=digit/1000
self.Answer[1]=digit%1000/100
self.Answer[2]=digit%100/10
self.Answer[3]=digit%10
if self.Answer[0]!=self.Answer[1] and self.Answer[0]!=self.Answer[2] and self.Answer[0]!=self.Answer[3] and self.Answer[1]!=self.Answer[2] and self.Answer[1]!=self.Answer[3] and self.Answer[2]!=self.Answer[3]:
return
def __init__(self):
Answer=[0,0,0,0]
AttemptTimes=0
self.BuildAnswer()
def IsTryStringOK(self,TryString):
if TryString.isdigit() and len(TryString)==4:
if TryString[0]!=TryString[1] and TryString[0]!=TryString[2] and TryString[0]!=TryString[3] and TryString[1]!=TryString[2] and TryString[1]!=TryString[3] and TryString[2]!=TryString[3]:
return 1
return 0
def Judge(self,TryString):
for i in range(4):
if(TryString[i]==str(self.Answer[i])):
self.A=self.A+1
else:
for j in range(4):
if(TryString[i]==str(self.Answer[j])):
self.B=self.B+1
ReturnStr = "%dA%dB"%(self.A,self.B)
self.A=0
self.B=0
return ReturnStr
class MainGame:
"""
Play the game
"""
B=None
def __init__(self):
self.B=Bingle()
#print "Answer:%s"%(self.B.Answer)
print "I've ready,please guess me."
def Play(self):
while self.B.AttemptTimes:
TryString=raw_input("%d:\t"%self.B.AttemptTimes)
if self.B.IsTryStringOK(TryString):
TryResult=self.B.Judge(TryString)
if TryResult=="4A0B":
print "You are winer!"
break
else:
print TryResult
self.B.AttemptTimes=self.B.AttemptTimes-1
else:
print "Input error! Type again,",
continue
else:
print "Attempt times is Eight.\nThe finily answer is: %s\nGame Over!"%self.B.Answer
if __name__=="__main__":
Try=1
while Try:
BingleGame = MainGame()
BingleGame.Play()
Data=raw_input( "Do you want to try again? \nType [0] for 'No' and others for [Yes]\n")
if Data.isdigit():
Try=int(Data)
else:
Try=1
else:
print "Game exited!"
<The end>