blog
嗯,寫個(gè)東西玩,這就是很像進(jìn)化的進(jìn)化算法.
進(jìn)化算法是以達(dá)爾文的進(jìn)化論思想為基礎(chǔ),通過模擬生物進(jìn)化過程與機(jī)制的求解問題的自組織、自適應(yīng)的人工智能技術(shù)。生物進(jìn)化是通過繁殖、變異、競(jìng)爭(zhēng)和選擇實(shí)現(xiàn)的;而進(jìn)化算法則主要通過選擇、重組和變異這三種操作實(shí)現(xiàn)優(yōu)化問題的求解。
首先生成一個(gè)隨機(jī)位置的"太陽(yáng)",然后生成一堆位置隨機(jī)會(huì)移動(dòng)會(huì)光合作用,會(huì)呼吸作用的生命.靠近"太陽(yáng)"將可以進(jìn)行"光合作用",否則就只能進(jìn)行"呼吸作用"消耗生命,當(dāng)生命值消耗完就die了,當(dāng)生命值很健康時(shí)有一定幾率產(chǎn)生后代.
import random
import math
import pylab
import matplotlib.animation as animation
#一個(gè)太陽(yáng)
sunCoordX = random.randint(1,99)
sunCoordY = random.randint(1,99)
#一堆生命
lifes = []
class Life(object):
"""一個(gè)會(huì)移動(dòng)會(huì)光合會(huì)呼吸的生命"""
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()
#一系列生化反應(yīng)
def live(self):
self.move()
self.costHp()
self.photosynthesis()
self.birth()
#運(yùn)動(dòng)
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)
#靠近太陽(yáng) 光合作用
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()