|
| 1 | +import random |
| 2 | + |
| 3 | +def generate_code(length): |
| 4 | + return [random.randint(1, 6) for _ in range(length)] |
| 5 | + |
| 6 | +def evaluate_guess(secret, guess): |
| 7 | + correct_positions = sum(1 for i in range(len(secret)) if secret[i] == guess[i]) |
| 8 | + correct_numbers = len(set(secret) & set(guess)) - correct_positions |
| 9 | + return correct_positions, correct_numbers |
| 10 | + |
| 11 | +def ai_brute_force(secret, code_length): |
| 12 | + possible_codes = [[i, j, k, l] for i in range(1, 7) for j in range(1, 7) |
| 13 | + for k in range(1, 7) for l in range(1, 7)] |
| 14 | + attempts = 0 |
| 15 | + while True: |
| 16 | + guess = possible_codes.pop(0) |
| 17 | + attempts += 1 |
| 18 | + print(f"AI guess #{attempts}: {guess}") |
| 19 | + correct_positions, correct_numbers = evaluate_guess(secret, guess) |
| 20 | + |
| 21 | + if correct_positions == code_length: |
| 22 | + print(f"AI cracked the code in {attempts} attempts!") |
| 23 | + break |
| 24 | + |
| 25 | + possible_codes = [code for code in possible_codes if evaluate_guess(code, guess) == (correct_positions, correct_numbers)] |
| 26 | + |
| 27 | +def main(): |
| 28 | + code_length = 4 |
| 29 | + max_attempts = 10 |
| 30 | + secret_code = generate_code(code_length) |
| 31 | + |
| 32 | + print("Welcome to the Codebreaker Game!") |
| 33 | + print("Try to guess the AI's secret code.") |
| 34 | + print(f"The secret code consists of {code_length} numbers between 1 and 6.") |
| 35 | + |
| 36 | + player_code = [] |
| 37 | + for attempt in range(1, max_attempts + 1): |
| 38 | + while True: |
| 39 | + try: |
| 40 | + player_code = [int(num) for num in input(f"Attempt #{attempt}: Enter your code (space-separated): ").split()] |
| 41 | + if len(player_code) != code_length or any(num < 1 or num > 6 for num in player_code): |
| 42 | + raise ValueError |
| 43 | + break |
| 44 | + except ValueError: |
| 45 | + print("Invalid input. Enter a valid code.") |
| 46 | + |
| 47 | + correct_positions, correct_numbers = evaluate_guess(secret_code, player_code) |
| 48 | + print(f"Result: {correct_positions} in correct position, {correct_numbers} correct numbers but in wrong position.") |
| 49 | + |
| 50 | + if correct_positions == code_length: |
| 51 | + print(f"Congratulations! You cracked the code in {attempt} attempts!") |
| 52 | + break |
| 53 | + else: |
| 54 | + print(f"Sorry, you couldn't crack the code. The AI's secret code was: {secret_code}") |
| 55 | + |
| 56 | +if __name__ == "__main__": |
| 57 | + main() |
0 commit comments