blog
嗯,写个东西玩,这就是很像进化的进化算法.
进化算法是以达尔文的进化论思想为基础,通过模拟生物进化过程与机制的求解问题的自组织、自适应的人工智能技术。生物进化是通过繁殖、变异、竞争和选择实现的;而进化算法则主要通过选择、重组和变异这三种操作实现优化问题的求解。
首先生成一个随机位置的"太阳",然后生成一堆位置随机会移动会光合作用,会呼吸作用的生命.靠近"太阳"将可以进行"光合作用",否则就只能进行"呼吸作用"消耗生命,当生命值消耗完就die了,当生命值很健康时有一定几率产生后代.
import random
import math
import pylab
import matplotlib.animation as animation
#一个太阳
sunCoordX = random.randint(1,99)
sunCoordY = random.randint(1,99)
#一堆生命
lifes = []
class Life(object):
"""一个会移动会光合会呼吸的生命"""
def __init__(self, name):
#super(Life, self).__init__()
self.name = name
self.x = random.randint(1,99)
self.y = random.randint(1,99)
self.hp = random.randint(0,99)
self.agility = random.randint(1,5)
self.cos = self.cosWithSun()
#一系列生化反应
def live(self):
self.move()
self.costHp()
self.photosynthesis()
self.birth()
#运动
def move(self):
self.x += round(random.randint(-self.agility,self.agility))
self.y += round(random.randint(-self.agility,self.agility))
if(self.x<=0):
self.x = 1
if(self.y<=0):
self.y = 1
self.cos = self.cosWithSun()
if(self.cos<5 and self.agility<10):
self.agility +=1
def printMe(self):
if(self.hp>0):
print "%s" % (self.name)
print "[cos:%f,x:%d,y:%d,hp:%d,agility:%d]" % (self.cos,self.x,self.y,self.hp,self.agility)
#靠近太阳 光合作用
def photosynthesis(self):
self.cos = self.cosWithSun()
if(self.cos<15):
#print "photosynthesis"
self.hp +=11
if(self.agility>1):
self.agility -=1
#呼吸 消耗生命值
def costHp(self):
self.hp -=10
if(self.hp<=0):
self.die()
def die(self):
print "%s die"%(self.name)
lifes.remove(self)
def cosWithSun(self):
cos = math.sqrt((sunCoordX-self.x)**2+(sunCoordY-self.y)**2)
#print "%d %d %d %d %d" % (sunCoordX,sunCoordY,self.x,self.y,cos)
return cos
#生小的
def birth(self):
if(random.randint(0,10)<2 and self.hp>70 and len(lifes)<2000):
child = Life(self.name+"_child")
child.x=self.x
child.y=self.y
child.hp=self.hp+1
child.agility=self.agility
lifes.append(child)
j=0
while(j<50):
life = Life("life%d"%(j))
lifes.append(life)
j+=1
fig = pylab.figure()
scat1 = pylab.scatter(1, 1, s=10,color='blue')
scat2 = pylab.scatter(1, 1, s=50,color='red')
pylab.xticks([0, 25, 50, 75, 100])
pylab.yticks([0, 25, 50, 75, 100])
def setup_plot():
return scat1,scat2
def update_plot(i):
print "lives num %d"%len(lifes)
data = []
for l in lifes:
#l.printMe()
data.append(l.x)
data.append(l.y)
l.live()
scat1.set_offsets([data])
scat2.set_offsets([sunCoordX,sunCoordY])
return scat1, scat2
ani = animation.FuncAnimation(fig, update_plot, interval=50, init_func=setup_plot, blit=True)
pylab.show()