Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # !python3
- # This is a small test/game which asks the user to enter a four digit number.
- # The number is then compared with a previously computer generated number -
- # the players goal is to guess the computer generated number correctly.
- # For each attempt the player sees the result with a "cow" and "bull" count.
- # legend:
- # cow = a user number matched exactly at the position within the random four digit number (4 cows = win)
- # bull = a user number can be found within the digit number list, but at a different position
- import re
- from random import randint
- # the following function creates a random 4-digit list which contains values
- # within the range of 0 to 9 for each element
- def randomFourDigitList():
- tmplist = []
- while len(tmplist) < 4:
- value = randint(0,9)
- if value not in tmplist:
- tmplist.append(value)
- return sorted(tmplist)
- # converts the user input to a real list object with integer type elements
- def convertToList(inputString):
- list = [int(x) for x in inputString]
- return list
- # actual game start, the player is being prompted to enter a four digit number
- print('Welcome to the Cows and Bulls Game!\nEnter a number:')
- bull = 0
- cow = 0
- # a random list is being created, called tmplist, by the use of the previously
- # created method "randomFourDigitList"
- tmplist = randomFourDigitList()
- # the user needs to enter a guess what the random list/digits look like
- userGuess = input()
- # the script tests if the user really entered a four digit number.
- # if the input is sth. different the script prompts the user to enter a value again
- while not re.match('^\d\d\d\d$', userGuess):
- print ('Error! Make sure you only use four digits from 0 to 9 as your input.')
- userGuess = input('Try again: ')
- else:
- # that part is the actual comparison between the random list and the users input
- # it also prints out the cows and/or bulls which are hit
- userGuess = convertToList(userGuess)
- while tmplist != userGuess:
- for i, x in enumerate(tmplist):
- print(str(tmplist[i])+str(userGuess[i]))
- if int(tmplist[i]) == int(userGuess[i]):
- cow += 1
- elif int(tmplist[i]) != int(userGuess[i]):
- if int(userGuess[i]) in tmplist:
- bull += 1
- cowString = ''
- bullString = ''
- if cow > 1:
- cowString = 's'
- elif bull > 1:
- bullString = 's'
- print(str(cow)+' cow'+cowString+', '+str(bull)+' bull'+bullString )
- bull = 0
- cow = 0
- userGuess = input('Try again: ')
- userGuess = convertToList(userGuess)
- # once the user guesses all the digits correctly the game ends and prints out the
- # random number which has been guessed
- print("Success! The correct numbers are "+str(tmplist)[1:-1]+"!")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement