-
Notifications
You must be signed in to change notification settings - Fork 0
/
cows_and_bulls.py
96 lines (52 loc) · 1.98 KB
/
cows_and_bulls.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# _*_ coding:utf-8 _*_
# Cows and bulss
# 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
import random
def isNumber(n):
try:
int(n)
return True
except:
return False
def enterGuess():
x = False
while x == False:
guess = raw_input("Enter a four digit number: ")
if isNumber(guess) == False:
x = False
elif isNumber(guess) == True:
if int(guess) < 1000 or int(guess) > 9999:
x = False
else:
x = True
return guess
def cowBull(a,b):
cowsbulls=[0,0]
for i in range(0,4):
if a[i]==b[i]:
cowsbulls[0]+=1
if a[i]!=b[i]:
if a[i] in b:
cowsbulls[1]+=1
return cowsbulls
number=str(random.randint(1000,10000))
cowsbulls=[0,0]
tried=1
while cowsbulls[0]<4:
guess=enterGuess()
cowsbulls=cowBull(guess,number)
print "cows=",cowsbulls[0], " bulls=",cowsbulls[1]
tried+=1
print "Your try count:", tried,"\n","cows=",cowsbulls[0],"\n","bulls=",cowsbulls[1]
print "Number generated by PC=",number