游戏编程中的人工智能技术-遗传算法入门(四)

本文介绍了游戏编程中使用遗传算法的基础,重点关注SGenome结构体及其在CgaBob类中的应用。CgaBob类包含创建初始种群、交叉(Crossover)和变异(Mutate)等关键函数,通过适应度函数计算来更新个体的适应值。文章以实际例子解释了如何根据累积概率选择个体,并强调了TestRoute函数在计算适应值中的作用。
摘要由CSDN通过智能技术生成

接下来介绍SGenome结构体。

struct SGenome
{
	vector<int> vecBits;
	
	double		dFitness;
	

	SGenome():dFitness(0){}
	
	SGenome(const int num_bits):dFitness(0)
	{
		//create a random bit string
		for (int i=0; i<num_bits; ++i)
		{
			vecBits.push_back(RandInt(0, 1)); //随机的产生一个染色体,vecBits.push_back表示往vecBits向量里塞值,RandInt(0, 1)表示塞的值要么是0,要么是1


		}
	}
};
定义了一个向量vecBIts,用来存储染色体中的每一位的。定义了一个dFItness,用来存储染色体的适应度函数值。

接下来就到了我们的正片环节:遗传算法类CgaBob了。

class CgaBob
{
private:

	//the population of genomes
	vector<SGenome>	m_vecGenomes; //定义一个向量m_vecGenomes,注意这个向量的每一个元素不是int型的了,是一个SGenome结构体,没错,每个元素都是一个结构体
	
	//size of population
	int             m_iPopSize;  //种群中染色体数

	double          m_dCrossoverRate; //杂交率
	
	double          m_dMutationRate; //变异率
	
	//how many bits per chromosome
	int             m_iChromoLength; //染色体的长度

	//how many bits per gene
	int             m_iGeneLength; //基因的长度
	
	int             m_iFittestGenome; //染色体的适应度
	
	double          m_dBestFitnessScore;//最佳染色体的适应度
	
	double          m_dTotalFitnessScore;//所有染色体适应度总和
	
	int             m_iGeneration;       //代数

	//create an instance of the map class
	CBobsMap        m_BobsMap;   

	//we use another CBobsMap object to keep a record of 
	//the best route each generation as an array of visited
	//cells. This is only used for display purposes.
	CBobsMap		m_BobsBrain;

	//lets you know if the current run is in progress.
	bool			m_bBusy;
	

	
	void        Mutate(vector<int> &vecBits);
	
	void        Crossover(const vector<int>	&mum,  //父类
                        const vector<int> &dad,<span style="white-space:pre">	</span>       //父类
                        vector<int>       &baby1,<span style="white-space:pre">	</span>//子类
                        vector<int>       &baby2);<span style="white-space:pre">	</span>//子类
	
	SGenome&		RouletteWheelSelection(); //轮盘赌
	
	//updates the genomes fitness with the new fitness scores and calculates
  //the highest fitness and the fittest member of the population.
  void			  UpdateFitnessScores();//适应度更新

	//decodes a vector of bits into a vector of directions (ints)
  vector<int>	Decode(const vector<int>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值