-
-
Save 1328/ec1a96c46c7b4a7e1b3d to your computer and use it in GitHub Desktop.
skills
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from collections import defaultdict | |
| from pprint import pprint | |
| class Effect(object): | |
| def __init__(self, what, how): | |
| self.what = what | |
| self.how = how | |
| def apply(self, base): | |
| return self.how(base) | |
| class Item(object): | |
| def __init__(self, name, effects = None): | |
| self.name = name | |
| if effects is None: | |
| self.effects = [] | |
| else: | |
| self.effects = effects | |
| class Skill(object): | |
| def __init__(self, name, base, affected_by = None): | |
| self.name = name | |
| self.base = base | |
| if affected_by is None: | |
| self.affected_by = {} | |
| else: | |
| self.affected_by = affected_by | |
| def calculate(self, attributes): | |
| result = self.base | |
| for attribute, effect in self.affected_by.items(): | |
| result = effect(result, attributes[attribute]) | |
| return result | |
| class Character(object): | |
| def __init__(self, name, **kwargs): | |
| self.name = name | |
| self.attributes = {k:v for k,v in kwargs.items()} | |
| self.items = [] | |
| self.skills = {} | |
| self.effectors = defaultdict(list) | |
| def get_attribute(self, attribute): | |
| result = self.attributes[attribute] | |
| for effect in self.effectors[attribute]: | |
| result = effect.apply(result) | |
| return result | |
| def add_item(self, item): | |
| self.items.append(item) | |
| for effect in item.effects: | |
| self.effectors[effect.what].append(effect) | |
| def get_skill(self, skill_name): | |
| skill = self.skills[skill_name] | |
| # lock current attributes in skill | |
| attributes = {a:self.get_attribute(a) for a in skill.affected_by.keys()} | |
| pprint(attributes) | |
| # get the base skill | |
| result = skill.calculate(attributes) | |
| # level up by other effectors | |
| for effect in self.effectors[skill_name]: | |
| result = effect.apply(result) | |
| return result | |
| pc = Character('smith', agility = 10, strength = 20) | |
| glove = Item('glove of agility and strength', [ | |
| Effect('strength', lambda x:x+2), | |
| Effect('agility', lambda x:x+1), | |
| Effect('smithy', lambda x:x+5), | |
| ]) | |
| pc.add_item(glove) | |
| pprint(pc.effectors) | |
| print(pc.get_attribute('strength')) | |
| print(pc.get_attribute('agility')) | |
| smithy = Skill('smithy',30,{ | |
| 'strength':lambda b,a:b + a*1.25, | |
| 'agility':lambda b,a:b+a*1 | |
| } | |
| ) | |
| pc.skills = {'smithy':smithy} | |
| print(pc.get_skill('smithy')) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment