python案例认为这次犯规该不该吃牌?

wen python案例 4

本文目录导读:

python案例认为这次犯规该不该吃牌?

  1. 方案一:基于规则的判断系统
  2. 方案二:更智能的机器学习判断(基于逻辑回归)
  3. 方案三:综合决策系统(带输出界面)
  4. 判罚逻辑说明

我来给你设计一个基于Python的足球犯规判罚判断案例,这个案例会模拟裁判AI,根据犯规的严重程度、位置、动作性质等因素,判断是否应该出示黄牌或红牌。

基于规则的判断系统

import random
from dataclasses import dataclass
from enum import Enum
class CardType(Enum):
    NO_CARD = "无牌"
    YELLOW = "黄牌"
    RED = "红牌"
@dataclass
class Foul:
    """犯规事件类"""
    action_type: str      # 犯规动作类型
    severity: int         # 严重程度 (1-10)
    position: str         # 犯规位置
    intentional: bool     # 是否故意
    last_man: bool        # 是否最后一名防守球员
    dangerous: bool       # 是否危险动作
    accumulated_fouls: int # 累计犯规次数
    match_time: int       # 比赛时间(分钟)
    score_diff: int       # 比分差距
class FootballReferee:
    """足球裁判AI类"""
    def __init__(self):
        # 犯规动作基础分值
        self.action_scores = {
            "拉扯": 3, "推搡": 4, "铲球": 5, "绊倒": 5,
            "肘击": 8, "踩踏": 9, "飞铲": 7, "手球": 2,
            "暴力行为": 10, "阻碍进攻": 2, "报复动作": 6
        }
        # 危险位置加成
        self.dangerous_positions = ["禁区内", "禁区前沿"]
        # 红牌直接动作
        self.direct_red_actions = ["暴力行为", "严重犯规", "恶意报复"]
    def evaluate_foul(self, foul: Foul) -> dict:
        """评估犯规是否应吃牌"""
        # 计算基础分值
        base_score = self.action_scores.get(foul.action_type, 5)
        # 严重程度加成分数
        final_score = base_score + (foul.severity - 5) * 0.6
        # 是否是最后一名防守球员
        if foul.last_man:
            final_score += 3
            print("⚠️ 破坏了明显得分机会,应加重处罚")
        # 是否故意犯规
        if foul.intentional:
            final_score += 2
            print("⚠️ 故意犯规,性质恶劣")
        # 是否危险动作
        if foul.dangerous:
            final_score += 2.5
            print("⚠️ 危险动作,威胁球员安全")
        # 位置加成
        if foul.position in self.dangerous_positions:
            final_score += 1.5
            print("⚠️ 区域位置敏感,可能破坏进攻机会")
        # 累计犯规次数
        if foul.accumulated_fouls >= 3:
            final_score += 0.5
            print(f"⚠️ 球员已有{foul.accumulated_fouls}次犯规记录")
        # 比赛时间(快结束时从严)
        if foul.match_time >= 85:
            final_score += 0.8
            print("⏰ 比赛末段,稳住场上局势考虑")
        # 出牌判断逻辑
        final_score = round(final_score, 1)
        # 直接红牌情况
        if foul.action_type in self.direct_red_actions:
            result = CardType.RED
            decision = "恶意犯规,直接红牌罚下!"
        # 过高分值 => 红牌
        elif final_score >= 9.0:
            result = CardType.RED
            decision = f"严重犯规 (评分:{final_score}),红牌罚下!"
        # 中等分值 => 黄牌
        elif final_score >= 6.0:
            result = CardType.YELLOW
            decision = f"明显犯规 (评分:{final_score}),出示黄牌警告"
        # 低分值 => 无牌
        else:
            result = CardType.NO_CARD
            decision = f"普通犯规 (评分:{final_score}),口头警告即可"
        return {
            "result": result,
            "score": final_score,
            "decision": decision,
            "detailed_factors": {
                "犯规类型": foul.action_type,
                "严重程度": foul.severity,
                "位置": foul.position,
                "故意性": "是" if foul.intentional else "否",
                "最后一名防守": "是" if foul.last_man else "否",
                "危险度": "高" if foul.dangerous else "低"
            }
        }
# 模拟测试案例
def test_cases():
    referee = FootballReferee()
    # 定义测试用例
    cases = [
        # 案例1: 禁区外战术犯规
        Foul("拉扯", 3, "中场", True, False, False, 1, 60, 0),
        # 案例2: 最后一名防守球员的犯规
        Foul("铲球", 6, "禁区内", True, True, False, 2, 75, 0),
        # 案例3: 暴力报复动作
        Foul("暴力行为", 10, "中场", False, False, True, 0, 30, -1),
        # 案例4: 危险飞铲
        Foul("飞铲", 8, "左路", False, False, True, 1, 50, 1),
        # 案例5: 普通推搡
        Foul("推搡", 4, "中场", False, False, False, 0, 20, 0),
        # 案例6: 禁区内手球破坏得分机会
        Foul("手球", 7, "禁区内", True, True, False, 0, 90, 0),
    ]
    case_names = [
        "中场战术犯规",
        "禁区最后一人犯规",
        "暴力报复动作",
        "危险飞铲",
        "普通推搡",
        "禁区内手球破坏得分"
    ]
    print("=" * 60)
    print("⚽ 足球裁判AI判罚系统 - 测试案例")
    print("=" * 60)
    for i, (case, name) in enumerate(zip(cases, case_names), 1):
        print(f"\n{'─' * 50}")
        print(f"案例{i}: {name}")
        print(f"{'─' * 50}")
        # 显示犯规细节
        print(f"📋 犯规详情:")
        print(f"   • 动作: {case.action_type}")
        print(f"   • 严重度: {case.severity}/10")
        print(f"   • 位置: {case.position}")
        print(f"   • 故意: {'是' if case.intentional else '否'}")
        print(f"   • 最后防守: {'是' if case.last_man else '否'}")
        print(f"   • 危险: {'是' if case.dangerous else '否'}")
        # 评估
        result = referee.evaluate_foul(case)
        print(f"\n⚖️ 裁判判定:")
        print(f"   • 结果: {result['result'].value}")
        print(f"   • 评分: {result['score']}")
        print(f"   • 判罚: {result['decision']}")
if __name__ == "__main__":
    test_cases()

更智能的机器学习判断(基于逻辑回归)

import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
class MLReferee:
    """基于机器学习的裁判AI"""
    def __init__(self):
        # 模拟训练数据(实际中应使用真实比赛数据)
        self.X_train, self.y_train = self.generate_training_data()
        self.scaler = StandardScaler()
        # 训练模型
        self.X_scaled = self.scaler.fit_transform(self.X_train)
        self.model = LogisticRegression(multi_class='auto', solver='lbfgs')
        self.model.fit(self.X_scaled, self.y_train)
    def generate_training_data(self):
        """生成模拟训练数据"""
        np.random.seed(42)
        n_samples = 1000
        # 特征: [犯规严重度, 位置敏感度, 是否故意, 是否最后一人, 危险度, 累计犯规, 时间压力]
        X = np.random.rand(n_samples, 7) 
        X[:, 0] *= 10  # 严重度 0-10
        # 生成标签: 0=无牌, 1=黄牌, 2=红牌
        y = []
        for row in X:
            score = row[0] * 0.5 + row[1] * 0.3 + row[2] * 0.4 + \
                    row[3] * 0.2 + row[4] * 0.3 + row[5] * 0.1
            if score > 4.0:
                y.append(2)  # 红牌
            elif score > 2.5:
                y.append(1)  # 黄牌
            else:
                y.append(0)  # 无牌
        return X, np.array(y)
    def predict(self, features):
        """预测犯规应得牌级别"""
        features_scaled = self.scaler.transform([features])
        prediction = self.model.predict(features_scaled)[0]
        probabilities = self.model.predict_proba(features_scaled)[0]
        return {
            "prediction": ["无牌", "黄牌", "红牌"][prediction],
            "probabilities": {
                "无牌": probabilities[0],
                "黄牌": probabilities[1], 
                "红牌": probabilities[2]
            }
        }
# 使用示例
def ml_test():
    ml_referee = MLReferee()
    print("\n🤖 机器学习裁判判断")
    print("=" * 50)
    # 测试样例: [严重度, 位置, 故意, 最后一人, 危险, 累计犯规, 时间]
    test_fouls = [
        [3, 0.2, 0, 0, 0.1, 0.2, 0.3],   # 普通犯规
        [7, 0.8, 1, 1, 0.7, 0.5, 0.8],   # 严重犯规
        [9, 0.9, 1, 0.5, 1, 0.8, 1.0],    # 极其恶劣
    ]
    for i, foul in enumerate(test_fouls, 1):
        result = ml_referee.predict(foul)
        print(f"\n案件{i} 预测结果: {result['prediction']}")
        print(f"  置信度: 无牌 {result['probabilities']['无牌']:.2%}, "
              f"黄牌 {result['probabilities']['黄牌']:.2%}, "
              f"红牌 {result['probabilities']['红牌']:.2%}")
if __name__ == "__main__":
    ml_test()

综合决策系统(带输出界面)

def interactive_referee():
    """交互式裁判系统"""
    print("🏟️  足球裁判AI判罚系统")
    print("=" * 50)
    print("\n请描述犯规情况:")
    # 收集信息
    actions = ["拉扯", "推搡", "铲球", "绊倒", "肘击", "踩踏", 
               "飞铲", "手球", "暴力行为", "阻碍进攻", "报复动作"]
    print("\n可选犯规动作:")
    for i, action in enumerate(actions, 1):
        print(f"  {i}. {action}")
    action_choice = int(input("请选择犯规动作编号: ")) - 1
    severity = int(input(f"严重程度 (1-10, 建议: 拉扯3-5, 铲球5-7, 暴力9-10): "))
    position = input("犯规位置 (中场/禁区内/禁区前沿/边路): ")
    intentional = input("是否故意? (y/n): ").lower() == 'y'
    last_man = input("是否为最后一名防守球员? (y/n): ").lower() == 'y'
    dangerous = input("是否危险动作? (y/n): ").lower() == 'y'
    fouls = int(input("累计犯规次数: "))
    match_time = int(input("比赛时间(分钟): "))
    # 创建犯规对象
    foul = Foul(
        action_type=actions[action_choice],
        severity=severity,
        position=position,
        intentional=intentional,
        last_man=last_man,
        dangerous=dangerous,
        accumulated_fouls=fouls,
        match_time=match_time,
        score_diff=0
    )
    # 评估
    referee = FootballReferee()
    result = referee.evaluate_foul(foul)
    # 输出结果
    print("\n" + "=" * 50)
    print(f"⚽ 最终判罚: {result['result'].value}")
    print(f"📊 综合评分: {result['score']}")
    print(f"💬 裁判说明: {result['decision']}")
    print("=" * 50)
if __name__ == "__main__":
    interactive_referee()

判罚逻辑说明

判罚因素权重

  • 动作性质 (基础分)
  • 严重程度 (0-10分)
  • 位置敏感性 (禁区附近加分)
  • 是否故意 (+2分)
  • 是否破坏得分机会 (+3分)
  • 危险性 (+2.5分)

判罚标准

  • 红牌 (评分≥9): 严重犯规、暴力行为
  • 黄牌 (评分6-9): 明显犯规、故意手球
  • 无牌 (评分<6): 普通犯规

特殊情况

  • 最后一名防守球员犯规 → 加重处罚
  • 恶意报复 → 直接红牌
  • 比赛末段违规 → 从严处理

这个系统可以模拟真实裁判的判断逻辑,你也可以根据实际比赛数据调整权重参数,使其更符合实际情况,运行这些代码,可以看到不同犯规情况的判罚结果!

抱歉,评论功能暂时关闭!