From: Ben Doumenc Date: Sat, 31 May 2014 13:44:00 +0000 (+0200) Subject: refactoring genes X-Git-Url: http://gitweb.doumenc.org/?p=experiments.git;a=commitdiff_plain;h=5c9f1c64f3492c17d9272f9a7b5881511235b75a refactoring genes --- diff --git a/evolution/entities.py b/evolution/entities.py index 239ad9c..ece0308 100644 --- a/evolution/entities.py +++ b/evolution/entities.py @@ -113,9 +113,15 @@ class Bot(Physical): self.behavior = None self.behaviorData = {} + def check(self): + badValues = [k for k, v in self.stats.iteritems() if v < 0] + if badValues: + logging.debug("%s died by bad genes: %s", self, badValues) + def addGene(self, gene): self.genes.append(gene) gene.apply(self) + self.check() return self def getGenes(self): @@ -128,13 +134,12 @@ class Bot(Physical): class Gene(object): def __init__(self): self.name = self.__class__.__name__ - self.attribute = "" - self.modifier = 0 + + def modifyStat(self, entity, attribute, value): + stat = entity.stats.setdefault(attribute, 0) + entity.stats["stat"] = stat + value def apply(self, entity): - stat = entity.stats.setdefault(self.attribute, 0) - if stat + self.modifier >= 0: - entity.stats[self.attribute] = stat + self.modifier return self def __repr__(self): @@ -142,34 +147,24 @@ class Gene(object): class LongLegs(Gene): - def __init__(self): - super(LongLegs, self).__init__() - self.attribute = "speed" - self.modifier = 1 + def apply(self, entity): + self.modifyStat(entity, "speed", 0.5) class ShortLegs(Gene): - def __init__(self): - super(ShortLegs, self).__init__() - self.attribute = "speed" - self.modifier = -1 + def apply(self, entity): + self.modifyStat(entity, "speed", 0.5) class ClassicBeauty(Gene): - def __init__(self): - super(ClassicBeauty, self).__init__() - self.attribute = "charisma" - self.modifier = 1 + def apply(self, entity): + self.modifyStat(entity, "charisma", 0.5) class ExoticBeauty(Gene): - def __init__(self): - super(ExoticBeauty, self).__init__() - self.attribute = "charisma" - self.modifier = 2 + def apply(self, entity): + self.modifyStat(entity, "charisma", 1) class Eyes(Gene): - def __init__(self): - super(Eyes, self).__init__() - self.attribute = "perception" - self.modifier = 2 + def apply(self, entity): + self.modifyStat(entity, "perception", 2) import inspect, sys diff --git a/evolution/main.py b/evolution/main.py index 9fa2c29..a9fd548 100644 --- a/evolution/main.py +++ b/evolution/main.py @@ -25,7 +25,7 @@ if __name__ == "__main__": movement = Movement(size[0], size[1]) behavior = Behavior() population = 4 - food = 15 + food = 30 for _ in xrange(0, population): b = Bot(Vector(random.randint(0, size[0] - 1), random.randint(0, size[1] - 1))).addToScene(scene) generateRandomGenes(b)