def reset(self): self.runs += 1 self.runhistory.append([self.creature, self.map]) if self.runs > 4: self.runhistory.sort(key=lambda x: x[0].ticks, reverse=True) print "-----------------------------" #for run in self.runhistory: print "ticks:", self.creature.ticks for neuronRow in self.creature.network.network: for neuron in neuronRow: print neuron.weights print "-----------------------------" self.map.generate() self.creature = Creature() for layerNum in range(len(self.creature.network.network)): for neuronNum in range(len(self.creature.network.network[layerNum])): randomNum = random.randint(-4,min(32,len(self.runhistory)/2)) if randomNum < 0: self.creature.network.network[layerNum][neuronNum].weights = [random.random(), random.random(), random.random()] else: self.creature.network.network[layerNum][neuronNum] = self.runhistory[randomNum][0].network.network[layerNum][neuronNum] self.creature.place(self.map) else: self.map.generate() self.creature = Creature() self.creature.place(self.map)
def __init__(self, x, y): Creature.__init__(self, x, y, KRAKEN_SPEED, KRAKEN_LIFE, KRAKEN_REGENERATION, 2) self.attack = KRAKEN_ATTACK self.attackSpeed = KRAKEN_ATTACK_SPEED self.lastAttack = 0 self.image = loadImage("art/kraken.png", (255,255,255))
def __init__(self, x, y, team): Creature.__init__(self, x, y, ARCHER_SPEED, ARCHER_LIFE, ARCHER_REGENERATION, team) self.attack = ARCHER_ATTACK self.attackSpeed = ARCHER_ATTACK_SPEED self.lastAttack = 0 if self.team == 0: self.image = loadImage("art/greek_archer.png", (255,255,255)) else: self.image = loadImage("art/egytian_archer.png", (255,255,255))
def __init__(self, x, y, team): Creature.__init__(self, x, y, SWORDSMAN_SPEED, SWORDSMAN_LIFE, SWORDSMAN_REGENERATION, team) self.attack = SWORDSMAN_ATTACK self.attackSpeed = SWORDSMAN_ATTACK_SPEED self.lastAttack = 0 if self.team == 0: self.image = loadImage("art/greek_swordsman.png", (255,255,255)) else: self.image = loadImage("art/egyptian_swordsman.png", (255,255,255))
def __init__(self, x, y, team): Creature.__init__(self, x, y, WIZARD_SPEED, WIZARD_LIFE, WIZARD_REGENERATION, team) self.attack = WIZARD_ATTACK self.attackSpeed = WIZARD_ATTACK_SPEED self.lastAttack = 0 self.movement = 0 if self.team == 0: self.image = loadImage("art/wizard.png", (255,255,255)) else: self.image = loadImage("art/egyptian_magician.png", (255,255,255))
def create_ideal(self, idealImagePath=None): """Create a creature of a single ideal color.""" self.idealCreature = Creature(self, self.cycle, name='ideal') if idealImagePath is None: self.idealCreature.set_to_color(self.idealColor) else: self.idealCreature.set_colors_from_image(idealImagePath)
def __init__(self, x=0, y=0, theta=0): """ Constructor """ Creature.__init__(self, x, y, theta) self.gradL = GradientSniffer(self, self.world, -10) self.senses.append((self.gradL)) self.gradC = GradientSniffer(self, self.world, 0) self.senses = self.senses.append(self.gradC) self.gradR = GradientSniffer(self, self.world, 10) self.senses.append(self.gradR) self.brain_data = ArrayInterface([("gradR", 1), ("gradC", 1), ("gradL", 1)]) self.brain = createEmpty(range(4), range(4))
def __init__(self, size, width, height, mutation_chance, creatures_to_remain): self._population = [] self._width = width self._height = height self._mutation_chance = mutation_chance self._creatures_to_remain = creatures_to_remain for _ in range(size): self.add_creature(Creature(width, height))
def load(self): try: fp = open('save.json', 'r') self.data = json.load(fp) tempcreatures = [] for creaturedictionary in self.data: tempcreatures.append(Creature(creaturedictionary)) self.data = tempcreatures print('Loaded your saved data') except FileNotFoundError: print('No save files exist created new data') self.data = [ Creature({ 'name': "Fluffy", 'age': 3, 'weight': 2.4, 'hungry': True, 'photo': "(=^O.O^=)_" }) ]
def __init__(self, pos): image = ("RSC/Block/Pot1.png") Creature.__init__(self, "RSC/Block/Pot1.png", [0, 0], pos) self.speedx = 0 self.speedy = 0 self.upImages = [pygame.image.load("RSC/Block/Pot1.png")] self.upHurtImages = [ pygame.image.load("RSC/Block/Pot2.png"), pygame.image.load("RSC/Block/Pot3.png") ] self.health = 2 self.facing = "up" self.changed = False self.waitCount = 0 self.maxWait = 60 * .25 self.images = self.upImages self.frame = 0 self.maxFrame = len(self.images) - 1 self.image = self.images[self.frame] self.rect = self.image.get_rect(center=self.rect.center)
def AddCreature(self): print("Let's add a new Creature!") NewPet = {} NewPet['name'] = input("What is the new pet called? ") NewPet['age'] = int(input("How old is the pet? ")) NewPet['weight'] = int(input("What does the pet weigh? ")) NewPet['hungry'] = True NewPet['photo'] = input("What does the pet look like? ") self.data.append(Creature(NewPet)) self.show() self.save()
def process(self, powerPopulation, buildingPopulation, terrain): Creature.process(self, powerPopulation, buildingPopulation, terrain) self.buildTime += TIME_QUANTUM if(self.repair(terrain) == False): if(self.buildTime > PEASANT_BUILD_INTERVAL): self.buildTime = 0 if(random.randint(0,100) < PEASANT_BUILD_CHANCE): self.buildRandomBuilding(buildingPopulation, terrain) else: if(self.moving == False): self.moveEvil(terrain) #self.movePurposefully(terrain, buildingPopulation) else: if(self.moving == False): self.moveEvil(terrain)
def process(self, powerPopulation, buildingPopulation, terrain): Creature.process(self, powerPopulation, buildingPopulation, terrain) self.lastAttack += TIME_QUANTUM if(self.lastAttack > self.attackSpeed): for i in range(3): for j in range(3): thing = terrain.getThingOcupying(self.x+i-1,self.y+j-1) if(isinstance(thing, Creature) or isinstance(thing, Building)): if(thing.getTeam() != self.team and thing.isAlive()): thing.damage(random.randint(0, self.attack)) self.lastAttack = 0 return if(self.moving == False): self.moveEvil(terrain)
def process(self, powerPopulation, buildingPopulation, terrain): Creature.process(self, powerPopulation, buildingPopulation, terrain) self.lastAttack += TIME_QUANTUM if(self.lastAttack > self.attackSpeed): for i in range(7): for j in range(7): thing = terrain.getThingOcupying(self.x+i-3,self.y+j-3) '''If there is a creature near by that's an enemy''' if(isinstance(thing, Creature)): if(thing.getTeam() != self.team and thing.isAlive()): '''move towards it''' powerPopulation.addPower(Lightning(self.x, self.y, random.randint(0, self.attack), thing)) self.lastAttack = 0 return if(self.moving == False): self.moveEvil(terrain)
def __init__(self): pygame.init() self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN) self.clock = pygame.time.Clock() pygame.display.update() pygame.draw.rect( self.screen, (255, 0, 0), (pygame.display.get_surface().get_width() / 2 - 50, 20, 100, 100), 1) self.background = pygame.transform.scale( pygame.image.load("CreatureModel/back.png").convert(), ((pygame.display.get_surface()).get_width(), (pygame.display.get_surface()).get_height())) self.creature = Creature( pygame.image.load("CreatureModel/modelOne.png").convert_alpha()) while True: self.clock.tick(120) self.update()
def __init__(self): self._running = True self.surf = None self.frameCount = 1 self.startTime = time.time() self.runhistory = [] self.runs = 0 self.size = self.width, self.height = -1, -1 self.speed = 10 self.map = Map(32, 32) self.map.generate() self.keys = {} for i in range(300): self.keys[i] = False self.creature = Creature()
def __init__(self, x, y, team): Creature.__init__(self, x, y, PEASANT_SPEED, PEASANT_LIFE, PEASANT_REGENERATION, team) self.buildTime = 0
class App: def __init__(self): self._running = True self.surf = None self.frameCount = 1 self.startTime = time.time() self.runhistory = [] self.runs = 0 self.size = self.width, self.height = -1, -1 self.speed = 10 self.map = Map(32, 32) self.map.generate() self.keys = {} for i in range(300): self.keys[i] = False self.creature = Creature() def on_init(self): pygame.init() displayModes = pygame.display.list_modes() print "Display modes:", displayModes x = displayModes[0][0] y = displayModes[0][1] if x > 1440: x = 1440 if y > 900: y = 900 mode = (x,y) print "Using mode:", mode self.size = self.width, self.height = mode self.surf = pygame.display.set_mode(self.size, pygame.HWSURFACE | pygame.DOUBLEBUF | pygame.FULLSCREEN) pygame.mouse.set_visible(False) self.creature.place(self.map) self._running = True def on_event(self, event): if event.type == pygame.QUIT: self._running = False def on_loop(self): if self.creature._living == False: self.reset() if self.keys[pygame.K_LEFT]: self.speed += 1 if self.keys[pygame.K_UP]: pass if self.keys[pygame.K_RIGHT]: self.speed -= 1 if self.keys[pygame.K_DOWN]: pass if self.speed < 1: self.speed = 1 mouse_pos = pygame.mouse.get_pos() self.map.viewPos[0] += mouse_pos[0]-self.width/2 self.map.viewPos[1] += mouse_pos[1]-self.height/2 pygame.mouse.set_pos([self.width/2, self.height/2]) if self.frameCount % self.speed == 0: self.simUntilDeath() def simUntilDeath(self): while self.creature._living == True: self.creature.sim(self.map) def reset(self): self.runs += 1 self.runhistory.append([self.creature, self.map]) if self.runs > 4: self.runhistory.sort(key=lambda x: x[0].ticks, reverse=True) print "-----------------------------" #for run in self.runhistory: print "ticks:", self.creature.ticks for neuronRow in self.creature.network.network: for neuron in neuronRow: print neuron.weights print "-----------------------------" self.map.generate() self.creature = Creature() for layerNum in range(len(self.creature.network.network)): for neuronNum in range(len(self.creature.network.network[layerNum])): randomNum = random.randint(-4,min(32,len(self.runhistory)/2)) if randomNum < 0: self.creature.network.network[layerNum][neuronNum].weights = [random.random(), random.random(), random.random()] else: self.creature.network.network[layerNum][neuronNum] = self.runhistory[randomNum][0].network.network[layerNum][neuronNum] self.creature.place(self.map) else: self.map.generate() self.creature = Creature() self.creature.place(self.map) def on_render(self): self.surf.fill((0, 0, 0)) self.map.draw(self.surf) self.creature.draw(self.surf, self.map) self.frameCount += 1 def on_cleanup(self): pygame.quit() def setScale(self, scale): if scale < 1: return self.map.viewPos = [ (self.map.viewPos[0] - self.width/2)*(scale/self.map.scale)+self.width/2, (self.map.viewPos[1] - self.height/2)*(scale/self.map.scale)+self.height/2 ] self.map.scale = scale def main(self): if self.on_init() == False: self._running = False while self._running: for event in pygame.event.get(): if self.keys[pygame.K_ESCAPE]: self._running = False self.on_event(event) if event.type == pygame.KEYDOWN: self.keys[event.key] = True if event.type == pygame.KEYUP: self.keys[event.key] = False if event.type == pygame.QUIT: self._running = False if event.type == MOUSEBUTTONDOWN: if event.button == 4: self.setScale(self.map.scale * 1.03) if event.button == 5: self.setScale(self.map.scale * 0.97) if event.type == MOUSEBUTTONUP: if event.button == 1: self.reset() self.on_loop() self.on_render() pygame.display.flip() self.on_cleanup()
class Environment: """A 'box' of Creatures. Creatures can reproduce asexually and die.""" def __init__(self, initialPopSize=50, cycleLimit=100, idealImagePath=None): self.cycleLimit = cycleLimit # max number of cycles to run the simulation self.cycle = 0 # current cycle self.idealColor = IDEAL_RGB # the color that keeps things alive self.create_ideal(idealImagePath) # make a creature of just this color self.sequence = itertools.count() # generator for naming new creatures self.population = [] # list of creatures currently living in the environment self.populate(initialPopSize) def __str__(self): return 'Current Cycle:%d Current Size:%d ' % (self.cycle, len(self.population)) def create_ideal(self, idealImagePath=None): """Create a creature of a single ideal color.""" self.idealCreature = Creature(self, self.cycle, name='ideal') if idealImagePath is None: self.idealCreature.set_to_color(self.idealColor) else: self.idealCreature.set_colors_from_image(idealImagePath) def draw_ideal(self): """Draw an ideal creature using this environment's ideal color.""" self.idealCreature.save_image(fileName='./images/ideal.png') def populate(self, popSize): """Fill the Environment with a given number of Creatures.""" for i in range(popSize): thisName = "creature_%06d" % next(self.sequence) newCreature = Creature(self, self.cycle, name=thisName) self.population.append(newCreature) def kill(self): """Kill the weakest DEATHRATE Creatures. This is the first step in the simulation.""" self.population.sort(key=lambda creature: creature.get_fitness()) # sort by fitness del self.population[:DEATHRATE] def spawn(self): """Have the existing Creatures randomly reproduce to fill the DEATHRATE empty slots. This is the second step in the simulation generation cycle.""" parents = range(len(self.population)) threads = [] for i in range(DEATHRATE): newThread = CreateCreatureThread(environment=self, parent=self.population[choice(parents)], newName="creature_%06d" % next(self.sequence)) threads.append(newThread) newThread.start() for t in threads: t.join() def evolve_one_generation(self): """Take on step in generation (one cycle) to kill the weakest creatures and repopulate to fill the gaps.""" if self.cycle % 10 == 0: print 'Cycle %d' % self.cycle self.kill() self.spawn() self.cycle += 1 def run(self): """Run the simulation. Cycle through kill() and spawn() until we reach the cycle limit.""" while self.cycle < self.cycleLimit: self.evolve_one_generation() def end(self): """Draw Creatures and remove from memory.""" print 'making images' print 'Cycle %d' % self.cycle for creature in self.population: print creature.name, creature.fitness creature.save_image('./images/final/%s.png' % creature.name)