Skip to content

Instantly share code, notes, and snippets.

@hiramf
Last active March 12, 2017 00:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hiramf/9f190f86d84b709074ce5551740d1614 to your computer and use it in GitHub Desktop.
Save hiramf/9f190f86d84b709074ce5551740d1614 to your computer and use it in GitHub Desktop.
PracticePython.org Excercise 18
# -*- coding: utf-8 -*-
#Excercise 18: Cows and Bulls Game
'''
This is the given example for what the __main__ method does:
def square(num):
return num * num
if __name__=="__main__":
user_num = input("Give me a number: ")
print(square(num))
'''
"""
Create a program that will play the “cows and bulls” game with the user. The game works like this:
Randomly generate a 4-digit number. Ask the user to guess a 4-digit number. For every digit that the
user guessed correctly in the correct place, they have a “cow”. For every digit the user guessed
correctly in the wrong place is a “bull.” Every time the user makes a guess, tell them how many
“cows” and “bulls” they have. Once the user guesses the correct number, the game is over. Keep track
of the number of guesses the user makes throughout teh game and tell the user at the end.
Say the number generated by the computer is 1038. An example interaction could look like this:
Welcome to the Cows and Bulls Game!
Enter a number:
>>> 1234
2 cows, 0 bulls
>>> 1256
1 cow, 1 bull
...
"""
def play_game():
def gen_num():
import random
return random.sample(range(0,9),4)
num = gen_num()
print(num) #show generated number
g = 1
guess = 0
while True:
guess = input('guess a 4 digit number: ')
if guess == 'exit':
break
guess = [int(d) for d in str(guess)]
if guess == num:
print('you got it!')
print('and it took you %s tries!' % g)
break
else:
b = 0
c = 0
for i in range(4):
if guess[i] == num[i]: c += 1
else:
if guess[i] in num:
b += 1
g += 1
print(str(c)+ ' cows, ' + str(b)+ ' bulls.')
if __name__=="__main__":
play_game()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment