Bài tập thực hành môn Các mẫu thiết kế hướng đối tượng - Bài thực hành số 9.1: Tiến hóa các tập luật chơi để tìm đường đi trong mê cung

Trang 1  
MÔN : CÁC MẪU THIẾT KẾ HỚNG ỐI TỢNG  
Bài thực hành số 9.1 : Tiến hóa các tập luật chi ể tìm ờng i trong mê cung  
I. Mục tiêu :  
. Giúp SV làm quen cách áp dụng gii thuật tiến hóa vào loi cá thể xác ịnh :  
tập luật miêu t ờng i của agent trong mê cung.  
II. Nội dung :  
Tổng hợp kết qu 2 bài thực hành .1 và 8.1 ể thử tiến hóa các tập luật miêu t  
ờng i của agent trong mê cung ban ầu về tập luật tối u.  
III. Chuẩn ầu ra :  
. Nắm vững tính chất, công dụng của các mẫu thiết kế ợc dùng trong bài  
thực hành này ể có thể dùng li các mẫu này trong bất kỳ vị trí nào của  
chng trình mới cần xây dựng.  
IV. Qui trình xây dựng chng trình  
1. Chy VS .Net, chọn menu File.Open.Project ể mở li Project của bài thực  
hành 8.1.  
2. Copy li các file mã nguồn ã viết trong bài thực hành .1 sang project hiện  
hành :  
Dời chuột về phần tử gốc của cây Project trong cửa sổ “Solution xplorer”, ấn  
phi chuột vào nó ể hiển thị menu lệnh, chọn chức nng Add.New Folder ể  
to 1 folder mới. ặt tên cho folder này là BaiTH . Click phi chuột vào folder  
mới vừa to và chọn option Add. xisting Item, duyệt chọn các file *.cs trong  
th mục qun lý project BaiTH ã có ể copy chúng vào folder hiện hành  
(chú ý không cần copy các file Program.cs, Form1.cs).  
3. Vào folder BaiTH của Project BaiTH81, duyệt xem và hiệu chỉnh (nếu cần)  
nội dung từng file mã nguồn theo nội dung mới nh sau :  
//nội dung file IEnvironment.cs  
interface IEnvironment {  
//tác vụ tính toán trị của cá thể  
double getVal(IIndividual ind);  
//tác vụ tính toán cá thể  
double eval(IIndividual ind);  
}
//nội dung file IIndividual.cs  
interface IIndividual : IComparable<IIndividual> {  
//thuộc tính luận lý SpecValue : chỉ ọc  
Object SpecValue { get; set; }  
//thuộc tính luận lý Fitness : ọc/ghi  
double Fitness { get; set; }  
//thuộc tính miêu t bị ột biến  
bool Muted { get; set; }  
//hàm phối giống với other  
Trang 2  
IIndividual cross(IIndividual other);  
//hàm ột biến mình  
void muter();  
//hàm to ối tợng mới theo c chế nhân bn vô tính (dùng mẫu Prototype)  
IIndividual clone();  
//hàm gii mã ối tợng thành dng chuỗi vn bn  
String ToString();  
}
//nội dung file Individual.cs  
class Individual : IIndividual {  
//giá trị ặc trng của cá thể  
private MyDouble spVal;  
//ộ thích nghi của cá thể  
private double fitness = 0.0;  
//thuộc tính miêu t ã bị ộ biến cha  
private bool muted = false;  
//ối tợng to số ngẫu nhiên duy nhất trong toàn chng trình  
private static MyRandom rnd = MyRandom.getInstance();  
//hàm khởi to cá thể có giá trị ặc trng ngẫu nhiên  
public Individual()  
{
this.spVal = new MyDouble(rnd.RndDouble());  
}
//hàm khởi to cá thể có giá trị ặc trng xác ịnh  
public Individual(MyDouble valeurPropre)  
{
this.spVal = valeurPropre;  
}
//hiện thực thuộc tính luận lý Muted  
public bool Muted  
{
get { return muted; }  
set { muted = value; }  
}
//hiện thực thuộc tính luận lý SpecValue  
public Object SpecValue  
{
get { return spVal; }  
set { spVal = (MyDouble)value; }  
}
//hiện thực thuộc tính luận lý Fitness  
public double Fitness  
Trang 3  
{
}
get { return fitness; }  
set { fitness = value; }  
//hàm gii mã ối tợng thành chuỗi vn bn  
public override String ToString()  
{
//return String.Format("vp={0:f4}, fit={1:f4}",valeurPropre, fitness);  
return String.Format("{0:f }", spVal);  
}
//hàm so sánh với cá thể khác (phục vụ sắp xếp danh sách)  
public int CompareTo(IIndividual o)  
{
if (o.Fitness == Fitness)  
return 0;  
else if (Fitness < o.Fitness)  
return -1;  
return 1;  
}
//hàm phối giống với cá thể khác  
public IIndividual cross(IIndividual other)  
{
MyDouble o1 = SpecValue as MyDouble; //giá trị ặc trng của mình  
MyDouble o2 = other.SpecValue as MyDouble;//giá trị ặc trng của ối tác  
//to cá thể con  
if (o1 == null && o2 == null) return new Individual(new MyDouble(0));  
if (o1 == null) return other;  
if (o2 == null) return this;  
return new Individual(new MyDouble((o1.Val + o2.Val) / 2));  
}
//hàm ột biến cá thể hiện hành  
public void muter()  
{
//ột biến tối a 10% biên ộ giá trị ặc trng  
// spVal += (rnd.RndDouble() < 0. ? 1 : -1) * rnd.RndDouble() * 0.1 * spVal;  
//theo trung bình cộng với giá trị ặc trng ngẫu nhiên  
spVal = new MyDouble((spVal.Val + rnd.RndDouble()) / 2);  
//theo giá trị ặc trng ngẫu nhiên  
// spVal = Math.random();  
}
Trang 4  
//hàm to ối tợng mới theo c chế nhân bn vô tính (dùng mẫu Prototype)  
public IIndividual clone()  
{
return new Individual(spVal);  
}
}
//nội dung file IPopulation.cs  
interface IPopulation {  
//hàm tr về số cá thể  
int size();  
//hàm thêm cá thể mới vào thế hệ  
void add(IIndividual individu);  
//hàm xuất giá trị các các thể  
String OutValue(IEnvironment cible);  
//hàm gii mã ối tợng thành chuỗi vn bn  
String ToString();  
//hàm tiến hóa sang thế hệ mới  
IPopulation evoluer(IEnvironment cible);  
}
//nội dung file IPopulationFactory.cs  
interface IPopulationFactory {  
IPopulation createRandomPopulation(int size);  
}
//nội dung file MyDouble.cs  
class MyDouble {  
private double val;  
public MyDouble(double v) { val = v; }  
public double Val  
{
get { return val; }  
set { val = value; }  
}
//hàm gii mã ối tợng mục tiêu ra chuỗi vn bn  
public override String ToString()  
{
String buf = String.Format("{0:f }", val);  
return buf;  
}
}
//nội dung file MyRandom.cs  
class MyRandom {  
//hàm khởi to private ể cấm bên ngoài to ối tợng MyRandom  
private MyRandom() { }  
Trang 5  
//thông tin dùng chung trong class  
private static MyRandom myrnd = new MyRandom();  
public static MyRandom getInstance() { return myrnd; }  
//thông tin trong ối tợng  
private Random rnd = new Random();  
public int RndInt() { return rnd.Next(); }  
public int RndInt(int n) { return rnd.Next(n); }  
public double RndDouble() { return rnd.NextDouble(); }  
}
//nội dung file Population.cs  
class Population : IPopulation {  
//qun lý thế hệ các cá thể bằng class List<T> của .NET  
private List<IIndividual> individus = new List<IIndividual>();  
//dùng ối tợng to số ngẫu nhiên duy nhất trong toàn chng trình  
private static MyRandom rnd = MyRandom.getInstance();  
//hàm tr về số cá thể  
public int size() {  
return individus.Count();  
}
//hàm thêm cá thể mới vào thế hệ  
public void add(IIndividual individu) {  
individus.Add(individu);  
}
//hàm gii mã ối tợng thành chuỗi vn bn  
public String OutValue(IEnvironment target)  
{
String buf = "[";  
bool fstart = true;  
for (int i = 0; i < individus.Count(); i++)  
if (fstart)  
{
fstart = false;  
buf += String.Format("{0:f }", target.getVal(individus[i]));  
}
else buf += ", " + String.Format("{0:f }", target.getVal(individus[i]));  
return buf + "]";  
}
//hàm gii mã ối tợng thành chuỗi vn bn  
public override String ToString() {  
String buf = "[";  
bool fstart = true;  
for (int i = 0; i < individus.Count(); i++)  
Trang 6  
if (fstart) {  
fstart = false;  
buf += individus[i].ToString();  
}
else buf += ", " + individus[i].ToString();  
return buf + "]";  
}
//hàm tiến hóa sang thế hệ mới  
public IPopulation evoluer(IEnvironment cible) {  
//tính ộ thích nghi các cá thể và sắp xếp chúng  
evaluer(cible);  
//to thế hệ mới  
Population pop = reproduire();  
//cho % cá thể bị ột biến  
pop.muter(0.1);  
//tính li ộ thích nghi các cá thể và sắp xếp chúng  
//pop.evaluer(cible);  
return pop;  
}
//hàm tính ộ thích nghi của từng cá thể và sắp xếp các cá thể theo ộ thích nghi của  
chúng  
private void evaluer(IEnvironment cible) {  
//lặp tính ộ thích nghi của từng cá thể  
foreach (IIndividual ind in individus)  
{
ind.Fitness = cible.eval(ind);  
}
//sắp xếp các cá thể theo ộ thích nghi của chúng  
Sort();  
}
//hàm sắp xếp thự tự các cá thể theo ngữ nghĩa xác ịnh  
private void Sort() {  
individus.Sort();  
individus.Reverse();  
}
//hàm ột biến cho cá thể  
private void muter(double ratio) {  
List<IIndividual> subl = individus. etRange(1, individus.Count - 1);  
//chọn ngẫu nhiên cá thể và thực hiện ột biến nó  
foreach (IIndividual ind in subl) {  
if (rnd.RndDouble() < ratio)  
ind.muter();  
Trang 7  
}
}
//hàm to thế hế mới  
private Population reproduire() {  
//chọn 20% cá thể có ộ thích nghi tốt nhất  
int max = individus.Count() / ;  
Population pop = new Population();  
//cho chúng thành cá thể của thế hệ mới  
for (int i = 0; i < max; i++) {  
pop.add(individus[i].clone());  
}
//lặp phối giống từng cặp cá thể ã có (chọn ngẫu nhiên) ể to thêm 80% cá thể mới  
for (int i = max; i < size(); i++) {  
int mec = rnd.RndInt(max);  
int mef = rnd.RndInt(max);  
pop.add(individus[mec].cross(individus[mef]));  
}
return pop;  
}
}
//nội dung file PopulationFactory.cs  
class PopulationFactory {  
public IPopulation createRandomPopulation(int size)  
{
//to 1 thế hệ rỗng  
IPopulation pop = new Population();  
//lặp thêm từng cá thể vào thế hệ  
for (int i = 0; i < size; i++)  
{
pop.add(new Individual());  
}
return pop;  
}
}
//nội dung file Target.cs  
class Target : IEnvironment {  
//giá trị mục tiêu mà ta mong muốn t ợc  
private double val;  
//ối tợng to số ngẫu nhiên duy nhất trong toàn chng trình  
private MyRandom rnd = MyRandom.getInstance();  
//hàm khởi to ngẫu nhiên giá trị mục tiêu  
public Target()  
{
val = rnd.RndDouble();  
Trang 8  
}
//hàm khởi to giá trị mục tiêu xác ịnh  
public Target(double d)  
{
val = d;  
}
//hàm tính ộ thích nghi của ối tợng theo ngữ nghĩa mong muốn  
//càng gần với mục tiêu càng có ộ thích nghi cao  
public double eval(IIndividual i)  
{
MyDouble o1 = i.SpecValue as MyDouble;  
if (o1 == null) return 0;  
return 1 / ((o1.Val - val) * (o1.Val - val));  
}
//tác vụ tính toán trị của cá thể  
public double getVal(IIndividual i) {  
MyDouble o1 = i.SpecValue as MyDouble;  
if (o1 == null) return 0;  
return o1.Val;  
}
//hàm tr về giá trị mục tiêu  
public double getValue()  
{
return val;  
}
//hàm gii mã ối tợng mục tiêu ra chuỗi vn bn  
public override String ToString()  
{
String buf = String.Format(" iá trị mong muốn : {0:f }", val);  
return buf;  
}
}
//nội dung file AbstractIndividual.cs  
abstract class AbstractIndividual : IIndividual {  
protected double fitness = 0.0;  
protected bool muted = false;  
public AbstractIndividual()  
{
}
//thuộc tính luận lý SpecValue : chỉ ọc  
public abstract Object SpecValue { get; set; }  
Trang 9  
public bool Muted  
{
get { return muted; }  
set { muted = value; }  
}
public double Fitness  
{
get { return fitness; }  
set { fitness = value; }  
}
//hàm so sánh với cá thể khác (phục vụ sắp xếp danh sách)  
public int CompareTo(IIndividual o)  
{
if (o.Fitness == Fitness)  
return 0;  
else if (Fitness < o.Fitness)  
return -1;  
return 1;  
}
//hàm nhân bn mình theo mẫu Prototype  
public abstract IIndividual clone();  
//hàm ột biến mình  
public abstract void muter();  
//hàm phối giống với other  
public abstract IIndividual cross(IIndividual other);  
}
4. Ở th mục gốc của Project, hiện thực class Score miêu t iểm tích lũy của  
agent. Viết code cho class này nh sau (lu ý các file mã nguồn ợc to mới  
ều phi dùng 2 lệnh using BaiTH using BaiTH81. ditLaby vì chúng có  
dùng các phần tử trong 2 namespace cũ này):  
class Score {  
//ịnh nghĩa các hằng cần dùng  
private const int DEFAULT_SCORE = 1;  
private const int DEFAULT_INCREMENT = 1;  
//iểm  
private int score;  
//hàm khởi to  
public Score()  
{
score = DEFAULT_SCORE;  
}
Trang 10  
//hàm tham kho iểm  
public int getScore()  
{
return score;  
}
//hàm tng iểm  
public void incrementScore()  
{
score += DEFAULT_INCREMENT;  
}
}
.
Ở th mục gốc của Project, hiện thực class Rule miêu t 1 luật i của agent.  
Viết code cho class này nh sau :  
class Rule : IComparable {  
//bng thông tin iều khiển  
private LabyItem[] conditions;  
//chiều di chuyển  
private Direction action;  
//hàm khởi to luật không xác ịnh  
public Rule() {  
conditions = new LabyItem[8];  
}
//hàm khởi to luật theo tham số xác ịnh  
public Rule(LabyItem[] cond, Direction dir) {  
conditions = cond;  
action = dir;  
}
//hàm khởi to luật theo tham số xác ịnh bằng chuỗi  
public Rule(String contenu, Direction dir) {  
conditions = new LabyItem[8];  
for (int i = 0; i < contenu.Length; i++)  
{
char symbol = contenu[i];  
switch (symbol)  
{
case '?':  
conditions[i] = LabyItem.ANY;  
break;  
case '.':  
conditions[i] = LabyItem.POINT;  
break;  
case ' ':  
Trang 11  
conditions[i] = LabyItem.NULL;  
break;  
case '#':  
conditions[i] = LabyItem.WALL;  
break;  
default:  
conditions[i] = LabyItem.A ENT;  
break;  
}
}
action = dir;  
}
//hàm kiểm tra luật có match với bng thông tin dò ờng  
public bool matches(LabyItem[] sensors) {  
for (int i = 0; i < 8; i++)  
{
if (conditions[i] != LabyItem.ANY)  
{
if (conditions[i] != sensors[i])  
return false;  
}
}
return true;  
}
//hiện thực thuộc tính Action (chiều di chuyển)  
public Direction Action {  
get { return action; }  
set { this.action = value; }  
}
//hàm thiết lập thông tin di chuyển  
public void setCondition(int index, LabyItem wall) {  
conditions[index] = wall;  
}
//hàm nhân bn vô tính ối tợng theo mẫu Prototype  
public Rule clone() {  
Rule retour = new Rule();  
retour.Action = Action;  
Array.Copy(conditions, retour.conditions, conditions.Length);  
return retour;  
}
//hàm gii mã ối tợng về chuỗi vn bn  
public override String ToString() {  
Trang 12  
StringBuilder retour = new StringBuilder("\r\n");  
retour.Append(ToChar(conditions[ ]));  
retour.Append(ToChar(conditions[0]));  
retour.Append(ToChar(conditions[1]));  
retour.Append("\r\n");  
retour.Append(ToChar(conditions[6]));  
retour.Append("x");  
retour.Append(ToChar(conditions[2]));  
retour.Append("\r\n");  
for (int i = ; i >2; i--)  
{
retour.Append(ToChar(conditions[i]));  
}
return retour + " -> " + action;  
}
//hàm gii mã nội dung cell thành ký tự miêu t  
private char ToChar(LabyItem cellContent) {  
switch (cellContent)  
{
case LabyItem.ANY:  
return '?';  
case LabyItem.POINT:  
return '.';  
case LabyItem.NULL:  
return 'n';  
case LabyItem.WALL:  
return '#';  
default:  
return '$';  
}
}
//tác vụ tính giá trị hashcode cho phần tử này  
public override int etHashCode() {  
//tính giá trị hashcode cho phần tử này rồi tr về  
return base. etHashCode();  
}
/*public int hashCode()  
{
const int prime = 31;  
int result = 1;  
result = prime * result + ((action == null) ? 0 : action.hashCode());  
result = prime * result + Arrays.hashCode(conditions);  
return result;  
Trang 13  
}*/  
public override bool Equals(Object obj)  
{
if (this == obj)  
return true;  
if (obj == null)  
return false;  
Rule other = obj as Rule;  
if (other == null)  
return false;  
if (action == null)  
{
if (other.action != null)  
return false;  
}
else if (!action.Equals(other.action))  
return false;  
if (!Array.Equals(conditions, other.conditions))  
return false;  
return true;  
}
//tác vụ so sánh tổng quát CompareTo  
public int CompareTo(Object obj)  
{
if (this == obj)  
return 0;  
if (obj == null) return 1;  
Rule other = obj as Rule;  
if (other == null)  
throw new ArgumentException("Object is not a Item");  
return -1;  
}
}
.
Ở th mục gốc của Project, hiện thực interface IController và class Controller  
miêu t 1 tập luật i của agent. Viết code cho interface và class này nh sau :  
interface IController {  
//chọn chiều di chuyển theo thông tin dò ờng  
Direction ChooseAction(LabyItem[] sensors);  
//nhân bn vô tính theo mẫu Prototype  
IController clone();  
//ột biến luật  
void muter(double d);  
//to mới ối tợng Controller  
IController CreateSon(IController controller, double d);  
Trang 14  
//hàm tr về kích thớc của tập luật  
int Size();  
//hàm thêm 1 luật vào danh sách luật  
bool add(Rule rule);  
//ịnh nghĩa indexer  
Rule this[int i] { get; set; }  
}
class Controller : IController {  
//sử dụng ối tợng to số ngẫu nhiên duy nhất theo mẫu Singleton  
private static MyRandom rnd = MyRandom.getInstance();  
//tập luật của Controller  
private List<Rule> ruleset = new List<Rule>();  
//hàm chọn hớng i thích hợp  
public Direction ChooseAction(LabyItem[] sensors) {  
foreach (Rule r in ruleset)  
{
if (r.matches(sensors))  
return r.Action;  
}
return Direction.STOP;  
}
//hàm ột biến  
public void muter(double proba) {  
for (int i = 0; i < Size(); i++)  
{
if (rnd.RndDouble() < proba)  
{
ruleset[i] = ControlFactory.generateRandomRule();  
}
}
}
public Rule this[int i] {  
get {  
return ruleset[i];  
}
set { ruleset[i] = value; }  
}
//hàm copy  
public IController copieCroisee(IController parent) {  
IController pere = (IController)parent;  
IController retour = clone();  
int cr1 = rnd.RndInt(Size());  
int cr2 = rnd.RndInt(pere.Size());  
retour[cr1] = pere[cr2];  
Trang 15  
return retour;  
}
//hàm to ối tợng con và ột biến nó  
public IController CreateSon(IController expr, double proba) {  
IController son = copieCroisee(expr);  
son.muter(proba);  
return son;  
}
//hàm nhân bn vô tính theo mẫu Prototype  
public IController clone() {  
IController retour = new Controller();  
foreach (Rule r in ruleset)  
{
retour.add(r.clone());  
}
return retour;  
}
//hàm thêm 1 luật vào danh sách luật  
public bool add(Rule rule) {  
try  
{
ruleset.Add(rule);  
return true;  
}
catch (Exception e) { return false; }  
}
//hàm gi mã ối tợng thành chuỗi vn bn  
public override String ToString() {  
return ruleset.ToString();  
}
public List<Rule> getRuleset() {  
return ruleset;  
}
public void setRuleset(List<Rule> ruleset) {  
this.ruleset = ruleset;  
}
//hàm tr về kích thớc của tập luật  
public int Size() {  
return ruleset.Count;  
}
Trang 16  
//tác vụ tính giá trị hashcode cho phần tử này  
public override int etHashCode() {  
//tính giá trị hashcode cho phần tử này rồi tr về  
return base. etHashCode();  
}
/*public int hashCode()  
{
const int prime = 31;  
int result = 1;  
result = prime * result + ((ruleset == null) ? 0 : ruleset.hashCode());  
return result;  
}*/  
public bool Equals(Object obj) {  
if (this == obj)  
return true;  
if (obj == null)  
return false;  
Controller other = obj as Controller;  
if (other == null)  
return false;  
if (ruleset == null)  
{
if (other.ruleset != null)  
return false;  
}
else if (!ruleset.Equals(other.ruleset))  
return false;  
return true;  
}
}
.
Ở th mục gốc của Project, hiện thực class ControlFactory phục vụ việc to  
các ối tợng Controller. Viết code cho interface và class này nh sau :  
class ControlFactory {  
//sử dụng ối tợng to số ngẩu nhiên duy nhất theo mẫu Singleton  
private static MyRandom rnd = MyRandom.getInstance();  
//hàm to ối tợng Controller  
public static IController CreateController(int nbRules) {  
IController c = new Controller();  
for (int i = 0; i < nbRules; i++)  
{
c.add(generateRandomRule());  
}
return c;  
Trang 17  
}
//hàm to 1 luật ngẫu nhiên  
static public Rule generateRandomRule() {  
Rule retour = new Rule();  
for (int i = 0; i < 8; i++) {  
double rand = rnd.RndDouble();  
if (rand > 0.20)  
// 80% joker  
retour.setCondition(i, LabyItem.ANY);  
else if (rand > 0.1 )  
// % mur  
retour.setCondition(i, LabyItem.WALL);  
else if (rand > 0.0 )  
// 10% bonus  
retour.setCondition(i, LabyItem.POINT);  
else  
// % blanc  
retour.setCondition(i, LabyItem.NULL);  
}
retour.Action = (Direction)rnd.RndInt(4);  
return retour;  
}
}
8. Ở th mục gốc của Project, hiện thực class ControllerIndividual miêu t 1 cá  
thể có giá trị ặc trng là 1 tập luật i của agent. Viết code cho class này nh  
sau :  
class ControllerIndividual : AbstractIndividual {  
private IController specval;  
//hàm khởi to  
public ControllerIndividual(IController controller) {  
this.specval = controller;  
}
//hàm khởi to  
public ControllerIndividual(int nbRules) {  
this.specval = ControlFactory.CreateController(nbRules);  
}
//hàm gii mã ối tợng về dng chuỗi gợi nhớ  
public override String ToString() {  
String ret = "" + Fitness + ":" + SpecValue;  
return ret;  
Trang 18  
}
//hiện thực thuộc tính SpecValue  
public override Object SpecValue {  
get { return specval; }  
set { specval = (IController)value; }  
}
public override IIndividual cross(IIndividual other) {  
ControllerIndividual o2 = other as ControllerIndividual;  
return new ControllerIndividual(specval.CreateSon((IController)o2.SpecValue, 0.0 ));  
}
public override void muter() {  
specval.muter(0.0 );  
}
public override IIndividual clone() {  
IIndividual ret = new ControllerIndividual(specval.clone());  
ret.Fitness = Fitness;  
return ret;  
}
}
.
Ở th mục gốc của Project, hiện thực class ControllerIndividualFactory có  
chức nng to các cá thể có giá trị ặc trng là 1 tập luật i của agent. Viết  
code cho class này nh sau :  
class ControlIndividualFactory {  
private static MyRandom rnd = MyRandom.getInstance();  
// hàm to 1 cá thể chứa tập luật có nbRules luật ngẫu nhiên  
public IController createController(int nbRules) {  
IController c = new Controller();  
for (int i = 0; i < nbRules; i++)  
{
c.add(generateRandomRule());  
}
return c;  
}
//hàm to 1 luật ngẫu nhiên  
private Rule generateRandomRule() {  
Rule retour = new Rule();  
for (int i = 0; i < 8; i++)  
{
double rand = rnd.RndDouble();  
if (rand > 0.20)  
// 80% joker  
Trang 19  
retour.setCondition(i, LabyItem.ANY);  
else if (rand > 0.1 )  
// % mur  
retour.setCondition(i, LabyItem.WALL);  
else if (rand > 0.0 )  
// 10% bonus  
retour.setCondition(i, LabyItem.POINT);  
else  
// % blanc  
retour.setCondition(i, LabyItem.NULL);  
}
retour.Action = (Direction)rnd.RndInt(4);  
return retour;  
}
}
10. Ở th mục gốc của Project, hiện thực class CtrlPopFactory có chức nng to  
thế hệ các cá thể có giá trị ặc trng là 1 tập luật i của agent. Viết code cho  
class này nh sau :  
class CtrlPopFactory {  
public IPopulation createRandomPopulation(int size, int nbRules, bool isSensor) {  
IPopulation pop = new Population();  
for (int i = 0; i < size; i++)  
{
pop.add(createIndividu(nbRules));  
}
return pop;  
}
public IIndividual createIndividu(int nbRules) {  
return new ControllerIndividual(nbRules);  
}
public IEnvironment createEnvironment(Labyrinth laby, int nbsteps) {  
return new MazeSimuEnvironment(laby, nbsteps);  
}
}
11. Ở th mục gốc của Project, hiện thực class Agent miêu t ngời chi (agent).  
Viết code cho class này nh sau :  
class Agent {  
//  
private LabyItem[] capteurs;  
//Agent biết về mê cung mà mình phi chi  
private Labyrinth laby;  
//vị trí của agent trong mê cung  
private MyPoint position;  
//luật chi của agent  
Trang 20  
private IController controleur;  
//bng iểm của agent  
private Score score;  
//hàm khởi to agent  
public Agent(MyPoint p, Labyrinth m, IController c) {  
position = p;  
capteurs = new LabyItem[8];  
controleur = c;  
score = new Score();  
laby = m;  
}
//hàm khởi to agent  
public Agent(MyPoint p, Labyrinth m) {  
position = p;  
capteurs = new LabyItem[8];  
controleur = ControlFactory.CreateController(0);  
score = new Score();  
laby = m;  
}
//hàm khởi to agent  
public Agent(int y, int x, Labyrinth m) {  
position = new MyPoint(y, x);  
capteurs = new LabyItem[8];  
controleur = ControlFactory.CreateController(0);  
score = new Score();  
laby = m;  
}
//hàm tham kho thông tin dò ờng của agent  
public LabyItem[] getSensorsArray() {  
return capteurs;  
}
//Thiết lập bng thông tin dò ờng của agent theo vị trí hiện hành của mê cung  
//qui ớc nh sau :  
// 0 = Bắc, 1 = ông bắc, 2 = ông, 3 = ông nam, 4 = Nam, = Tây nam, 6 = Tây, =  
Tây bắc  
private void UpdateCapteurs() {  
capteurs[0] = laby.getContenuCase(Position.y - 1,Position.x);  
capteurs[1] = laby.getContenuCase(Position.y - 1, Position.x + 1);  
capteurs[2] = laby.getContenuCase(Position.y, Position.x + 1);  
capteurs[3] = laby.getContenuCase(Position.y + 1, Position.x + 1);  
capteurs[4] = laby.getContenuCase(Position.y + 1, Position.x);  
capteurs[ ] = laby.getContenuCase(Position.y + 1, Position.x - 1);  
capteurs[6] = laby.getContenuCase(Position.y,Position.x - 1);  
Tải về để xem bản đầy đủ
pdf 27 trang myanh 19060 Free
Bạn đang xem 20 trang mẫu của tài liệu "Bài tập thực hành môn Các mẫu thiết kế hướng đối tượng - Bài thực hành số 9.1: Tiến hóa các tập luật chơi để tìm đường đi trong mê cung", để tải tài liệu gốc về máy hãy click vào nút Download ở trên

File đính kèm:

  • pdfbai_tap_thuc_hanh_mon_cac_mau_thiet_ke_huong_doi_tuong_bai_t.pdf