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

Python战队对战功能实现:嵌套列表操作、输入校验与战斗逻辑编写

Python战队对战功能实现代码

完整可运行代码

import random

def get_valid_team(team_list, input_prompt):
    """校验输入的战队名称是否存在,存在则返回对应战队数据子列表"""
    while True:
        input_name = input(input_prompt).strip()
        for team in team_list:
            if team[0] == input_name:
                return team
        print("输入的战队不存在,请重新输入")

def match(team_list):
    # 1. 校验获取两支对战战队
    team1 = get_valid_team(team_list, "Please select team:")
    # 确保两支战队不重复
    while True:
        team2 = get_valid_team(team_list, "Please select another team:")
        if team2 != team1:
            break
        print("不能选择同一支战队对战,请重新输入")

    # 2. 获取对战总轮次
    while True:
        try:
            battle_rounds = int(input("How many rounds would you like to go for?"))
            if battle_rounds > 0:
                break
            print("轮次必须为正整数,请重新输入")
        except ValueError:
            print("输入格式错误,请输入数字")
    num_of_battles = 0

    # 对战前重置两队健康值为100(可根据需求移除该逻辑保留原有健康值)
    team1[4] = 100
    team2[4] = 100

    # 3. 对战循环
    while num_of_battles < battle_rounds and team1[4] > 0 and team2[4] > 0:
        num_of_battles += 1
        # 生成两队各自受到的伤害
        damage1 = random.randint(1, 50)
        damage2 = random.randint(1, 50)
        # 更新健康值,最低为0
        team1[4] = max(0, team1[4] - damage1)
        team2[4] = max(0, team2[4] - damage2)
        # 输出本轮结果
        print(f"--- 第{num_of_battles}轮对战结果 ---")
        print(f"{team1[0]} 受到伤害{damage1},剩余健康值:{team1[4]}")
        print(f"{team2[0]} 受到伤害{damage2},剩余健康值:{team2[4]}\n")

    # 4. 胜负判定与数据更新
    # 两队参赛场次都+1
    team1[1] += 1
    team2[1] += 1

    print("=== 对战最终结果 ===")
    if team1[4] > team2[4]:
        winner = team1
        loser = team2
        print(f"{winner[0]} 获胜!")
    elif team2[4] > team1[4]:
        winner = team2
        loser = team1
        print(f"{winner[0]} 获胜!")
    else:
        print("双方平局!")
        winner = None

    if winner:
        winner[2] += 1
        loser[3] += 1
        if loser[4] == 0:
            print(f"{loser[0]} 已战败,健康值归零")

# 示例使用
if __name__ == "__main__":
    # 初始化战队列表,格式:[战队名, 已参赛场次, 胜场数, 负场数, 健康值]
    team_list = [
        ["红队", 0, 0, 0, 100],
        ["蓝队", 0, 0, 0, 100],
        ["绿队", 0, 0, 0, 100]
    ]
    match(team_list)
    # 打印更新后的战队列表验证数据
    print("\n更新后的战队数据:")
    for t in team_list:
        print(t)

核心逻辑说明

  • 战队名校验:通过get_valid_team辅助函数循环接收用户输入,遍历战队列表匹配名称,匹配成功才返回对应战队的子列表,因为Python列表是可变对象,后续对战队子列表的修改会直接同步到原team_list中,无需额外回写
  • 输入容错:对战轮次输入增加了格式校验,避免用户输入非数字或者负数导致程序崩溃
  • 健康值处理:扣减伤害后用max(0, 健康值)保证健康值不会出现负数
  • 数据更新:对战结束后自动同步两队的参赛场次、胜场/负场数到原列表,无需额外操作

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 09:45:04