Skip to content

Instantly share code, notes, and snippets.

@mathewcohle
Created March 17, 2017 08:50
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 mathewcohle/14e5dc171b1874f6747bb165afa960d0 to your computer and use it in GitHub Desktop.
Save mathewcohle/14e5dc171b1874f6747bb165afa960d0 to your computer and use it in GitHub Desktop.
import random
class BullsAndCows:
def __init__(self):
self.NUMOFDIGITS = 4
def play(self):
print(
"Hi buddy!\n",
"Do you fancy play with me bulls and cows? The rules are simple:\n",
"\t1. I will generated random {} digits for you\n".format(self.NUMOFDIGITS),
"\t2. You are supposed to guess the generated number\n",
"Let's play a bulls and cows game!\n",
"Enter a number:")
self.game_number = self._generate_number()
num_of_tries = 0
while(1):
inp = str(input(">"))
valid_input = self._validate_input(inp)
num_of_tries += 1
if(valid_input):
bulls, cows = self._get_bulls_cows(inp)
print("{} bulls, {} cows.".format(bulls, cows))
if(bulls == self.NUMOFDIGITS):
break
print("Correct, you've guessed the right number in {} guesses!".format(num_of_tries))
if num_of_tries < 4:
performance = "amazing"
elif num_of_tries < 7:
performance = "average"
else:
performance = "not so good"
print("That's {} result.".format(performance))
def _get_bulls_cows(self, inp):
bulls = 0
cows = 0
for i, digit in enumerate(inp):
if digit in self.game_number:
if digit == self.game_number[i]:
bulls += 1
else:
cows += 1
return bulls, cows
def _generate_number(self):
digits = [str(x) for x in range(0, 10)]
return "".join(random.sample(digits, self.NUMOFDIGITS))
def _validate_input(self, inp):
try:
int(inp)
except:
print("Man, enter a number, not {}!".format(inp))
return 0
if len(inp) != self.NUMOFDIGITS:
print("You are guessing {} digits number, not {}.".format(self.NUMOFDIGITS, len(inp)))
return 0
if len(set(inp)) != self.NUMOFDIGITS:
print("You are supposed to guess {} distinct digits.".format(self.NUMOFDIGITS))
return 0
return 1
if __name__ == "__main__":
game = BullsAndCows()
game.play()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment