本文目录导读:

我来为你创建一个有趣的Python案例,模拟地面对抗(王者荣耀》或《英雄联盟》中的对抗场景),统计谁胜出。
完整案例:英雄对战模拟器
import random
from collections import Counter
from dataclasses import dataclass
from typing import List, Dict
import time
@dataclass
class Hero:
"""英雄类"""
name: str
health: int # 生命值
attack: int # 攻击力
defense: int # 防御力
speed: int # 速度(决定先手)
skill_power: int # 技能威力
crit_chance: float # 暴击率 (0-1)
def is_alive(self) -> bool:
return self.health > 0
def take_damage(self, damage: int):
"""受到伤害"""
actual_damage = max(1, damage - self.defense // 2) # 防御减伤
self.health = max(0, self.health - actual_damage)
return actual_damage
def calculate_attack_damage(self, use_skill: bool = False) -> int:
"""计算攻击伤害"""
if use_skill:
base_damage = self.attack * 2 + self.skill_power
return int(base_damage)
else:
# 普通攻击,有暴击几率
if random.random() < self.crit_chance:
return int(self.attack * 2.5) # 暴击伤害
return self.attack
def create_heroes() -> List[Hero]:
"""创建对战英雄"""
return [
Hero("剑圣", 1000, 120, 30, 80, 150, 0.25),
Hero("法师", 800, 150, 20, 70, 200, 0.15),
Hero("战士", 1200, 110, 40, 60, 120, 0.20),
Hero("刺客", 700, 170, 15, 100, 180, 0.35),
Hero("坦克", 1500, 90, 50, 50, 100, 0.10)
]
def start_battle(hero1: Hero, hero2: Hero, rounds: int = 3) -> Dict:
"""模拟英雄对战"""
results = {
'battles': [],
'hero1_wins': 0,
'hero2_wins': 0,
'total_rounds': rounds
}
for battle_num in range(1, rounds + 1):
# 复制英雄以保持原始状态
h1 = Hero(hero1.name, hero1.health, hero1.attack, hero1.defense,
hero1.speed, hero1.skill_power, hero1.crit_chance)
h2 = Hero(hero2.name, hero2.health, hero2.attack, hero2.defense,
hero2.speed, hero2.skill_power, hero2.crit_chance)
# 判断先手(速度决定)
first, second = (h1, h2) if h1.speed >= h2.speed else (h2, h1)
battle_log = {
'battle_num': battle_num,
'rounds': 0,
'winner': None,
'total_damage': 0,
'actions': []
}
current_round = 0
max_rounds = 20 # 防止无限循环
print(f"\n🎮 第{battle_num}场对战:{hero1.name} VS {hero2.name}")
print("=" * 50)
while first.is_alive() and second.is_alive() and current_round < max_rounds:
current_round += 1
# 先手攻击
skill_used = random.random() < 0.3 # 30%概率使用技能
damage = first.calculate_attack_damage(skill_used)
actual_damage = second.take_damage(damage)
skill_text = "🔮技能" if skill_used else "⚔️普通攻击"
print(f"回合{current_round}: {first.name}使用{skill_text}对{second.name}造成{actual_damage}伤害")
battle_log['actions'].append({
'round': current_round,
'attacker': first.name,
'defender': second.name,
'damage': actual_damage,
'skill': skill_used
})
if not second.is_alive():
break
# 后手攻击
skill_used = random.random() < 0.3
damage = second.calculate_attack_damage(skill_used)
actual_damage = first.take_damage(damage)
skill_text = "🔮技能" if skill_used else "⚔️普通攻击"
print(f"回合{current_round}: {second.name}使用{skill_text}对{first.name}造成{actual_damage}伤害")
battle_log['actions'].append({
'round': current_round,
'attacker': second.name,
'defender': first.name,
'damage': actual_damage,
'skill': skill_used
})
# 判断胜负
battle_log['rounds'] = current_round
if first.is_alive() and not second.is_alive():
battle_log['winner'] = first.name
winner_name = first.name
elif second.is_alive() and not first.is_alive():
battle_log['winner'] = second.name
winner_name = second.name
else:
# 平局(都活着或都死了)
battle_log['winner'] = "平局"
winner_name = "平局"
if winner_name == hero1.name:
results['hero1_wins'] += 1
elif winner_name == hero2.name:
results['hero2_wins'] += 1
battle_log['total_damage'] = sum([a['damage'] for a in battle_log['actions']])
results['battles'].append(battle_log)
print(f"🏆 第{battle_num}场胜者:{battle_log['winner']}")
print(f" 共进行了{battle_log['rounds']}回合,总伤害{battle_log['total_damage']}")
time.sleep(0.5) # 稍作暂停,让观感更好
return results
def analyze_results(results: Dict) -> None:
"""分析对战结果"""
print("\n" + "=" * 60)
print("📊 对战统计结果")
print("=" * 60)
total_battles = results['total_rounds']
win_rate1 = (results['hero1_wins'] / total_battles) * 100
win_rate2 = (results['hero2_wins'] / total_battles) * 100
print(f"\n共进行 {total_battles} 场对战")
if 'hero1_wins' in results:
print(f"\n🏆 英雄1获胜次数: {results['hero1_wins']} ({win_rate1:.1f}%)")
print(f"🏆 英雄2获胜次数: {results['hero2_wins']} ({win_rate2:.1f}%)")
# 统计各英雄胜率
winner_counts = Counter()
for battle in results['battles']:
winner_counts[battle['winner']] += 1
print("\n📈 胜场分布:")
for hero_name, count in winner_counts.most_common():
print(f" {hero_name}: {count}场 ({count/total_battles*100:.1f}%)")
# 分析平均回合数和伤害
avg_rounds = sum(b['rounds'] for b in results['battles']) / total_battles
avg_damage = sum(b['total_damage'] for b in results['battles']) / total_battles
print(f"\n📊 平均回合数: {avg_rounds:.1f}")
print(f"💥 平均总伤害: {avg_damage:.1f}")
def tournament_mode(heroes: List[Hero], rounds_per_match: int = 5):
"""锦标赛模式:所有英雄两两对战"""
print("\n" + "🏆" * 20)
print("🏆 锦标赛模式开始!")
print("🏆" * 20)
tournament_results = {}
for i in range(len(heroes)):
for j in range(i + 1, len(heroes)):
hero1 = heroes[i]
hero2 = heroes[j]
print(f"\n🔴 {hero1.name} vs 🟦 {hero2.name}")
results = start_battle(hero1, hero2, rounds_per_match)
analyze_results(results)
# 记录对战结果
match_key = f"{hero1.name} vs {hero2.name}"
if results['hero1_wins'] > results['hero2_wins']:
winner = hero1.name
elif results['hero2_wins'] > results['hero1_wins']:
winner = hero2.name
else:
winner = "平局"
tournament_results[match_key] = {
'winner': winner,
'hero1_wins': results['hero1_wins'],
'hero2_wins': results['hero2_wins']
}
# 显示锦标赛总结
print("\n" + "=" * 60)
print("🏆 锦标赛结果总览")
print("=" * 60)
for match, result in tournament_results.items():
print(f"{match}: {result['winner']} 获胜")
print(f" ({result['hero1_wins']}胜 - {result['hero2_wins']}负)")
# 主程序
def main():
print("⚔️ 英雄对战模拟系统 ⚔️")
print("=" * 50)
heroes = create_heroes()
print("可选的英雄:")
for i, hero in enumerate(heroes, 1):
print(f" {i}. {hero.name} (生命:{hero.health}, 攻击:{hero.attack}, 防御:{hero.defense}, 速度:{hero.speed})")
while True:
print("\n请选择模式:")
print("1. 双人对战")
print("2. 锦标赛模式(全部对战)")
print("3. 退出")
choice = input("\n输入选择 (1-3): ").strip()
if choice == "1":
try:
print("\n选择英雄1:")
for i, hero in enumerate(heroes, 1):
print(f" {i}. {hero.name}")
hero1_idx = int(input("输入英雄编号: ")) - 1
print("\n选择英雄2:")
for i, hero in enumerate(heroes, 1):
print(f" {i}. {hero.name}")
hero2_idx = int(input("输入英雄编号: ")) - 1
if hero1_idx in range(len(heroes)) and hero2_idx in range(len(heroes)):
rounds = int(input("训练场数 (建议3-5场): "))
results = start_battle(heroes[hero1_idx], heroes[hero2_idx], rounds)
analyze_results(results)
else:
print("❌ 无效的英雄编号!")
except (ValueError, IndexError):
print("❌ 输入无效!请输入数字")
elif choice == "2":
tournament_mode(heroes)
elif choice == "3":
print("感谢使用,再见!")
break
else:
print("❌ 无效选择,请重试")
input("\n按回车继续...")
if __name__ == "__main__":
main()
运行示例
# 快速测试示例
if __name__ == "__main__":
# 创建英雄
hero1 = Hero("剑圣", 1000, 120, 30, 80, 150, 0.25)
hero2 = Hero("法师", 800, 150, 20, 70, 200, 0.15)
# 进行5场对战
results = start_battle(hero1, hero2, rounds=5)
# 分析结果
analyze_results(results)
功能特点
- 英雄系统:每个英雄有独立的属性(生命、攻击、防御、速度、暴击率、技能威力)
- 战斗系统:包含普通攻击、技能攻击、暴击等机制
- 统计功能:对战胜率、平均回合数、伤害统计等
- 多种模式:双人对战和锦标赛模式
- 详细日志:显示每回合的战斗详情
扩展建议
# 添加新英雄
def add_new_heroes():
return [
Hero("射手", 850, 160, 20, 90, 170, 0.30),
Hero("辅助", 950, 70, 35, 75, 200, 0.10),
Hero("打野", 1100, 130, 35, 85, 160, 0.22)
]
# 添加天气系统
weather_effects = {
'sunny': {'damage_bonus': 1.1, 'defense_penalty': 0.9},
'rainy': {'damage_penalty': 0.9, 'defense_bonus': 1.1},
'fog': {'crit_chance_bonus': 0.1, 'accuracy_penalty': 0.9}
}
这个系统非常灵活,可以根据需求扩展更多功能,比如装备系统、技能树、等级系统等。
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播