In the previous article I discussed the rules of the game and started our programming of the game with the generate() function. We will now write the other two function and then use them in our program.
def result(guess,actual): guess=list(guess) actual=list(actual) cow=0 bull=0 total_matchings=len([i for i in guess if i in actual]) for i in range(4): if guess[i]==actual[i]: bull+=1 cow=int(total_matchings)-bull return cow,bull
We first find the total number of digits that are same, both in our guess and the actual number. Then the
for loop is used to calculate the bull and cow is = total_maching - bull. Then return cow,bull as a 2-tuple.
Though the program can me made with these two functions only but to make a good game we will another function called check_valid(guess) with 1 argument. I will check if the input is a valid input or not.
for loop is used to calculate the bull and cow is = total_maching - bull. Then return cow,bull as a 2-tuple.
Though the program can me made with these two functions only but to make a good game we will another function called check_valid(guess) with 1 argument. I will check if the input is a valid input or not.
def check_valid(guess): if len(guess)!=4: print "not a four digit number" return False if guess[0]=='0': print "1st digit cannot be 0" return False if not guess.isdigit(): print "it is not a number" return False for i in guess: if guess.count(i)!=1: print "number cannot have repeated digits" return False return True
check_valid(guess) checks if the guess follows all the rules of the game or not. If any rule is violated the it returns a 'False' else returns a 'True'.
Since we are equipped with the 3 fu
nctions we can move on to complete our game.
nctions we can move on to complete our game.
Rest of the code of the game is as follows:
actual=generate() times=0 cow=0 bull=0 while times < 10: guess=raw_input("enter your guess number "+str(times+1)+": ") if check_valid(guess): cow,bull=result(guess,actual) print "cow = ",cow,"\tbull = ",bull,'\n' times+=1 else : print "invalid input\n" if bull==4: print "you won..." raw_input() exit() print "you lost" print "correct answer was: ",actual
Here we generate a random 4-digit number and ask the user to make guesses untill he makes 10 valid guess. If he guesses the correct number, he wins and the game exits, otherwise, the user loses and the correct answer is printed on the screen.
No comments:
Post a Comment