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

Python Chomp游戏功能修改:支持输入数值直接删除对应区块

Chomp游戏按数值删除功能实现方案

实现逻辑

  • 新增坐标查找函数:遍历当前巧克力矩阵,匹配用户输入的数值,返回对应坐标,匹配失败则提示输入无效
  • 跳过左上角的毒块"P ",不允许用户选中该位置
  • 修复原代码隐含问题:原代码每次删除都会重新生成完整巧克力块,不会保留上一次删除的状态,同时递归调用main()会导致栈溢出,改为循环实现游戏流程

修改后完整代码

def create_chocolate_bar(rows, columns):
    # 生成巧克力块矩阵
    chocolate_bar = []
    if 1 <= rows <=9 and 1 <= columns <=9:
        for r in range(1, rows+1):
            columns_worth = []
            for k in range(1,columns+1):
                each_columns_worth = r*10 + k
                columns_worth.append(each_columns_worth)
            chocolate_bar.append(columns_worth)
        chocolate_bar[0][0] = "P "
        return chocolate_bar
    else:
        return False

def print_chocolate_bar(a):
    # 打印当前巧克力块
    for current_row in range(len(a)):
        for current_col in range(len(a[current_row])):
            print(a[current_row][current_col], end=" ")
        print("\n")

def chomp(matrix, row, col):
    # 删除对应坐标右下角的所有巧克力块
    for x in range(row, len(matrix)):
        del matrix[x][col:]
    print_chocolate_bar(matrix)

def check_winner(matrix):
    # 判断游戏是否结束,只剩毒块则结束
    if len(matrix) == 1 and len(matrix[0]) == 1:
        return True
    else:
        return False

def find_position(matrix, target):
    # 根据输入的数值查找对应的行列坐标
    for row_idx in range(len(matrix)):
        for col_idx in range(len(matrix[row_idx])):
            # 跳过字符串类型的毒块,只匹配数字
            if type(matrix[row_idx][col_idx]) == int and matrix[row_idx][col_idx] == target:
                return row_idx, col_idx
    # 没找到对应数值返回无效坐标
    return -1, -1

def main():
    while True:
        rows = int(input("请问你想要巧克力块有多少行?"))
        columns = int(input("请问你想要巧克力块有多少列?"))
        current_matrix = create_chocolate_bar(rows, columns)
        if not current_matrix:
            print("输入的行列数无效,请输入1-9之间的整数!")
            continue
        # 游戏主循环
        while True:
            print_chocolate_bar(current_matrix)
            if check_winner(current_matrix):
                print("游戏结束!你吃到了毒块!")
                break
            remove = input("是否要移除部分巧克力块?y/n:")
            if remove.lower() != "y":
                print("Goodbye!")
                return
            try:
                target_num = int(input("请输入你要移除的巧克力块数值:"))
            except ValueError:
                print("请输入有效的数字!")
                continue
            row, col = find_position(current_matrix, target_num)
            if row == -1 or col == -1:
                print("该数值不存在,请重新输入!")
                continue
            chomp(current_matrix, row, col)

if __name__ == "__main__":
    main()

关键修改说明

  1. 新增find_position函数,接收当前矩阵和用户输入的数值,遍历匹配到对应的行列坐标后返回,支持自动跳过左上角的毒块"P "
  2. 原main函数的递归调用改为循环实现,避免栈溢出风险,同时新增变量current_matrix存储当前游戏状态,不会每次删除都重新生成完整巧克力
  3. 新增输入合法性校验,处理用户输入非数字、输入不存在数值的异常情况
  4. 整合check_winner逻辑,游戏结束后自动提示并退出

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 09:15:02