Source

wd_pys60 / Forguys.py

Full commit
#Filename:Forguys.py -- a simple game named four number guess
#42
import random
def creatData(numLen=4):
	import random
	data=[]
	ALL_NUM=list('0123456789')
	tnum=ALL_NUM
	for i in range(numLen):
		data.append(random.choice(tnum))
		tnum=[num for num in tnum if not num in data]
	return data
	

class Forguys:
	'''four number guess'''
	def __init__(self,numLen=4,maxTimes=8,answer=None,bossKey='b',quitFlag='0'):
		self.quitFlag=quitFlag
		self.bossKey=bossKey
		self.answer=[]
		self.allAnswers=[]
		self.ctr=0
		self.maxTimes=maxTimes-1
		self.A=[0]*maxTimes
		self.B=[0]*maxTimes
		if answer:
			self.answer=list(answer)
		else:
			self.answer=creatData(numLen)
		
	def _ask(self,input):
		'''recive a list'''
		self.tanswer=input
		self.allAnswers.append(self.tanswer)
	def _compare(self):
		for i in self.tanswer:
			if i in self.answer and self.tanswer.index(i)==self.answer.index(i):
				self.A[self.ctr]+=1
			if i in self.answer and self.tanswer.index(i)!=self.answer.index(i):
				self.B[self.ctr]+=1
		
		return self.A[self.ctr],self.B[self.ctr]
	def showResult(self):
		print "".join(self.answer),'<-answer'
		for i in range(self.ctr):
			print "".join(self.allAnswers[i]),self.A[i],'A',self.B[i],'B'
		print 'ctr:',self.ctr+1
	def run(self,input=None):
		while 1:
			try:
				self._ask(input[self.ctr])
				if self.ctr==self.maxTimes:
					self.showResult()
					# print self.ctr
					# w=raw_input('Enter to continue')
					break
			except:
				self._ask(list(raw_input('%d TIMES:'%(self.ctr+1))))
			A,B=self._compare()
			if A==4 or self.ctr==self.maxTimes or self.tanswer==[self.quitFlag] or self.tanswer==[self.bossKey]:
				self.showResult()
				# w=raw_input('Enter to continue')
				break
			print A,'A',B,'B'
			self.ctr+=1
			

def test(maxTimes=8,numLen=4,answer=None,bossKey="b",quitFlag="0"):
	testData=[]
	for i in range(maxTimes):
		testData.append(creatData(numLen))
	f=Forguys(numLen,maxTimes,answer,bossKey,quitFlag)
	f.run(testData)

if __name__=="__main__":
	numLen=4
	maxTimes=8
	bossKey='b'
	quitFlag='0'
	answer=None
	test()
	while 1:
		f=Forguys(numLen,maxTimes,answer,bossKey,quitFlag)
		f.run()
		if f.tanswer==[f.quitFlag]:
			break
	w=raw_input('Enter to quit')