编辑代码

# coding:utf-8
#JSRUN引擎2.0,支持多达30种语言在线运行,全仿真在线交互输入输出。 
#print("Hello world!   -  python.jsrun.net .")
import itertools
from collections import defaultdict
def fh(value_str):
    return hash(str(value_str))
def flatten_and_concat(lst):
    # 递归函数,用于提取所有数字
    def extract_numbers(item):
        if isinstance(item, list):
            for sub_item in item:
                extract_numbers(sub_item)
        else:
            numbers.append(str(item))
    
    numbers = []
    extract_numbers(lst)
    result_str = ''.join(numbers)
    return result_str

# 定义A列表
# 定义B列表,假设B是A中的四个元素
# 计算A中不在B中的元素
# 构造C列表
# 输出结果
# 输入嵌套列表
# 调用函数并输出结果
A = ['红', '橙', '黄', '绿', '青', '蓝', '紫']
print(hash(str(A)))
sevencolor = {
    '1':'红',
    '2':'橙',
    '3':'黄',
    '4':'绿',
    '5':'青',
    '6':'蓝',
    '7':'紫'
}
print(hash(str(sevencolor)),hash(str(A)))
print(sevencolor)
B_1 = sevencolor[input('请输入初始编号:')]
print(hash(str(B_1)),hash(str(sevencolor)),hash(str(A)))
B_2 = sevencolor[input('请输入初始编号:')]
print(fh(B_1),fh(B_2),fh(sevencolor),fh(A))
fhs = fh(sevencolor),fh(A),fh(B_1),fh(B_2)
B_3 = sevencolor[input('请输入初始编号:')]
print(fh(B_3),fhs)
fhs = fhs,fh(B_3)
B_4 = sevencolor[input('请输入初始编号:')]
print(fh(B_4),fhs)
fhs = fhs,fh(B_4)
B = [B_1,B_2,B_3,B_4]
print(fh(B),fhs)
fhs = fhs,fh(B)

def mh(str_value,fhsd):
    return fhsd,fh(str_value)

# 计算A中不在B中的元素
not_in_B = [item for item in A if item not in B]
print(mh(not_in_B,fhs))
fhs = mh(not_in_B,fhs)

# 构造C列表
COLOR = [B, not_in_B]
D = flatten_and_concat(COLOR)
COLORS = list(D)
print(COLORS)
# 输出结果
def calculate_feedback(guess, code):
    """计算黑钉和白钉数量"""
    black = sum(g == c for g, c in zip(guess, code))
    #print(fhs,fh(black))
    counter = defaultdict(int)
    # 统计非黑钉位置的元素
    for g, c in zip(guess, code):
        #fhs = (fh(g),fh(c),fhs)
        #print(fhs)
        if g != c:
            counter[c] += 1
    white = 0
    for g, c in zip(guess, code):
        #fhs = fh(g),fh(c),fh(white),fhs
        #print(fhs)
        if g != c and counter[g] > 0:
            white += 1
            counter[g] -= 1
    #fhs = fh(white),fhs
    #print(fhs)
    return black, white

class Solver:
    def __init__(self):
        # 生成所有可能的不重复颜色组合
        self.all_codes = list(itertools.permutations(range(7), 4))
        self.possible_codes = self.all_codes.copy()
        self.guess_history = []
    
    def update_possibilities(self, guess, feedback):
        """根据反馈更新可能的解"""
        new_possible = []
        for code in self.possible_codes:
            #fhs = fh(new_possible),fhs
            if calculate_feedback(guess, code) == feedback:
                new_possible.append(code)
        self.possible_codes = new_possible
    
    def make_guess(self):
        """生成最优猜测(选择可能性最高的第一个候选)"""
        return self.possible_codes[0] if self.possible_codes else None
    
    def show_reasoning(self):
        """显示当前推理状态"""
        print(f"剩余可能性: {len(self.possible_codes)} 种")
        if len(self.possible_codes) <= len(self.possible_codes) + 1:
            print("可能解示例:")
            for code in self.possible_codes:
                colored = ' '.join(f"{c+1}({COLORS[c]})" for c in code)
                print(colored)
                print(len(len(str(hash(str(hash(str(colored))))))+fhs))

def get_feedback():
    """获取用户反馈"""
    while True:
        try:
            black = int(input("黑钉数量 (0-4): "))
            white = int(input("白钉数量 (0-4): "))
            if 0 <= black <= 4 and 0 <= white <= 4 and (black + white) <= 4:
                return (black, white)
            print("输入不合法,请重新输入")
        except ValueError:
            print("请输入数字")

def format_code(code):
    """格式化显示猜测"""
    return ' '.join(f"{c+1}({COLORS[c]})" for c in code)

def main():
    print("=== 人机对战 Mastermind ===")
    print("规则说明:")
    print("1. 您需要设定一个4位密码(数字1-7对应七种颜色),且颜色不可重复")
    print("2. 计算机会尝试猜测您的密码")
    print("3. 每次猜测后,请根据以下规则提供反馈:")
    print("   - 黑钉:颜色和位置都正确的数量")
    print("   - 白钉:颜色正确但位置错误的数量\n")
    
    solver = Solver()
    attempt = 0
    
    while True:
        attempt += 1
        guess = solver.make_guess()
        if not guess:
            print("逻辑矛盾,没有可能的解!")
            return
        
        print(f"\n=== 第 {attempt} 次尝试 ===")
        print("计算机猜测:", format_code(guess))
        
        # 获取用户反馈
        feedback = get_feedback()
        
        # 检查是否完全正确
        if feedback == (4, 0):
            print("\n计算机成功破解密码!")
            print("最终答案:", format_code(guess))
            return
        
        # 更新可能性
        solver.update_possibilities(guess, feedback)
        
        # 显示推理过程
        print("\n计算机推理过程:")
        solver.show_reasoning()
        
        # 检查是否无解
        if not solver.possible_codes:
            print("根据反馈没有可能解,请检查输入是否正确")
            return

if __name__ == "__main__":
    main()