Python游戏开发:如何避免用大量if语句匹配数字模式
问题与解决方案
问题描述
刚完成CS50的Python基础学习,正在开发一款练习用小游戏:用户输入5个0-9的数字,程序需匹配预设的20种固定数字模式并计分。目前用大量if语句实现匹配,但写法冗余且维护麻烦,尝试过字典跳转表但没效果,求可行解决方案。
游戏规则示例
用户输入:1,2,3,4,5
可匹配模式及对应分数:
- a,a+1,a+2,a+3,a+4 → 1分
- a,a+2,a+4,a+6,a+8 → 2分
- a,a+1,a+3,a+5,a+7 → 3分
此时用户得1分。
当前实现问题
当前代码采用大量连续if语句判断,示例如下:
if ..... if ..... if .....
这种写法不仅代码冗长,后续新增、修改模式时成本极高。
解决方案:模式函数化+统一管理
核心思路是把每种模式的判断逻辑封装成独立函数,将「模式判断函数-对应分数」的组合存入列表,最后遍历列表逐一匹配用户输入、计算总分。
步骤1:预处理用户输入
先将用户输入的字符串转换为整数列表(若模式不要求输入顺序,可先排序,根据实际规则调整):
def process_input(user_input): # 处理用户输入的逗号分隔字符串,比如"1,2,3,4,5" nums = list(map(int, user_input.split(','))) # 若模式不要求输入顺序,可开启排序 # nums.sort() return nums
步骤2:定义模式判断函数
针对每种模式编写独立判断函数,接收数字列表,返回True/False表示是否匹配:
# 模式1:连续递增1的序列(a,a+1,a+2,a+3,a+4) def is_consecutive_1(nums): for i in range(1, 5): if nums[i] != nums[i-1] + 1: return False return True # 模式2:连续递增2的序列(a,a+2,a+4,a+6,a+8) def is_consecutive_2(nums): for i in range(1, 5): if nums[i] != nums[i-1] + 2: return False return True # 模式3:a,a+1,a+3,a+5,a+7 def is_pattern_3(nums): expected = [nums[0], nums[0]+1, nums[0]+3, nums[0]+5, nums[0]+7] return nums == expected
步骤3:统一管理模式与分数
把所有模式函数和对应分数存入列表,后续新增/修改模式只需调整此列表:
# 模式列表:每个元素为(判断函数, 对应分数) patterns = [ (is_consecutive_1, 1), (is_consecutive_2, 2), (is_pattern_3, 3), # 继续添加剩余17种模式... ]
步骤4:计算总分
遍历模式列表,检查匹配情况并累加分数:
def calculate_score(nums): total = 0 for pattern_func, score in patterns: if pattern_func(nums): total += score return total # 示例使用 user_input = "1,2,3,4,5" nums = process_input(user_input) print(f"用户得分:{calculate_score(nums)}") # 输出:用户得分:1
额外优化:处理多模式匹配
若存在输入同时符合多种模式的情况,可选择只取最高分:
def calculate_max_score(nums): max_score = 0 for pattern_func, score in patterns: if pattern_func(nums) and score > max_score: max_score = score return max_score
内容的提问来源于stack exchange,提问作者Koh Cw
相关产品推荐
相关产品推荐

