Loading... # 函数与类 ## 小玩意 ![就喜欢帅气的魔女](https://lolisis.com/usr/uploads/2023/01/3577474537.webp) 承接上一节做的那个小玩意,学了函数与类之后又加了一点功能,变成了小垃圾。主要是:可以普攻,技能攻击,前后排换人。 其中:技能攻击如果是负数则是全屏奶,可以攒能量进入变身状态,所有攻击翻倍,一段行动次数后退出。前排死人后排顶上,前后排都死了就挂了,全挂了游戏结束 ### 代码 dragon.py ```python HDD_CRITICAL = 100 class Dragon: def __init__(self, name, health, damage, skill_damage, speed, skill_active_punish): self.name = name self.health = health self.damage = damage self.skill_damage = skill_damage self.speed = speed self.skill_active_punish = skill_active_punish class BattleDragon: def __init__(self, dragon): self.action_point = 0 self.hdd_point = 0 self.dragon = dragon self.health_point = dragon.health self.hdd_form = False self.alive = True def attack(self): if self.hdd_form: return self.dragon.damage * 2 else: self.hdd_point += 10 return self.dragon.damage def get_hurt(self, enemy_damage): self.health_point -= enemy_damage print(f"{self.dragon.name.title()} get {enemy_damage} damage.") if self.health_point <= 0: self.alive = False self.health_point = 0 print(f"{self.dragon.name.title()} is dead.") return 0 self.hdd_point += 20 return self.health_point def skill(self): if self.hdd_form: return self.dragon.skill_damage * 2 self.action_point -= self.dragon.skill_active_punish else: self.hdd_point += 10 return self.dragon.skill_damage def alive_status(self): return self.alive def turn_start(self): if self.hdd_point >= 100: self.hdd_form = True self.hdd_point = 100 print(f"{self.dragon.name} has changed to HDD form.") def turn_over(self): if self.hdd_form: self.hdd_point -= 30 if self.hdd_point <= 0: self.hdd_form = False print(f"{self.dragon.name} has changed to normal form") def active(self): # if self.action_point % self.dragon.speed == 0: if self.action_point == self.dragon.speed: self.action_point = 0 return True else: return False def ap(self): self.action_point += 1 def info(self): if self.alive: message = f"{self.dragon.name.title()}: HP\t {self.health_point} STR\t {self.dragon.damage}\t" if self.hdd_form: message += "DRAGON FORM!!!" else: message = f"{self.dragon.name.title()}: DEAD" # message += f"HDD\t{self.hdd_point}" return message def name(self): return self.dragon.name.title() def get_heal(self, value): self.health_point += value if self.health_point >= self.dragon.health: self.health_point = self.dragon.health ``` boss.py ```python class Boss: def __init__(self, health, damage, speed): self.health = health self.damage = damage self.dead = False self.active_point = 0 self.speed = speed def attack(self): return self.damage def get_hurt(self, player_damage): self.health -= player_damage if self.health <= 0: self.dead = True return 0 else: return self.health def active(self): if self.active_point % self.speed == 0: return True else: return False def ap(self): self.active_point += 1 ``` battle.py ```python from random import randint import boss import dragon class BattleField: def __init__(self, field_boss, front_dragons, back_dragons): self.field_boss = field_boss self.front_dragons = [] self.back_dragons = []## 列表要先定义 for key in front_dragons: self.front_dragons.append(dragon.BattleDragon(key)) for key in back_dragons: self.back_dragons.append(dragon.BattleDragon(key)) self.dead_dragons = [] self.win = False self.over = False def ap(self): self.field_boss.ap() for key in self.front_dragons: key.ap() def change_position(self, position): temp = self.front_dragons[position] self.front_dragons[position] = self.back_dragons[position] self.back_dragons[position] = temp def battle_filed_info(self): message = f"\nBOSS: \t{self.field_boss.health}" print(message) print(f"Front Line:") for key in self.front_dragons: print(f"\t{key.info()}") print(f"Back Line:") for key in self.back_dragons: print(f"\t{key.info()}") def boss_turn(self): if self.field_boss.active(): print(f"\nBOSS TURN:") key = randint(0, len(self.front_dragons) - 1) self.front_dragons[key].get_hurt(self.field_boss.attack()) if not self.front_dragons[key].alive_status():## 前排死了吗? if self.back_dragons[key].alive_status(): self.change_position(key) else:##前后都挂了就没戏了 del self.front_dragons[key] del self.back_dragons[key] self.battle_filed_info() if not self.front_dragons: self.over = True return self.over def player_turn(self): for key in range(0, len(self.front_dragons) - 1): if self.front_dragons[key].active(): self.front_dragons[key].turn_start()#写了忘记加,感觉这么写不好 print(f"\n{self.front_dragons[key].name()}'s turn. ") self.battle_filed_info() message = f"\nPress 1 or ENTER for attack, 2 skill" if self.back_dragons[key].alive_status(): message +=(", 3 change dragon") print(message) i = input() if i == "": value = 1 else: value = int(i) if value == 2: if self.front_dragons[key].skill() < 0: for friend_dragon in self.front_dragons: friend_dragon.get_heal(0 - self.front_dragons[key].skill()) else: self.field_boss.get_hurt(self.front_dragons[key].skill()) elif value == 3 and self.back_dragons[key].alive_status(): self.change_position(key)#不满足要求就执行1 else: # value == 1 self.field_boss.get_hurt(self.front_dragons[key].attack()) self.front_dragons[key].turn_over() if self.field_boss.dead: self.win = True self.over = True break return self.over ``` main.py ```python import boss import dragon import battle # info enemy = boss.Boss(1000, 1000, 3)##调高了伤害,使角色容易死试出了角色死亡了依然能替换上场的BUG zehpy = dragon.Dragon("Zephy", 200, 50, 70, 4, 1) charlotta = dragon.Dragon("Charlotta", 100, 100, 200, 6, 2) minessa = dragon.Dragon("Minessa", 150, 40, -60, 3, 0) karikaro = dragon.Dragon("Karikaro", 130, 50, 70, 4, 1) laponette = dragon.Dragon("Laponette", 80, 30, -30, 1, 0) faria = dragon.Dragon("Faria", 150, 40, 100, 4, 2) dragons = [zehpy, charlotta, minessa, karikaro, laponette, faria] front_dragons = [] back_dragons = dragons[:] message = "There are:\n" value = 0 for key in dragons: value += 1 message += f"{value}: {key.name}\t" message += "\navailable. Input 1 - 6 to choose 3 of them." print(message) ###其实可以选同样的人上场,这个bug不想修了…… while len(front_dragons) < 3: key = int(input()) if 1 <= key <= 6: front_dragons.append(dragons[key -1]) print(f"{dragons[key - 1].name} added.") else: print(f"Invalid input.") for key in front_dragons: back_dragons.remove(key) game = battle.BattleField(enemy, front_dragons, back_dragons) def game_over(): if game.win: print(f"Congratulations, you win!!") else: print(f"Oh no, you loose") while not game.over: game.ap() if game.boss_turn(): break if game.player_turn(): break game_over() ``` 结果 ### 输了的 ``` There are: 1: Zephy 2: Charlotta 3: Minessa 4: Karikaro 5: Laponette 6: Faria available. Input 1 - 6 to choose 3 of them. 1 Zephy added. 2 Charlotta added. 3 Minessa added. BOSS TURN: Charlotta get 1000 damage. Charlotta is dead. BOSS: 1000 Front Line: Zephy: HP 200 STR 50 Laponette: HP 80 STR 30 Minessa: HP 150 STR 40 Back Line: Karikaro: HP 130 STR 50 Charlotta: DEAD Faria: HP 150 STR 40 Zephy's turn. BOSS: 1000 Front Line: Zephy: HP 200 STR 50 Laponette: HP 80 STR 30 Minessa: HP 150 STR 40 Back Line: Karikaro: HP 130 STR 50 Charlotta: DEAD Faria: HP 150 STR 40 Press 1 or ENTER for attack, 2 skill, 3 change dragon 3 Laponette's turn. BOSS: 1000 Front Line: Karikaro: HP 130 STR 50 Laponette: HP 80 STR 30 Minessa: HP 150 STR 40 Back Line: Zephy: HP 200 STR 50 Charlotta: DEAD Faria: HP 150 STR 40 Press 1 or ENTER for attack, 2 skill 3 Laponette's turn. BOSS: 970 Front Line: Karikaro: HP 130 STR 50 Laponette: HP 80 STR 30 Minessa: HP 150 STR 40 Back Line: Zephy: HP 200 STR 50 Charlotta: DEAD Faria: HP 150 STR 40 Press 1 or ENTER for attack, 2 skill 2 BOSS TURN: Laponette get 1000 damage. Laponette is dead. BOSS: 970 Front Line: Karikaro: HP 130 STR 50 Minessa: HP 150 STR 40 Back Line: Zephy: HP 200 STR 50 Faria: HP 150 STR 40 Karikaro's turn. BOSS: 970 Front Line: Karikaro: HP 130 STR 50 Minessa: HP 150 STR 40 Back Line: Zephy: HP 200 STR 50 Faria: HP 150 STR 40 Press 1 or ENTER for attack, 2 skill, 3 change dragon 3 BOSS TURN: Zephy get 1000 damage. Zephy is dead. BOSS: 970 Front Line: Karikaro: HP 130 STR 50 Minessa: HP 150 STR 40 Back Line: Zephy: DEAD Faria: HP 150 STR 40 BOSS TURN: Minessa get 1000 damage. Minessa is dead. BOSS: 970 Front Line: Karikaro: HP 130 STR 50 Faria: HP 150 STR 40 Back Line: Zephy: DEAD Minessa: DEAD Karikaro's turn. BOSS: 970 Front Line: Karikaro: HP 130 STR 50 Faria: HP 150 STR 40 Back Line: Zephy: DEAD Minessa: DEAD Press 1 or ENTER for attack, 2 skill 1 BOSS TURN: Faria get 1000 damage. Faria is dead. BOSS: 920 Front Line: Karikaro: HP 130 STR 50 Back Line: Zephy: DEAD BOSS TURN: Karikaro get 1000 damage. Karikaro is dead. BOSS: 920 Front Line: Back Line: Oh no, you loose ``` ## 没有用到的内容 ### 参数与调用 ``` def describe_pet (pet_name, animal_type = "dog"): """显示宠物的信息""" print(f"\nI have a {animal_type}") print(f"My {animal_type}'s name is {pet_name.title()}") describe_pet("whillie") describe_pet(pet_name="whillie") ##以上调用等效 describe_pet("harry", "hamster") describe_pet(pet_name="harry", animal_type="hamster") describe_pet(animal_type="hamster", pet_name="harry") ##以上调用等效 ``` ### 返回字典 ``` def build_person(first_name, last_name, age=None): """返回一个字典,其中包含有关一个人的信息""" person = {"first": first_name, "last_name": last_name} if age: person["age"] = age return person print(build_person("jimi", "hendrix")) print(build_person("David", "wood", 17)) ``` 结果 ``` {'first': 'jimi', 'last_name': 'hendrix'} {'first': 'David', 'last_name': 'wood', 'age': 17} ``` ### 任意数量实参 ``` def make_pizza(size, *toppings): """概述要做的pizza""" print(f"\nMaking a {size}-inch pizza with the following toppings") for topping in toppings: print(f"- {topping}") make_pizza(16, "pepperoni") make_pizza(12, "mushrooms", "green peppers", "extra cheese") ``` 注*args也收集任意数量的位置实参 ### 任意数量关键字实参 有时需要接受任意数量的实参,但预先不知道传递给函数的会是什么样的信息 ``` def build_profile(first, last, **user_info): """创建一个字典,其中包含我们知道的有关用户的一切""" user_info["first_name"] = first user_info["last_name"] = last return user_info user_profile = build_profile("albert", "einstein", location="princeton", filed="phycis") print(user_profile) ``` ``` {'location': 'princeton', 'filed': 'phycis', 'first_name': 'albert', 'last_name': 'einstein'} ``` 注**kwargs 用于收集任意数量的关键字实参。 ### 导入函数与类 ``` import pizza#要用pizza.make_pizza调用 import pizza as p from pizza import make_pizza## 可能与本地重复 from pizza import make_pizza as mp ##解决重复或太长的办法 from pizza import *# 调用所有,不推荐 ``` 导入类是一样的 ### 继承 ``` import self as self class Car: """一次模拟汽车的尝试""" def __init__(self, make, model, year): self.make = make self.model = model self.year = year self.odometer_reading = 0 def get_descriptive_name(self): long_name = f"{self.year} {self.make} {self.model}" return long_name.title() def read_odometer(self): print(f"This Car has {self.odometer_reading} miles on it") def update_odometer(self, mileage): if mileage >= self.odometer_reading: self.odometer_reading = mileage else: print(f"You can't roll back an odometer") def increment_odometer(self, miles): self.odometer_reading +=miles def fill_gas_tank(self): print(f"Filling gas tank") class ElectricCar(Car): """电动车的独到之处""" def __init__(self, make, model, year): super().__init__(make, model, year) self.battery_size = 75 def describe_battery(self): print(f"This car has a {self.battery_size}-KWh battery") def fill_gas_tank(self):##重写父类的方法 print(f"There is no tank.") print(f"Charging") my_tesla = ElectricCar("tesla", "model s", 2019) print(my_tesla.get_descriptive_name()) my_tesla.describe_battery() my_tesla.fill_gas_tank() ``` ``` 2019 Tesla Model S This car has a 75-KWh battery There is no tank. Charging ``` Last modification:January 20, 2023 © Allow specification reprint Like 如果觉得我的文章对你有用,请留下评论。