编辑代码

# coding:utf-8
#JSRUN引擎2.0,支持多达30种语言在线运行,全仿真在线交互输入输出。 
#print("Hello world!   -  python.jsrun.net .")
import random
from itertools import product

COLORS = ['red', 'orange', 'yellow', 'green', 'porden', 'blue', 'purple']

class ColorGame:
    def __init__(self):
        self.answer = None
        self.initial_conditions = []
        self.attempts = 0
    
    def validate_condition(self, guess, a, b, c):
        # 计算A/B/C值的核心逻辑
        a_count = sum(g == a for g, a in zip(guess, self.answer))
        common = sum(min(guess.count(c), self.answer.count(c)) for c in set(guess))
        b_count = common - a_count
        c_count = 4 - a_count - b_count
        return (a_count, b_count, c_count) == (a, b, c)
    
    def generate_answer(self, conditions):
        # 生成所有可能的组合并筛选符合条件的
        all_combinations = product(COLORS, repeat=4)
        valid = []
        for comb in all_combinations:
            self.answer = comb
            if all(self.validate_condition(*cond) for cond in conditions):
                valid.append(comb)
        return random.choice(valid) if valid else None
    
    def get_feedback(self, guess):
        # 获取用户输入的猜测结果
        a = sum(g == a for g, a in zip(guess, self.answer))
        common = sum(min(guess.count(c), self.answer.count(c)) for c in set(guess))
        b = common - a
        c = 4 - a - b
        return f"{a}A{b}B{c}C"
    
    def start_game(self):
        print("请输入初始条件(格式:颜色1 颜色2 颜色3 颜色4 |aAbBcC),输入end开始游戏")
        while True:
            inp = input().strip()
            if inp.lower() == 'end':
                break
            try:
                colors, result = inp.split('|')
                colors = colors.strip().split()
                a, b, c = map(int, [result[0], result[2], result[4]])
                self.initial_conditions.append((colors, a, b, c))
            except:
                print("输入格式错误,请重新输入")
        
        # 生成有效答案
        conditions = []
        for cond in self.initial_conditions:
            colors, a, b, c = cond
            conditions.append((colors, a, b, c))
        
        self.answer = self.generate_answer(conditions)
        if not self.answer:
            print("初始条件矛盾,无法生成答案!")
            return
        
        print("\n游戏开始!你有7次猜测机会")
        for _ in range(7):
            self.attempts += 1
            while True:
                guess = input(f"第{self.attempts}次猜测(输入4个颜色,用空格分隔):").strip().split()
                if len(guess) != 4 or any(c not in COLORS for c in guess):
                    print(f"请输入4个有效颜色,可选颜色:{' '.join(COLORS)}")
                else:
                    break
            
            feedback = self.get_feedback(guess)
            print(f"结果:{feedback}")
            
            if feedback == "4A0B0C":
                print("恭喜你,猜对了!")
                return
        
        print(f"\n游戏失败!正确答案是:{' '.join(self.answer)}")

if __name__ == "__main__":
    game = ColorGame()
    game.start_game()