The assignment is to write a program to play the game of Bul
The assignment is to write a program to play the game of Bulls and Cows with a human player.
The game can be played with any list of symbols, but we’ll use the digits
0, 1, 2, 3, 4, 5, 6, 7, 8, 9.
The computer chooses a “secret word” consisting of a string of four digits. Repetitions are not allowed. Use the Random module to make a random choice. Note we are treating the secret word as a string of digits, not as a number. The length of the secret word (2–9) should be a parameter in your program, but start with four digits.
The human Player tries to guess the secret word. The program will prompt the Player for a guess. Of course, if the player guesses the secret word, the game is over. The score of the game is the number of guesses it took the Player to guess the secret word.
If the Player’s guess is not the secret word, the computer will report the number of “Bulls” and “Cows”. A Bull occurs when the Player’s guess has a digit that is in the secret word and is in the same position as in the secret word. A Cow occurs when the guess has a digit that is in the secret word but not in the same position (i.e., it’s not a Bull).
For example, suppose the secret word is 9025 and the Player’s guess is 5032 Then there is one Bull, the digit 0, and there are two Cows, the digits 5 and 2, which are in both strings, but are not in the same position in the two strings. The Player tries to use this information to improve their next guess. Your program will communicate with the player in text mode (so you can use input to get the players guess). You should check that the Player’s guess follows the rule the repetitions are not allowed.
Turn in a program that follows these instructions. You can work in a group of 2 or 3
Solution
import random
def compare_numbers(number, user_guess):
cowbull = [0,0] #cows, then bulls
for i in range(len(number)):
if number[i] == user_guess[i]:
cowbull[1]+=1
else:
cowbull[0]+=1
return cowbull
if __name__==\"__main__\":
playing = True #gotta play the game
number = str(random.randint(0,9999)) #random 4 digit number
guesses = 0
print(\"Let\'s play a game of Cowbull!\") #explanation
print(\"I will generate a number, and you have to guess the numbers one digit at a time.\")
print(\"For every number in the wrong place, you get a cow. For every one in the right place, you get a bull.\")
print(\"The game ends when you get 4 bulls!\")
print(\"Type exit at any prompt to exit.\")
while playing:
user_guess = input(\"Give me your best guess!\")
if user_guess == \"exit\":
break
cowbullcount = compare_numbers(number,user_guess)
guesses+=1
print(\"You have \"+ str(cowbullcount[0]) + \" cows, and \" + str(cowbullcount[1]) + \" bulls.\")
if cowbullcount[1]==4:
playing = False
print(\"You win the game after \" + str(guesses) + \"! The number was \"+str(number))
break #redundant exit
else:
print(\"Your guess isn\'t quite right, try again.\")


