Pages

Wednesday 10 July 2013

Cow Bull game (aka guess the number) in python


I used to play a game called 'Cow-Bull' with my friends at school. It is a game that can be played with a notebook and pencil. But it could be a nice project to write a program that lets you play the game with your computer :).

First let us understand the rules of the game:





The aim of the game is to guess a four digit number. For this the person has 10 chances. The number should not have repeated digits.
Eg. '1223' is not allowed because 2 is repeated.
Also the number cannot start with a 0. (because then, it wont be a 4 digit number).
On each guess we make, we get a result in terms of x-cow and y-bull.
x-cow means that x digits match the unknown number but are not in correct place.
y-bull means that y digits match the unknown number and are also in correct place.
Eg. Let the number to be guessed is 5678 and your guess is 7685.
Then your result would be 1-bull (because '6' is in its correct position) and 2-cow (because '7' and '8' are guessed right but are not in their correct possition)



Now let's start our program :D. We will make 3 functions for this.
1.generate() : this will generate a valid 4 digit number.
2.result(guess,actual): this will analyse the user's guess and the generated number to give a result in terms of cow/bull.
3.check_valid(guess): checks if the guess is valid or not.
By 'valid' I mean that the guess should be in accordance with the above mentioned rules.
def generate():
    digits=list('1234567890')
    number=[digits.pop(random.choice(range(9)))]
    number+=random.sample(digits,3)
    number=reduce(lambda i,j:i+j, number)
    return number

'number' is a list whose 1st element is randomly popped out of the list 'digits' excluding the last digit in 'digits' (i.e. '0' will not be chosen). Then from the remaining digits in 'digits', select 3 digits randomly and insert them into the list 'numbers'. Now number has 4 digits. Now our job is easy. Just join the digits and return them as a string.

I dont want to make this article very long, so I will continue the game in the next article so that its an easy read. I hope you liked the article. Your feedback is most welcome.
 



1 comment: