Study, standard input to number guessing game!
test.py
#! F:/Python/python.exe
# -*- coding: utf-8 -*-
import random
import re
#Number of digits
SCALE = 4
#Returns an array of random, unique numbers
def GetRandomNumbers(place):
seed = range(0, 10)
random.shuffle(seed)
result = ""
for i in range(0, place):
result = result + str(seed.pop())
return result
#Compare answers with answers
def CompareSolAns(solution, answer):
h = 0
b = 0
for sIndex, sValue in enumerate(answer):
for aIndex, aValue in enumerate(solution):
if sValue == aValue :
if sIndex == aIndex :
h += 1
else :
b += 1
return {"H":h, "B":b, "A":answer}
#Generate answer
solution = GetRandomNumbers(SCALE)
#Loop to the correct answer
count = 0
history = []
while True :
#Answer input count
count += 1
#Enter the answer
inputStr = "Turn "+str(count)+", Input Number:"
inputStr = inputStr.decode('utf-8')
ans = raw_input(inputStr)
#Check input with regular expression
checkMatch = re.match(r'^\d{'+str(SCALE)+'}$', ans)
#If the input does not follow the regular expression, start over
if checkMatch is None :
print u"Bad Input"
continue
#Compare the answer with the correct answer
result = CompareSolAns(solution, ans)
#If the answer is correct, end
if result["H"] == SCALE:
break
#If the answer is incorrect, the results are stacked and displayed, and a loop is displayed.
history.append(result)
#View results
print('------------------------------')
for i, val in enumerate(history) :
print "Turn "+str(i+1)+"\t"+val["A"]+"\t"+str(val["H"])+"H\t"+str(val["B"])+"B\t"
print('------------------------------')
print unicode("****** Exactly! ****** "+str(count)+" turn you are seikai")
Recommended Posts