You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Mastermind游戏代码中集成类?新手开发问题求解

优化Mastermind游戏:类集成与输入错误处理指南

嘿,作为编程新手能完成Mastermind的基础版本已经超棒了!咱们一步步解决你遇到的两个核心问题~

一、类的集成:拆分模块让代码更精简可维护

把游戏拆成不同职责的类,能让代码逻辑更清晰,也方便后续扩展。咱们可以把Mastermind的核心功能分成3个类,用主类把它们集成起来:

  • CodeMaker:专门负责生成随机的秘密颜色序列
  • CodeBreaker:处理玩家输入、验证输入格式、计算猜测结果(位置全对/颜色对位置错的数量)
  • MastermindGame:控制游戏整体流程,整合前两个类的功能,管理猜测次数

给你个简单的示例代码参考:

import random

# 生成秘密序列的类
class CodeMaker:
    def __init__(self, available_colors, code_length):
        self.colors = available_colors
        self.length = code_length
    
    def generate_secret_code(self):
        return [random.choice(self.colors) for _ in range(self.length)]

# 处理玩家猜测的类
class CodeBreaker:
    def __init__(self, available_colors, code_length):
        self.colors = available_colors
        self.length = code_length
    
    def check_guess_validity(self, guess):
        # 验证输入长度和颜色合法性
        if len(guess) != self.length:
            raise ValueError(f"猜测必须是{self.length}个颜色!")
        for color in guess:
            if color not in self.colors:
                raise ValueError(f"颜色只能是{self.colors}中的一种!")
        return True
    
    def calculate_match_result(self, guess, secret_code):
        # 计算位置和颜色都匹配的数量
        exact_matches = sum(g == s for g, s in zip(guess, secret_code))
        # 计算颜色匹配但位置不对的数量
        temp_guess = guess.copy()
        temp_code = secret_code.copy()
        # 先移除完全匹配的元素
        for g, s in zip(guess, secret_code):
            if g == s:
                temp_guess.remove(g)
                temp_code.remove(s)
        color_matches = sum(1 for color in temp_guess if color in temp_code)
        return exact_matches, color_matches

# 游戏主类,集成上面两个类
class MastermindGame:
    def __init__(self, colors=["红", "蓝", "绿", "黄", "紫", "橙"], code_length=4, max_guesses=10):
        self.colors = colors
        self.code_length = code_length
        self.max_guesses = max_guesses
        # 初始化两个功能类
        self.code_maker = CodeMaker(colors, code_length)
        self.code_breaker = CodeBreaker(colors, code_length)
        self.secret_code = self.code_maker.generate_secret_code()
    
    def start_game(self):
        print(f"欢迎玩Mastermind!请猜测由{self.code_length}个颜色组成的序列,可选颜色:{self.colors}")
        remaining_guesses = self.max_guesses
        
        while remaining_guesses > 0:
            print(f"剩余猜测次数:{remaining_guesses}")
            # 处理输入验证,无效输入不消耗次数
            valid_input = False
            while not valid_input:
                user_guess = input("请输入你的猜测(用空格分隔,比如:红 蓝 绿 黄):").split()
                try:
                    self.code_breaker.check_guess_validity(user_guess)
                    valid_input = True
                except ValueError as e:
                    print(f"输入错误:{e},请重新输入!")
            
            # 计算并展示结果
            exact, color_only = self.code_breaker.calculate_match_result(user_guess, self.secret_code)
            print(f"结果:{exact}个颜色位置都对,{color_only}个颜色对但位置错")
            
            if exact == self.code_length:
                print("恭喜你猜对了!游戏胜利🎉")
                return
            remaining_guesses -= 1
        
        print(f"游戏结束!正确答案是:{' '.join(self.secret_code)}")

# 启动游戏
if __name__ == "__main__":
    game = MastermindGame()
    game.start_game()

二、try-except处理输入错误:无效输入不占猜测次数

你看上面的代码里,我用了嵌套循环+try-except实现了这个逻辑:

  1. 外层循环控制游戏的猜测次数,内层循环专门处理输入验证
  2. 当玩家输入无效时,check_guess_validity会抛出ValueError,except块捕获后提示错误,然后继续内层循环让玩家重新输入
  3. 只有当输入验证通过(valid_input变为True),才会退出内层循环,进入结果计算环节,之后才会减少剩余猜测次数

核心逻辑就是:只有验证通过的输入才被算作一次有效猜测,错误输入只是让玩家重新输入,完全不消耗猜测次数。

内容的提问来源于stack exchange,提问作者madinge

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:56:37