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ố 8.1 : Viết chương trình soạn thảo 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ố 8.1 : Viết chng trình son tho mê cung  
I. Mục tiêu :  
. Giúp SV làm quen cách viết chng trình có kh nng tng tác trực quan  
với ngời dùng. Giúp SV nắm vững cấu trúc của mê cung mà s ợc dùng  
trong bài thực hành .1.  
II. Nội dung :  
Mê cung là 1 ma trận 2 chiều gồm nhiều hàng và cột. Giao mỗi hàng và mỗi cột là  
1 cell. Cell có thể chứa 1 phần tử xác ịnh của mê cung. Trong bài này, ta giới hn  
dùng 3 loi cell : cell trống là cell mà ngời chi có thể i qua cell tờng là cell mà  
ngời chi không thể i qua cell iểm là cell mà ngời chi có thể i qua và khi i  
qua, ngời chi s tng ợc 1 iểm tích lũy. Trong bài thực hành .1, ta s sử  
dụng thuật toán tiến hóa ã viết ở bài thực hành .1 ể tìm ờng i tha mãn  
iều kiện : số bớc i xác ịnh, n nhiều iểm nhất có thể có.  
Nội dung bài thực hành này là viết cng trình cho phép ngời dùng son tho mê  
cung bất kỳ ể có thễ dùng li trong bài thực hành .1. Chng trình gồm 1 form  
chứa :  
-
-
-
menu bar chứa 1 menu pop-up. Menu pop-up chứa 2 option chính yếu : Load  
file mê cung và Lu file mê cung.  
anel chứa mê cung cần son tho, ể n gin ta qui ịnh kích thớc mê  
cung theo chuẩn 20 x 20 cell.  
Danh sách 3 loi cell cần son : cell trống, cell iểm, cell tờng ể ngời dùng  
có thể chọn từng thời iểm.  
Form có dng nh sau :  
III. Chuẩn ầu ra :  
. Nắm vững cách viết chng trình có kh nng tng tác trực quan với ngời  
dùng.  
IV. Qui trình xây dựng chng trình  
1. Dùng chng trình aint ể son 4 hình bitmap miêu t 4 loi cell ợc dùng  
trong mê cung. Chọn kích thớc 30x30 pixels. Lu các hình lên các file bitmap  
ở th mục xác ịnh. Nhớ vị trí th mục này ể các bớc sau dùng li các file  
nh.  
2. Chy VS .Net, chọn menu File.New. roject ể hiển thị cửa sổ New roject.  
3. Mở rộng mục Visual C# trong TreeView " roject Types", chọn mục Window,  
chọn icon "Windows Form Application" trong listbox "Templates" bên phi,  
thiết lập th mục chứa roject trong listbox "Location", nhập tên roject vào  
Trang 2  
textbox "Name:" (td. BaiTH81), click button OK ể to roject theo các thông  
số ã khai báo.  
3. Form ầu tiên của ứng dụng ã hiển thị trong cửa sổ thiết kế, việc thiết kế  
form là quá trình lặp 4 thao tác to mới/xóa/hiệu chỉnh thuộc tính/to hàm  
xử lý sự kiện cho từng ối tợng cần dùng trong form.  
4. Do nội dung của form chỉ ợc hiển thị ộng nên ta không thiết kế trực quan  
ợc, do ó ta viết code ể hiển thị ộng form. Vào cửa sổ son code cho form  
và thêm on code sau vào hàm khởi ộng form :  
public Form1() {  
InitializeComponent();  
//to ối tợng qun lý assembly  
System.Reflection.Assembly myAssembly =  
System.Reflection.Assembly. et xecutingAssembly();  
//to ối tợng Stream miêu t nh bitmap  
Stream myStream =  
myAssembly. etManifestResourceStream("BaiTH 1.Resources.dot.bmp");  
//to ối tợng nh bitmap cho cell dot  
dotbm = new Bitmap(myStream);  
//to ối tợng nh bitmap cho cell space  
myStream =  
myAssembly. etManifestResourceStream("BaiTH 1.Resources.space.bmp");  
spacebm = new Bitmap(myStream);  
//to ối tợng nh bitmap cho cell space  
myStream =  
myAssembly. etManifestResourceStream("BaiTH 1.Resources.wall.bmp");  
wallbm = new Bitmap(myStream);  
this.ClientSize = new Size(COLS * CSIZ +300,ROWS * CSIZ );  
this.MouseDown += new Mouse ventHandler(Frm_MouseDown);  
//tiêu ề form  
this.Text = "Laby Builder";  
//to mê cung  
laby = new Labyrinth(ROWS, COLS);  
//to Panel và menu  
CreateCenterPanel();  
CreateMenus();  
}
.
Dời chuột về ầu class Form1 rồi thêm các lệnh ịnh nghĩa sau :  
//ịnh nghĩa các hằng cần dùng  
private const long serialVersionUID = 1L;  
private const String S R_ XPORT_M NU = "Save labyrinth";  
private const String S R_IMPORT_M NU = "Load labyrinth";  
private const int ROWS = 20, COLS = 20;  
private const int CSIZ = 30;  
private Bitmap dotbm, spacebm, wallbm;  
//vùng chứa các buttons  
Trang 3  
private Panel sidePanel;  
//mê cung cần hiển thị  
private Labyrinth laby;  
private LabyItem actionChoosed = LabyItem.WALL;  
// Pour les tests getSource dans le Menu Listener : les sources d'événements menu  
private MenuItem mi_export;  
private MenuItem mi_import;  
//vùng hiển thị mê cung  
private LabyPanel centerPanel;  
private int xl, yl;  
//hàm to menu  
private void CreateMenus()  
{
//to 2 option phục vụ thực hiện 2 tác vụ xport/Import mê cung  
mi_export = new MenuItem(S R_ XPORT_M NU, xport_Click);  
mi_import = new MenuItem(S R_IMPORT_M NU, Import_Click);  
MenuItem[] fmItems = new MenuItem[2];  
fmItems[0] = mi_export;  
fmItems[1] = mi_import;  
//to menu File và add vào menu bar;  
MenuItem fmenu = new MenuItem("File", fmItems);  
//to menu bar cho form  
MenuItem[] mbItems = new MenuItem[1];  
mbItems[0] = fmenu;  
MainMenu mainMenu = new MainMenu(mbItems);  
this.Menu = mainMenu;  
}
//tác vụ v bộ mặt giao diện của Button  
protected override void OnPaint(Paint ventArgs e)  
{
raphics g = e. raphics;  
int xl = ClientSize.Width - 260;  
int yl = 20;  
//xuất các chuỗi hớng dẫn  
//to ối tợng font chữ cần dùng  
Font myFont = new Font("BKHelvetica", 10);  
//to biến miêu t chế ộ canh giữa khi xuất chuỗi  
StringFormat format1 = new StringFormat(StringFormatFlags.NoClip);  
format1.Alignment = StringAlignment.Near;  
Brush brush = System.Drawing.Brushes.Black;  
//xuất chuỗi miêu t giờ/phút/giây  
g.DrawString("Click chọn mẫu cell cần dùng", myFont, brush, xl, yl, format1);  
yl += 20;  
g.DrawString("Rồi Click vào cell cần son", myFont, brush, xl, yl, format1);  
yl += 20;  
g.DrawString("ể son cell theo mẫu chọn.", myFont, brush, xl, yl, format1);  
Trang 4  
yl += 30;  
//to các Button chức nng  
g.DrawImage(spacebm, xl, yl);  
g.DrawImage(dotbm, xl + CSIZ + 20, yl);  
g.DrawImage(wallbm, xl + 2 * (CSIZ + 20), yl);  
//lu vị trí các icon mẫu cell  
this.xl = xl; this.yl = yl;  
yl += 0;  
g.DrawString("Mẫu cell ang chọn:", myFont, brush, xl, yl, format1);  
yl += 2 ;  
Bitmap bm = null;  
switch (actionChoosed)  
{
case LabyItem.NULL: bm = spacebm; break;  
case LabyItem.POINT: bm = dotbm; break;  
case LabyItem.WALL: bm = wallbm; break;  
}
g.DrawImage(bm, xl, yl);  
}
private void Frm_MouseDown(object sender, Mouse ventArgs e)  
{
//xác ịnh vị trí chuột hiện hành  
//Point mousePos = Control.MousePosition;  
if (e.X < xl) return;  
if (e.Y < yl) return;  
if (e.Y > yl + CSIZ ) return;  
//tính tọa ộ luận lý chuột ợc click  
int c = (e.X - xl) / (CSIZ + 20);  
if (c > 2) return;  
switch (c)  
{
case 0: actionChoosed = LabyItem.NULL; break;  
case 1: actionChoosed = LabyItem.POINT; break;  
case 2: actionChoosed = LabyItem.WALL; break;  
}
centerPanel.ActionSelected = actionChoosed;  
//v li panel mê cung  
// Refresh();  
Rectangle rc = new Rectangle();  
rc.Location = new Point(xl, 20);  
rc.Size = new Size(1 0, 00);  
Invalidate(rc);  
}
//hàm xử lý option xport  
Trang 5  
private void xport_Click(object sender, ventArgs e)  
{
exportMazeData();  
}
//hàm xử lý option Import  
private void Import_Click(object sender, ventArgs e)  
{
chargerLabyrinthe();  
}
//hàm to Panel chính  
private void CreateCenterPanel()  
{
centerPanel = new LabyPanel(laby);  
Controls.Add(centerPanel);  
}
public static DialogResult InputBox(string title, string promptText, ref string value)  
{
Form form = new Form();  
Label label = new Label();  
TextBox textBox = new TextBox();  
Button buttonOk = new Button();  
Button buttonCancel = new Button();  
form.Text = title;  
label.Text = promptText;  
textBox.Text = value;  
buttonOk.Text = "OK";  
buttonCancel.Text = "Cancel";  
buttonOk.DialogResult = DialogResult.OK;  
buttonCancel.DialogResult = DialogResult.Cancel;  
label.SetBounds( , 20, 372, 13);  
textBox.SetBounds(12, 36, 372, 20);  
buttonOk.SetBounds(228, 72, 7 , 23);  
buttonCancel.SetBounds(30 , 72, 7 , 23);  
label.AutoSize = true;  
textBox.Anchor = textBox.Anchor | AnchorStyles.Right;  
buttonOk.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;  
buttonCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;  
form.ClientSize = new Size(3 6, 107);  
form.Controls.AddRange(new Control[] { label, textBox, buttonOk, buttonCancel });  
form.ClientSize = new Size(Math.Max(300, label.Right + 10), form.ClientSize.Height);  
Trang 6  
form.FormBorderStyle = FormBorderStyle.FixedDialog;  
form.StartPosition = FormStartPosition.CenterScreen;  
form.MinimizeBox = false;  
form.MaximizeBox = false;  
form.AcceptButton = buttonOk;  
form.CancelButton = buttonCancel;  
DialogResult dialogResult = form.ShowDialog();  
value = textBox.Text;  
return dialogResult;  
}
//lu mê cung lên file  
public void exportMazeData()  
{
//thiết lập chế ộ cập nhật  
centerPanel.modifLaby();  
String fileName = null;  
InputBox("Nhập tên file : ", "Nhập tên file cần ghi", ref fileName);  
LabyrinthLoader.Save_Labyrinth(fileName, laby);  
}
//np mê cung từ file  
public void chargerLabyrinthe()  
{
//to form duyệt chọn file cần ọc  
OpenFileDialog dlg = new OpenFileDialog();  
//hiển thị form duyệt chọn file cần ọc  
DialogResult ret = dlg.ShowDialog();  
//kiểm tra quyết ịnh của ngời dùng, nếu ngời dùng chọn OK thì ọc  
if (ret != DialogResult.OK) return;  
try  
{
laby = LabyrinthLoader.Load_Labyrinth(dlg.FileName);  
}
catch (IO xception e)  
{
MessageBox.Show("Không ọc ợc file " + dlg.FileName);  
return;  
}
catch (LabyFault ntour xception e)  
{
laby. ntourofWalls();  
}
catch (BeginCellNotNull xception e)  
{
laby.setContenuCase(1, 1, LabyItem.NULL);  
Trang 7  
}
catch ( xception e)  
{
MessageBox.Show("Lỗi cha xác ịnh.");  
return;  
}
centerPanel.setLaby(laby);  
}
//lu mê cung ra file  
public void sauverLabyrinthe nXML()  
{
centerPanel.modifLaby();  
LabyrinthLoader.chargerLabyrinthe nXML("maze_xml.txt", laby);  
}
Lu ý thêm lệnh using sau vào ầu file mã nguồn ặc t Form1 ể nó có thể  
sử dụng các file ợc to ra trong các bớc kế tiếp :  
using BaiTH81. ditLaby  
6. Dời chuột về phần tử gốc của cây roject 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à ditLaby. Trong th mục này, ta s  
chứa các file mã nguồn ợc to ra trong bài thực hành này.  
.
Dời chuột về folder ditLaby, ấn phi chuột vào nó ể hiển thị menu lệnh,  
chọn chức nng Add.Class ể hiển thị cửa sổ “Add New Item”, chọn mục  
“Class”, hiệu chỉnh tên class là Laby rror xception.cs, chọn button Add ể  
máy to 1 class mới. ây là class miêu t 1 loi lỗi xception mà chng trình  
s dùng. Viết code cho class này nh sau :  
namespace BaiTH81. ditLaby {  
class Laby rror xception : xception {  
//chỉ số version  
private const long serialVersionUID = 1L;  
public Laby rror xception(String message)  
: base(message)  
{
}
}
}
.
Dời chuột về folder ditLaby, ấn phi chuột vào nó ể hiển thị menu lệnh,  
chọn chức nng Add.Class ể hiển thị cửa sổ “Add New Item”, chọn mục  
“Class”, hiệu chỉnh tên class là BeginCellNotNull xception.cs, chọn button  
Add ể máy to 1 class mới. ây là class miêu t 1 loi lỗi xception mà  
chng trình s dùng. Viết code cho class này nh sau :  
namespace BaiTH81. ditLaby {  
class BeginCellNotNull xception : Laby rror xception {  
// chỉ số version  
Trang 8  
private const long serialVersionUID = 1L;  
public BeginCellNotNull xception(String message)  
: base(message)  
{
}
}
}
8. Dời chuột về folder ditLaby, ấn phi chuột vào nó ể hiển thị menu lệnh,  
chọn chức nng Add.Class ể hiển thị cửa sổ “Add New Item”, chọn mục  
“Class”, hiệu chỉnh tên class là LabyFault ntour xception.cs, chọn button Add  
ể máy to 1 class mới. ây là class miêu t 1 loi lỗi xception mà chng  
trình s dùng. Viết code cho class này nh sau :  
namespace BaiTH81. ditLaby {  
class LabyFault ntour xception : Laby rror xception {  
// chỉ số version  
private const long serialVersionUID = 1L;  
public LabyFault ntour xception(String message)  
: base(message)  
{
}
}
}
.
Dời chuột về folder ditLaby, ấn phi chuột vào nó ể hiển thị menu lệnh,  
chọn chức nng Add.Class ể hiển thị cửa sổ “Add New Item”, chọn mục  
“Class”, hiệu chỉnh tên class là LabyItem.cs, chọn button Add ể máy to 1  
class mới. Viết code cho kiểu liệt kê này nh sau :  
namespace BaiTH81. ditLaby {  
enum LabyItem {  
ANY, //cell joker  
NULL, //cell trống  
POINT, //cell iểm  
WALL, //cell tờng không i qua ợc  
A NT //cell chứa ngời i  
}
public enum Direction {  
UP, DOWN, L FT, RI HT, STOP  
}
}
10. Dời chuột về folder ditLaby, ấn phi chuột vào nó ể hiển thị menu lệnh,  
chọn chức nng Add.Class ể hiển thị cửa sổ “Add New Item”, chọn mục  
“Class”, hiệu chỉnh tên class là Laby anel.cs, chọn button Add ể máy to 1  
class mới. Viết code cho class này nh sau :  
...  
using System.Windows.Forms;  
using System.Drawing;  
using System.IO;  
Trang 9  
namespace BaiTH81. ditLaby {  
class LabyPanel : Panel {  
private const int ROWS = 20, COLS = 20;  
private const int CSIZ = 30;  
// Serializable trivia  
private const long serialVersionUID = 1L;  
//ma trận cell của mê cung ang hiệu chỉnh  
private Labyrinth laby;  
private LabyItem[,] Cells;  
private int hcnt, ccnt;  
//loi cell ang chọn  
private LabyItem actionSelected = LabyItem.NULL;  
private Bitmap agentbm, dotbm, spacebm, wallbm;  
protected bool edit_enable = true;  
private MyPoint npos, opos = new MyPoint(1, 1);  
//hàm copy nội dung mê cung  
public void setLaby(Labyrinth laby)  
{
this.laby = laby;  
hcnt = laby.Ysize();  
ccnt = laby.Xsize();  
Cells = new LabyItem[hcnt, ccnt];  
npos = null;  
for (int h = 0; h < hcnt; h++)  
for (int c = 0; c < ccnt; c++)  
{
Cells[h, c] = laby.getContenuCase(h, c);  
if (Cells[h, c] == LabyItem.A NT) npos = new MyPoint(h, c);  
}
//v vị trí mới của agent  
Refresh();  
/*v li vị trí củ của agent trong mê cung  
Rectangle rc = new Rectangle();  
rc.Location = new Point(opos.x * CSIZ , opos.y * CSIZ );  
rc.Size = new Size(CSIZ , CSIZ );  
Invalidate(rc);  
if (npos != null)  
{
opos = npos;  
rc.Location = new Point(opos.x * CSIZ , opos.y * CSIZ );  
rc.Size = new Size(CSIZ , CSIZ );  
Invalidate(rc);  
//ngủ chờ 1s  
//Thread.Sleep( 00);  
}*/  
}
Trang 10  
//hàm cập nhật li mê cung  
public void modifLaby()  
{
for (int h = 0; h < hcnt; h++)  
{
for (int c = 0; c < ccnt; c++)  
{
laby.setContenuCase(h, c, Cells[h, c]);  
}
}
}
public LabyItem ActionSelected  
{
set { actionSelected = value; }  
}
//hàm khởi to  
public LabyPanel(Labyrinth laby)  
{
this.MouseDown += new Mouse ventHandler(Frm_MouseDown);  
//this.Paint += new Paint ventHandler(OnPaint);  
//to ối tợng qun lý assembly  
System.Reflection.Assembly myAssembly =  
System.Reflection.Assembly. et xecutingAssembly();  
//to ối tợng Stream miêu t nh bitmap  
Stream myStream =  
myAssembly. etManifestResourceStream("BaiTH 1.Resources.dot.bmp");  
//to ối tợng nh bitmap cho cell dot  
dotbm = new Bitmap(myStream);  
//to ối tợng nh bitmap cho cell space  
myStream =  
myAssembly. etManifestResourceStream("BaiTH 1.Resources.space.bmp");  
spacebm = new Bitmap(myStream);  
//to ối tợng nh bitmap cho cell space  
myStream =  
myAssembly. etManifestResourceStream("BaiTH 1.Resources.wall.bmp");  
wallbm = new Bitmap(myStream);  
//to ối tợng nh bitmap cho cell space  
myStream =  
myAssembly. etManifestResourceStream("BaiTH 1.Resources.agent.jpg");  
agentbm = new Bitmap(myStream);  
setLaby(laby);  
this.ClientSize = new Size(ccnt * CSIZ , hcnt * CSIZ );  
// v li mê cung  
Refresh();  
Trang 11  
}
//tác vụ v bộ mặt giao diện của Button  
protected override void OnPaint(Paint ventArgs e)  
{
raphics g = e. raphics;  
int h, c;  
for (h = 0; h < hcnt; h++)  
for (c = 0; c < ccnt; c++)  
{
Bitmap bm = null;  
switch (Cells[h, c])  
{
case LabyItem.NULL: bm = spacebm; break;  
case LabyItem.POINT: bm = dotbm; break;  
case LabyItem.WALL: bm = wallbm; break;  
case LabyItem.A NT: bm = agentbm; break;  
}
g.DrawImage(bm, c * CSIZ , h * CSIZ );  
}
}
private void Frm_MouseDown(object sender, Mouse ventArgs e)  
{
if (!edit_enable) return;  
//tính tọa ộ cell mà user vừa chọn  
int c = e.X / CSIZ ;  
int h = e.Y / CSIZ ;  
//thiết lập nội dung cho cell  
Cells[h, c] = actionSelected;  
//v li panel mê cung  
//v li panel mê cung  
Rectangle rc = new Rectangle();  
rc.Location = new Point(c * CSIZ , h * CSIZ );  
rc.Size = new Size(CSIZ , CSIZ );  
Invalidate(rc);  
}
}
}
11. Dời chuột về folder ditLaby, ấn phi chuột vào nó ể hiển thị menu lệnh,  
chọn chức nng Add.Class ể hiển thị cửa sổ “Add New Item”, chọn mục  
“Class”, hiệu chỉnh tên class là Labyrinth.cs, chọn button Add ể máy to 1  
class mới. Viết code cho class này nh sau :  
...  
namespace BaiTH81. ditLaby {  
[Serializable]  
Trang 12  
class Labyrinth {  
//chỉ số version ể phục vụ việc ọc/ghi mê cung  
private const long serialVersionUID = 1L;  
//kích thớc mê cung  
int width, height;  
//ma trận các cell của mê cung  
private LabyItem[,] carte;  
//hàm khởi to mê cung 1 cách ngẫu nhiên  
public Labyrinth(int width, int height)  
{
this.width = width;  
this.height = height;  
carte = new LabyItem[width, height];  
for (int h = 0; h < height; h++)  
{
for (int c = 0; c < width; c++)  
carte[h, c] = LabyItem.WALL;  
/*{  
if (i == 0 || j == 0 || i == width - 1 || j == height - 1)  
carte[i,j] = LabyItem.MUR;  
else  
carte[i,j] = LabyItem.POINT;  
}*/  
}
}
//hàm khởi to mê cung theo nội dung ã có  
private Labyrinth(LabyItem[,] copy)  
{
carte = copy;  
height = copy. etLength(0);  
width = copy. etLength(1);  
}
//hàm tr về ộ rộng  
public int Xsize()  
{
return width;  
}
//hàm tr về ộ cao  
public int Ysize()  
{
return height;  
}
Trang 13  
//hàm tr về cell p  
public LabyItem getContenuCase(MyPoint p)  
{
return getContenuCase(p.y, p.x);  
}
//hàm tr về cell ở vị trí x,y  
public LabyItem getContenuCase(int y, int x)  
{
return carte[y, x];  
}
//hàm thiết lập nội dung của cell p  
public void setContenuCase(MyPoint p, LabyItem element)  
{
setContenuCase(p.y, p.x, element);  
}
//hàm thiết lập nội dung của cell ở vị trí x,y  
public void setContenuCase(int y, int x, LabyItem element)  
{
carte[y, x] = element;  
}
//hàm tính số cell point  
public int getNbPoints()  
{
int nbPoints = 0;  
int h, c;  
//lặp từng hàng  
for (h = 0; h < height; h++)  
{
//lặp từng cột  
for (c = 0; c < width; c++)  
{
if (carte[h, c] == LabyItem.POINT)  
nbPoints++;  
}
}
return nbPoints;  
}
//hàm gii mã mê cung thành chuỗi vn bn  
public override String ToString()  
{
return "Mê cung chứa " + getNbPoints() + " cell Point";  
}
Trang 14  
//kiểm tra xem mê cung ợc tờng bao quanh hết không  
public bool is ntourofWalls()  
{
//duyệt từng hàng  
for (int h = 0; h < height; h++)  
{
if (carte[h, width - 1] != LabyItem.WALL) return false;  
if (carte[h, 0] != LabyItem.WALL) return false;  
}
for (int c = 0; c < width; c++)  
{
if (carte[0, c] != LabyItem.WALL) return false;  
if (carte[height - 1, c] != LabyItem.WALL) return false;  
}
return true;  
}
//hàm bao tờng khép kín cho mê cung  
public void ntourofWalls()  
{
int h, c;  
for (h = 0; h < height; h++)  
{
carte[h, width - 1] = LabyItem.WALL;  
carte[h, 0] = LabyItem.WALL;  
}
for (c = 0; c < width; c++)  
{
carte[0, c] = LabyItem.WALL;  
carte[height - 1, c] = LabyItem.WALL;  
}
}
//hàm nhân bn vô tính ối tợng  
public Labyrinth clone()  
{
LabyItem[,] copy = new LabyItem[height, width];  
for (int h = 0; h < height; h++)  
for (int c = 0; c < width; c++)  
copy[h, c] = carte[h, c];  
return new Labyrinth(copy);  
}
}
}
Trang 15  
12. Dời chuột về folder ditLaby, ấn phi chuột vào nó ể hiển thị menu lệnh,  
chọn chức nng Add.Class ể hiển thị cửa sổ “Add New Item”, chọn mục  
“Class”, hiệu chỉnh tên class là Labyrinth.cs, chọn button Add ể máy to 1  
class mới. Viết code cho class này nh sau :  
...  
using System.IO;  
using System.Runtime.Serialization;  
using System.Runtime.Serialization.Formatters.Binary;  
namespace BaiTH81. ditLaby {  
class LabyrinthLoader {  
//hàm ọc mê cung từ file nhị phân  
public static Labyrinth Load_Labyrinth(String fileName)  
{
//ịnh nghĩa ối tợng FileStream miêu t file chứa dữ liệu ã có  
FileStream fs = new FileStream(fileName, FileMode.Open);  
//to ối tợng BinaryFormatter phục vụ ọc ối tợng  
BinaryFormatter formatter = new BinaryFormatter();  
//gọi tác vụ Deserialize ể ọc ối tợng từ file vào  
try  
{
Labyrinth laby = (Labyrinth)formatter.Deserialize(fs);  
if (!laby.is ntourofWalls()) throw new LabyFault ntour xception("Thiếu tờng bao.");  
if (laby.getContenuCase(1, 1) == LabyItem.WALL) throw new  
BeginCellNotNull xception("Tờng nằm ở vị trí xuất phát.");  
fs.Close();  
return laby;  
}
catch (InvalidCast xception e)  
{
throw new IO xception(  
"File chứa nội dung không hợp lệ : phi là mê cung ã ợc ghi trớc từ máy  
tính", e);  
}
catch (TypeLoad xception e)  
{
throw new IO xception(  
".N T không biết kiểu mê cung", e);  
}
}
//hàm ghi mê cung ra file nhị phân  
public static void Save_Labyrinth(String fileName, Labyrinth maze)  
{
//ịnh nghĩa ối tợng FileStream miêu t file chứa kết qu  
FileStream fs = new FileStream(fileName, FileMode.Create);  
//to ối tợng BinaryFormatter phục vụ ghi ối tợng  
Trang 16  
BinaryFormatter formatter = new BinaryFormatter();  
//gọi tác vụ Serialize của formatter ể ghi ối tợng lên file tng ứng  
formatter.Serialize(fs, maze);  
fs.Close();  
}
//hàm ọc mê cung từ file XML  
public static void chargerLabyrinthe nXML()  
{
throw new xception();  
}
//hàm ghi mê cung ra file XML  
public static void chargerLabyrinthe nXML(String fileName, Labyrinth maze)  
{
// to ối tợng phục vụ ghi file vn bn  
StreamWriter writer = new StreamWriter(fileName, false, ncoding.Unicode);  
writer.WriteLine("<Maze>");  
for (int i = 0; i < maze.Xsize(); i++)  
{
writer.Write("<Row>");  
for (int j = 0; j < maze.Ysize(); j++)  
{
writer.WriteLine(" < lement>" + maze.getContenuCase(i, j)  
+ "</ lement>");  
}
writer.WriteLine("</Row>");  
}
writer.WriteLine("</Maze>");  
writer.Close();  
}
}
}
13. Dời chuột về folder ditLaby, ấn phi chuột vào nó ể hiển thị menu lệnh,  
chọn chức nng Add.Class ể hiển thị cửa sổ “Add New Item”, chọn mục  
“Class”, hiệu chỉnh tên class là My oint.cs, chọn button Add ể máy to 1  
class mới. Viết code cho class này nh sau :  
...  
namespace BaiTH81. ditLaby {  
class MyPoint {  
public int x;  
public int y;  
public MyPoint(int y, int x)  
{
this.x = x;  
this.y = y;  
Trang 17  
}
}
}
14. Ấn phi chuột vào phần tử gốc của cây roject trong cửa sổ Solution xplorer,  
chọn option Add.New Folder ể thêm folder với tên là Resources, ta s dùng  
folder này chứa các file bitmap ợc dùng trong chng trình.  
1 . Ấn phi chuột vào folder Resources, chọn option xisting Items, duyệt chọn 4  
file bitmap son ở bớc 1 ể add chúng vào folder Resources.  
16. Chọn 4 mục vừa add vào folder Resources ể hiển thị cửa sổ thuộc tính của  
chúng, hiệu chỉnh li thuộc tính Build Action về giá trị mới là " mbedded  
Resource".  
1 . Dịch và chy chng trình. Nếu có lỗi thì sửa, nếu hết lỗi thì chng trình s  
chy. Hãy son thử từng mê cung theo sở thích và lu lên file ể dùng li cho  
bài .1.  
pdf 17 trang myanh 21460 Free
Bạn đang xem 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ố 8.1 : Viết chương trình soạn thảo 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