Hi Everyone,

Sorry if this has a totally obvious solution. I am trying to write a simple cows and bulls game; the program generates a secret number, the player has to guess it, the program then compares the guess to the secret number and tells the player that either they have guessed it, or they have gotten x number of cows (right number in right position) and x number of bulls (right number in wrong position).

I've had a go but I have been working on this for long it's all jumbled up. It just doesn't work as it is below. Can anyone help?

import random

secret_number = random.randrange(100) + 1

# Secret number printed here just for testing purposes
print secret_number

guess = int(raw_input("Guess a number between 1 and 100: "))
tries = 1

if guess == secret_number:
    print "\nYou guessed it! The number was", secret_number
else:
    while count != len(secret_number_str):
        if guess[len(secret_number_str) - (len(secret_number_str) - count)]== secret_number_str[len(secret_number_str) - (len(secret_number_str) - count)]:
            cows += 1
        elif guess[len(secret_number_str) - (len(secret_number_str) - count)] in secret_number_str:
            bulls += 1
        tries+= 1
        print "\nYou guess has", cows, "cows and", bulls, "bulls \n"

raw_input("\n\nPress the enter key to exit.")
Member Avatar for masterofpuppets

hi, by the way this is a nice game :)
try this:

import random

number = random.randrange( 100 ) + 1
numberString = str( number )

guess = raw_input( "Guess a number between 1 and 100: " )

while guess != numberString:
    cows, bulls = 0, 0
    for i in range( len( guess ) ):
        if guess[ i ] == numberString[ i ]:
            cows += 1
        elif guess[ i ] in numberString:
            bulls += 1
    print "Your guess has", cows, "cow(s) and", bulls, "bull(s).\n"
    guess = raw_input( "Guess again: " )

# If the program gets to this stage the number is guessed
print "You guessed it! The number was", numberString

Hope this helps. I will test it now and if there's a problem I'll post it here :) again nice game...

Member Avatar for masterofpuppets

I just tested it and the number was 43. What are the rules of the game for this situation, i.e if my guess is 33.
I mean this:

>>>number = 43
>>>Enter your guess: 33
>>>Your guess has 1 cows and 1 bulls.

is that correct? :)

Hi - thank you for replying, this really is a friendly forum! I've got it all worked out now :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.