文曲星上的经典“猜数字”游戏,伴我度过了多少个无聊的时该,今天回想起来,依然心潮澎湃。前几天将这个游戏做到到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>
※※※※※※※※※※※※※※--我的程序人生--※※※※※※※※※※※※※※