Mastermind Game in Python

后端 未结 2 481
说谎
说谎 2021-01-17 05:57

I have already looked at this thread Python Mastermind Game Troubles on your website but the question I am asking is slightly different as I have been given a different task

2条回答
  •  孤城傲影
    2021-01-17 06:34

    You just forgot to reset your numberswrong variable to zero :)

    As a side note, to spot bugs, try to make your code simpler.

    • Count the number of right numbers, instead of the number of wrong ones!
    • Use lists instead of copy pasting code.
    • Once you feel more confortable with loops, use python generators
    • Use text formatting instead of string concatenation.
    • Name your variables with names that make sense (avoid "c" when you can call it "num_tries")
    • Comment!

    It you try to apply all this advices, you final code should look like this:

    from random import randint
    
    # Init variable
    numbers = [randint(1, 9) for _ in range(4)]
    num_tries = 0
    guesses = None
    
    # Loop while numbers and guesses are not the same.
    while numbers != guesses:
        # Ask user to guess the 4 values
        guesses = [
            int(input("guess the first number: ")),
            int(input("guess the second number: ")),
            int(input("guess the third number: ")),
            int(input("guess the fourth number: "))
        ]
    
        num_tries += 1
    
        # Display message with number of right numbers.
        num_right_numbers = len([1 for i in range(4) if numbers[i] == guesses[i]])
        print 'You got {0} numbers right.'.format(num_right_numbers)
    
    # User won, print message and quit.
    print 'Well Done!'
    print 'It took you {0} tries to guess the number!'.format(num_tries)
    

提交回复
热议问题