欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 艺术 > python实现回合制的战斗模拟游戏

python实现回合制的战斗模拟游戏

2025/3/11 9:26:26 来源:https://blog.csdn.net/2301_76444133/article/details/146164095  浏览:    关键词:python实现回合制的战斗模拟游戏

一个简单的基于回合制的战斗模拟游戏。其中包含了英雄角色的创建、攻击、治疗以及胜负判断等逻辑。

import random
import time
from enum import Enum# 枚举类型定义装备品质
class Rarity(Enum):COMMON = 1RARE = 2EPIC = 3LEGENDARY = 4# 装备类
class Equipment:def __init__(self, name, eq_type, attack=0, defense=0, hp=0, effect=None):self.name = nameself.eq_type = eq_type  # weapon/armor/accessoryself.attack = attackself.defense = defenseself.hp = hpself.rarity = random.choice(list(Rarity))self.effect = effect  # 特殊效果函数# 装备品质颜色显示@propertydef colored_name(self):colors = {Rarity.COMMON: '\033[37m',  # 白色Rarity.RARE: '\033[94m',  # 蓝色Rarity.EPIC: '\033[95m',  # 紫色Rarity.LEGENDARY: '\033[93m'  # 金色}return f"{colors[self.rarity]}{self.name}\033[0m"# 角色类
class Hero:def __init__(self, name):# 基础属性self.name = nameself.max_hp = 100self.hp = 100self.base_attack = random.randint(15, 25)self.base_defense = random.randint(5, 15)# 装备系统self.weapon = Noneself.armor = Noneself.accessory = None# 技能系统self.skills = []self.cooldowns = {}# 初始化角色专属技能self._init_skills()# 动态属性计算(考虑装备加成)@propertydef attack(self):weapon_bonus = self.weapon.attack if self.weapon else 0return self.base_attack + weapon_bonus@propertydef defense(self):armor_bonus = self.armor.defense if self.armor else 0return self.base_defense + armor_bonus# 角色专属技能初始化def _init_skills(self):skill_db = {'剑影': [('幻影连斩', self._sword_dance, 3)],'霜月': [('寒冰护盾', self._ice_shield, 4)],'炎魂': [('烈焰爆发', self._flame_burst, 5)],'星尘': [('星辰治愈', self._stellar_heal, 3)],'风行者': [('疾风连射', self._wind_shot, 4)],'幽澜': [('深渊召唤', self._abyss_summon, 6)]}self.skills = skill_db.get(self.name, [])# 以下为各角色专属技能实现-----------------------------------------# 剑影技能:三连击def _sword_dance(self, target):dmg = sum([max(self.attack + random.randint(-3, 5) - target.defense, 1)for _ in range(3)])target.hp -= dmgprint(f"🌀 \033[93m{self.name}发动幻影连斩!造成三次攻击,总计{dmg}点伤害!\033[0m")# 霜月技能:冰盾def _ice_shield(self, _):self.max_hp += 20self.hp = min(self.hp + 20, self.max_hp)self.base_defense += 5print(f"❄️ \033[94m{self.name}召唤寒冰护盾!防御提升,恢复20HP!\033[0m")# 炎魂技能:范围伤害def _flame_burst(self, targets):dmg = self.attack * 2for t in targets:t.hp -= max(dmg - t.defense, 1)print(f"🔥 \033[91m{self.name}释放烈焰爆发!全体受到{dmg}点灼烧伤害!\033[0m")# 星尘技能:群体治疗def _stellar_heal(self, allies):heal = 30 + random.randint(-5, 10)for a in allies:a.hp = min(a.hp + heal, a.max_hp)print(f"🌌 \033[96m{self.name}引导星辰之力!全体恢复{heal}点生命!\033[0m")# 风行者技能:远程连击def _wind_shot(self, target):hits = random.randint(2, 5)dmg = sum([self.attack + random.randint(-2, 3) - target.defense // 2for _ in range(hits)])target.hp -= dmgprint(f"🎯 {self.name}发动疾风连射!{hits}连击造成{dmg}点伤害!")# 幽澜技能:召唤分身def _abyss_summon(self, _):self.max_hp += 50self.hp = min(self.hp + 50, self.max_hp)print(f"🌑 \033[35m{self.name}召唤深渊分身!最大HP增加50!\033[0m")# 通用方法-----------------------------------------------------def equip(self, equipment):if equipment.eq_type == 'weapon':self.weapon = equipmentelif equipment.eq_type == 'armor':self.armor = equipmentelse:self.accessory = equipmentdef show_status(self):eq_info = []if self.weapon: eq_info.append(f"武:{self.weapon.colored_name}")if self.armor: eq_info.append(f"防:{self.armor.colored_name}")if self.accessory: eq_info.append(f"饰:{self.accessory.colored_name}")print(f"{self.name.ljust(6)} [\033[92m{self.hp}\033[0m/{self.max_hp}] "f"攻:{self.attack} 防:{self.defense} | {' '.join(eq_info)}")def is_alive(self):return self.hp > 0# 装备生成器
def generate_equipment():weapons = [Equipment("铁剑", "weapon", attack=8),Equipment("秘银长刀", "weapon", attack=12),Equipment("龙牙匕首", "weapon", attack=15, defense=-3)]armors = [Equipment("皮甲", "armor", defense=5),Equipment("链甲", "armor", defense=10, hp=20),Equipment("龙鳞铠", "armor", defense=15)]accessories = [Equipment("治疗戒指", "accessory", hp=30),Equipment("狂暴项链", "accessory", attack=10, defense=-5),Equipment("幸运护符", "accessory")]return random.choice(random.choice([weapons, armors, accessories]))# 战斗系统核心
class BattleSystem:def __init__(self, heroes):self.heroes = heroesself.round = 1# 初始化装备for hero in self.heroes:for _ in range(3):hero.equip(generate_equipment())def start_battle(self):while len([h for h in self.heroes if h.is_alive()]) > 1:print(f"\n\033[1m=== 第 {self.round} 回合 ===\033[0m")self._process_round()self.round += 1time.sleep(1)survivors = [h.name for h in self.heroes if h.is_alive()]print(f"\n\033[1m战斗结束!幸存者:{', '.join(survivors) if survivors else '无'}\033[0m")def _process_round(self):# 随机行动顺序random.shuffle(self.heroes)for attacker in self.heroes.copy():if not attacker.is_alive():continue# 血量检测if attacker.hp < attacker.max_hp * 0.3 and random.random() < 0.5:if self._use_heal_skill(attacker):continue# 技能释放判断if self._use_attack_skill(attacker):continue# 普通攻击targets = [h for h in self.heroes if h.is_alive() and h != attacker]if targets:target = random.choice(targets)self._normal_attack(attacker, target)# 状态更新self._update_status()def _use_heal_skill(self, attacker):for skill_name, skill_func, cd in attacker.skills:if '治愈' in skill_name and attacker.cooldowns.get(skill_name, 0) == 0:allies = [h for h in self.heroes if h.is_alive()]skill_func(allies)attacker.cooldowns[skill_name] = cdreturn Truereturn Falsedef _use_attack_skill(self, attacker):for skill_name, skill_func, cd in attacker.skills:if attacker.cooldowns.get(skill_name, 0) == 0 and random.random() < 0.4:targets = self._select_targets(attacker, skill_name)if targets:skill_func(targets)attacker.cooldowns[skill_name] = cdreturn Truereturn Falsedef _select_targets(self, attacker, skill_name):alive_heroes = [h for h in self.heroes if h.is_alive()]if skill_name == '星辰治愈':return alive_heroeselif skill_name == '烈焰爆发':return [h for h in alive_heroes if h != attacker]elif skill_name in ['幻影连斩', '疾风连射']:return random.choice([h for h in alive_heroes if h != attacker])return Nonedef _normal_attack(self, attacker, target):dmg = max(attacker.attack + random.randint(-3, 5) - target.defense, 1)target.hp -= dmgprint(f"{attacker.name} 对 {target.name} 造成 {dmg} 点伤害!")def _update_status(self):print("\n\033[90m当前状态:\033[0m")for h in self.heroes:if h.is_alive():h.show_status()else:print(f"{h.name.ljust(6)} [已阵亡]")# 初始化战斗
if __name__ == "__main__":heroes = [Hero(name) for name in ['剑影', '霜月', '炎魂', '星尘', '风行者', '幽澜']]battle = BattleSystem(heroes)battle.start_battle()

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词