用python编写代码
时间: 2024-11-15 20:20:39 浏览: 9
用python编写代码找出1000以内的素数和双素数
5星 · 资源好评率100%
根据提供的文档内容,下面是一个基于Python编写的面向对象程序,用于模拟足球比赛。该程序包括联赛、球队、球员和教练的类定义,以及相关的方法实现。
### 类定义
#### 1. `League` 类
- `__init__(self, name)`: 构造函数
- `AddTeam(self, team)`: 添加球队
- `GetTeam(self, teamName)`: 获取球队
- `Print(self)`: 打印联赛信息
#### 2. `Team` 类
- **属性**:
- `name`: 球队名称
- `players`: 球队中的球员列表
- `coach`: 球队的教练
- **方法**:
- `__init__(self)`: 构造函数
- `AddPlayer(self, player)`: 添加球员
- `AddCoach(self, coach)`: 添加教练
- `GetRate(self)`: 计算球队综合能力
- `GetTeamAttackPower(self)`: 计算球队攻击力
- `GetTeamDefendPower(self)`: 计算球队防御力
- `GetTeamStabilityPower(self)`: 计算球队稳定性
- `Print(self)`: 打印球队信息
#### 3. `TeamMember` 类
- **属性**:
- `id`: 成员ID
- `name`: 成员姓名
- `position`: 成员位置
- **方法**:
- `__init__(self)`: 构造函数
- `GetRate(self)`: 抽象方法,由子类实现
#### 4. `Player` 类
- **属性**:
- 继承自 `TeamMember`
- `attackPower`: 攻击力
- `defendPower`: 防守力
- `stability`: 稳定性
- **方法**:
- `__init__(self)`: 构造函数
- `GetRate(self)`: 计算球员综合评分
#### 5. `Coach` 类
- **属性**:
- 继承自 `TeamMember`
- `personalPower`: 人格魅力
- `tacticsPower`: 战术指数
- **方法**:
- `__init__(self)`: 构造函数
- `GetRate(self)`: 计算教练综合评分
#### 6. `Match` 类
- **属性**:
- `homeTeam`: 主队
- `awayTeam`: 客队
- `homeTeamGoal`: 主队进球数
- `awayTeamGoal`: 客队进球数
- `details`: 比赛细节
- **方法**:
- `__init__(self, homeTeam, awayTeam)`: 构造函数
- `Print(self)`: 打印比赛详情
- `Run(self)`: 运行比赛
- `IsTrueByProb(self, prob)`: 根据概率判断事件是否发生
### 代码实现
```python
import random
import time
class League:
def __init__(self, name):
self.name = name
self.teams = []
def AddTeam(self, team):
if not any(t.name == team.name for t in self.teams):
self.teams.append(team)
return team
return None
def GetTeam(self, teamName):
for team in self.teams:
if team.name == teamName:
return team
return None
def Print(self):
print(f"{'球队名称':<10} {'球队攻击力':<10} {'球队防御力':<10} {'球队稳定性':<10} {'球队综合能力':<10}")
for team in self.teams:
print(f"{team.name:<10} {team.GetTeamAttackPower():<10.2f} {team.GetTeamDefendPower():<10.2f} {team.GetTeamStabilityPower():<10.2f} {team.GetRate():<10.2f}")
class Team:
def __init__(self, name):
self.name = name
self.players = []
self.coach = None
def AddPlayer(self, player):
self.players.append(player)
def AddCoach(self, coach):
self.coach = coach
def GetRate(self):
return (self.GetTeamAttackPower() + self.GetTeamDefendPower() + self.GetTeamStabilityPower()) / 3
def GetTeamAttackPower(self):
attack_players = [p for p in self.players if p.position in ["前锋", "中场"]]
return sum(p.attackPower for p in attack_players) / len(attack_players) if attack_players else 0
def GetTeamDefendPower(self):
defend_players = [p for p in self.players if p.position in ["后卫", "门将"]]
return sum(p.defendPower for p in defend_players) / len(defend_players) if defend_players else 0
def GetTeamStabilityPower(self):
stability = sum(p.stability for p in self.players) / len(self.players)
return stability * (self.coach.GetRate() / 100) if self.coach else stability
def Print(self):
print(f"{'姓名':<10} {'身份证号':<10} {'位置':<10} {'攻击指数':<10} {'防守指数':<10} {'稳定性':<10} {'综合评价':<10}")
for player in self.players:
print(f"{player.name:<10} {player.id:<10} {player.position:<10} {player.attackPower:<10.2f} {player.defendPower:<10.2f} {player.stability:<10.2f} {player.GetRate():<10.2f}")
class TeamMember:
def __init__(self, id, name, position):
self.id = id
self.name = name
self.position = position
def GetRate(self):
pass
class Player(TeamMember):
def __init__(self, id, name, position, attackPower, defendPower, stability):
super().__init__(id, name, position)
self.attackPower = attackPower
self.defendPower = defendPower
self.stability = stability
def GetRate(self):
if self.position == "前锋":
return self.attackPower * 0.7 + self.defendPower * 0.1 + self.stability * 0.2
elif self.position == "中场":
return self.attackPower * 0.4 + self.defendPower * 0.4 + self.stability * 0.2
elif self.position == "后卫":
return self.attackPower * 0.1 + self.defendPower * 0.5 + self.stability * 0.4
elif self.position == "门将":
return self.attackPower * 0.0 + self.defendPower * 0.6 + self.stability * 0.4
class Coach(TeamMember):
def __init__(self, id, name, personalPower, tacticsPower):
super().__init__(id, name, "教练")
self.personalPower = personalPower
self.tacticsPower = tacticsPower
def GetRate(self):
return self.personalPower * 0.3 + self.tacticsPower * 0.7
class Match:
Descriptions = [
"点球!点球!他竟然把球踢向了看台",
"比赛沉闷至极,球迷都睡着了",
"裁判出示了黄牌,这个犯规太恶劣了",
"好机会,球进了!裁判举旗了,越位在先",
"这么好的机会竟然没有打门,他在思考人生吗?",
"比赛你来我往,十分精彩",
"门将发挥太出色了,看来很难进球",
"天若有情天亦老,看到哈特来一脚",
"面对空门,竟然没有打进,不得不说,这个球打不进的难度更大",
"他鱼跃冲顶,可惜偏出球门",
"面对门将了,可惜单刀没有打进"
]
def __init__(self, homeTeam, awayTeam):
self.homeTeam = homeTeam
self.awayTeam = awayTeam
self.homeTeamGoal = 0
self.awayTeamGoal = 0
self.details = []
def Print(self):
for minute, detail in enumerate(self.details, start=1):
print(f"第{minute * 10}分钟: {detail}")
time.sleep(1)
print("裁判一声哨响,比赛结束")
print(f"{self.homeTeam.name} vs {self.awayTeam.name}, 比分 {self.homeTeamGoal}:{self.awayTeamGoal}")
def Run(self):
self.homeTeamGoal = 0
self.awayTeamGoal = 0
self.details.clear()
isHomeNotGood = self.IsTrueByProb(1 - (self.homeTeam.GetTeamStabilityPower() / 100))
isAwayNotGood = self.IsTrueByProb(1 - (self.awayTeam.GetTeamStabilityPower() / 100))
homeTeamRateAtGame = self.homeTeam.GetRate() * 0.8 if isHomeNotGood else self.homeTeam.GetRate()
awayTeamRateAtGame = self.awayTeam.GetRate() * 0.8 if isAwayNotGood else self.awayTeam.GetRate()
for _ in range(9):
n1 = abs(self.homeTeam.GetTeamAttackPower() - self.awayTeam.GetTeamDefendPower())
n2 = abs(self.awayTeam.GetTeamAttackPower() - self.homeTeam.GetTeamDefendPower())
prob = (n1 + n2 + random.uniform(5.0, 10.0)) / 100
isGoal = self.IsTrueByProb(prob)
if isGoal:
isHomeGoal = self.IsTrueByProb(homeTeamRateAtGame / (homeTeamRateAtGame + awayTeamRateAtGame))
if isHomeGoal:
self.homeTeamGoal += 1
self.details.append(f"Goal~{self.homeTeam.name}进球了,太精彩了,主场球迷欢欣鼓舞!")
else:
self.awayTeamGoal += 1
self.details.append(f"Goal~{self.awayTeam.name}在客场进球,难以置信!")
else:
self.details.append(random.choice(self.Descriptions))
return self.homeTeamGoal, self.awayTeamGoal
def IsTrueByProb(self, prob):
if prob > 1.0:
prob = 1.0
return random.random() < prob
# 主程序
def main():
league_name = input("请输入联赛名称:")
league = League(league_name)
while True:
print("-" * 80)
print(f"欢迎进入{league_name}联赛")
print("-" * 80)
for i, option in enumerate(["退出", "新建球队", "显示球队信息", "显示联赛信息", "开始比赛", "比赛多次"]):
print(f"{i} - {option}")
choice = input("请选择操作:")
if choice == '0':
break
elif choice == '1':
new_team = Team(input("请输入球队名称:"))
while True:
add_player = input("是否添加球员? Y or N:").upper()
if add_player == 'N':
break
player_id = input("请输入球员ID:")
player_name = input("请输入球员姓名:")
player_position = input("请输入球员位置(前锋, 中场, 后卫, 门将):")
player_attack_power = float(input("请输入球员攻击力(0-100):"))
player_defend_power = float(input("请输入球员防御力(0-100):"))
player_stability = float(input("请输入球员稳定性(0-100):"))
new_player = Player(player_id, player_name, player_position, player_attack_power, player_defend_power, player_stability)
new_team.AddPlayer(new_player)
print("请添加教练信息")
coach_id = input("请输入教练ID:")
coach_name = input("请输入教练姓名:")
coach_personal_power = float(input("请输入教练个人魅力(0-100):"))
coach_tactics_power = float(input("请输入教练战术指数(0-100):"))
new_coach = Coach(coach_id, coach_name, coach_personal_power, coach_tactics_power)
new_team.AddCoach(new_coach)
league.AddTeam(new_team)
elif choice == '2':
team_name = input("请输入显示的队伍名称:")
team = league.GetTeam(team_name)
if team:
team.Print()
else:
print("未找到该球队")
elif choice == '3':
league.Print()
elif choice == '4':
home_team_name = input("请输入主队队伍名称:")
away_team_name = input("请输入客队队伍名称:")
home_team = league.GetTeam(home_team_name)
away_team = league.GetTeam(away_team_name)
if home_team and away_team:
match = Match(home_team, away_team)
match.Run()
match.Print()
else:
print("未找到指定球队")
elif choice == '5':
num_matches = int(input("请输入比赛次数:"))
home_team_name = input("请输入主队队伍名称:")
away_team_name = input("请输入客队队伍名称:")
home_team = league.GetTeam(home_team_name)
away_team = league.GetTeam(away_team_name)
if home_team and away_team:
results = []
for _ in range(num_matches):
match = Match(home_team, away_team)
match.Run()
results.append(match)
for match in results:
match.Print()
else:
print("未找到指定球队")
if __name__ == "__main__":
main()
```
### 功能说明
1. **新建联赛**: 用户可以输入联赛名称,创建一个新的联赛。
2. **新建球队**: 在联赛中新建球队,输入球队名称、球员信息和教练信息。
3. **显示球队信息**: 输入球队名称,显示该球队的详细信息,包括球员和教练的信息。
4. **显示联赛信息**: 显示联赛中所有球队的能力指数信息。
5. **开始比赛**: 选择两个球队进行比赛,模拟比赛过程并显示结果。
6. **比赛多次**: 选择两个球队进行多次比赛,显示每次比赛的结果。
希望这段代码能满足您的需求!如果有任何问题或需要进一步的功能扩展,请随时告知。
阅读全文