英雄大乱斗
今日作业
1.什么是对象?什么是类?
对象是特征与技能的结合体;
类是一系列对象相同特征和技能的结合体。
2.绑定方法的有什么特点
绑定给谁就由谁来调用,绑定给类,就是一个普通的函数,该传几个参数就传几个参数;
绑定给对象,会把对象本身当做第一个参数,自动传入。
3.基于面向对象设计一个对战游戏
# 仿制英雄联盟英雄角色
import random
class Hero:
def __init__(self, name, attack, life_value, defend):
self.name = name
self.attack = attack
self.life_value = life_value
self.defend = defend
# print(self.__dict__)
def fight(self, enemy):
# print(enemy.name)
# print(enemy.life_value)
if enemy.life_value <= 0:
return True
effect_hurt = random.choice( self.attack) - enemy.defend
enemy.life_value -= effect_hurt
print(f'''
{self.name}攻击了{enemy.name}:
有效伤害为:{effect_hurt},
{enemy.name}还剩血量为:{ enemy.life_value}
''')
h1 = Hero('盖伦', [120,50,300], 1000, 10)
h2 = Hero('瑞文', [100,280,40], 1000, 30)
count=0
while True:
count+=1
print(f'第{count}回合:\n')
flag1 = h1.fight(h2)
if flag1:
print(f'第{count}回合 {h2.name}已经挂掉了!')
break
flag2 = h2.fight(h1)
if flag2:
print(f'第{count}回合{h1.name}已经挂掉了!')
break
# 升级版
import random
import time
class Hero:
def __init__(self,name,level,blood,att,q_hurt,w_hurt,e_hurt):
# 简便写法
lcs = locals()
lcs.pop("self")
self.__dict__.update(lcs)
def attack(self,enemy):
enemy.blood -= self.att
print("%s对%s释放了普通攻击 造成了%s的伤害 敌人剩余血量%s" % (self.name, enemy.name, self.att, enemy.blood))
if enemy.blood <= 0:
print("%s被%s使用普通攻击击杀了" % (enemy.name,self.name))
def Q(self,enemy):
enemy.blood -= self.q_hurt
print("%s对%s释放了Q 造成了%s的伤害 敌人剩余血量%s" % (self.name, enemy.name, self.q_hurt, enemy.blood))
if enemy.blood <= 0:
print("%s被%s使用Q技能击杀了" % (enemy.name, self.name))
def W(self,enemy):
enemy.blood -= self.w_hurt
print("%s对%s释放了W 造成了%s的伤害 敌人剩余血量%s" % (self.name, enemy.name, self.w_hurt, enemy.blood))
if enemy.blood <= 0:
print("%s被%s使用W技能击杀了" % (enemy.name, self.name))
def E(self,enemy):
enemy.blood -= self.e_hurt
print("%s对%s释放了E 造成了%s的伤害 敌人剩余血量%s" % (self.name,enemy.name,self.e_hurt,enemy.blood))
if enemy.blood <= 0:
print("%s被%s使用E技能击杀了" % (enemy.name, self.name))
h1 = Hero("亚索",20,2000,100,600,0,1000)
h2 = Hero("妲己",20,2000,100,600,500,1000)
h3 = Hero("鲁班",20,1500,700,100,200,300)
h4 = Hero("蔡文姬",20,2000,10,0,0,10)
#
# h1.attack(h2)
# h2.Q(h1)
# h2.E(h1)
# h2.W(h1)
#从字典中随机拿出一个值
def random_hero(heros):
hero_index = random.randint(1, len(heros))
return heros[hero_index]
while True:
# # 把所有的攻击方法装到字典里 为了随机取出一个
funcs = {1: Hero.Q, 2: Hero.W, 3: Hero.E, 4: Hero.attack}
func_index = random.randint(1, 4)
func = funcs[func_index]
# 把所有的英雄方法装到字典里 为了随机取出一个
heros = {1: h1, 2: h2, 3: h3, 4: h4}
hero = random_hero(heros)
# 剩余的英雄们
other_heros = {}
new_index = 1
for k, v in heros.items():
if v != hero:
other_heros[new_index] = v
new_index += 1
# 从剩余的英雄中随机挑出一个英雄来挨打
enemy = random_hero(other_heros)
# 打他
func(hero, enemy)
if enemy.blood <= 0:
break
time.sleep(0.5)