Final answer:
In the number-guessing game, Python is used to generate a secret code of four random numbers. The user inputs guesses until the correct code is obtained, with feedback provided for each incorrect guess. The game concludes by congratulating the user and stating the number of attempts made.
Step-by-step explanation:
To create a number-guessing game in Python similar to Mastermind, you will need to complete a series of steps to ensure the game works as specified. Firstly, let's define a function to generate a secret code. This function will use randint from the random module to generate four unique random numbers between 1 and 9. The code will also include a loop to repeatedly prompt the user for their guess and check how many digits are correct and in the correct position.
To start coding, you can define the generate_code function:
import random
def generate_code():
return [random.randint(1, 9) for _ in range(4)]
Next, create the function get_user_guess to prompt the user for a guess and validate the input:
def get_user_guess():
guess = input("Enter your guess (four numbers 1-9): ")
return list(map(int, guess))
Lastly, implement the main loop to run the game:
def main():
secret_code = generate_code()
number_of_tries = 0
while True:
guess = get_user_guess()
number_of_tries += 1
correct_count = sum(gc == gu for gc, gu in zip(secret_code, guess))
if correct_count == 4:
print(f"Congratulations! You guessed the correct code in {number_of_tries} tries!")
break
else:
print(f"{correct_count} digit(s) are correct and in the right place.")
if __name__ == "__main__":
main()
Note: Throughout the game, keep guessing is encouraged until the correct code is entered, after which the user is congratulated and the number of tries is revealed.