1. Trang chủ
  2. » Công Nghệ Thông Tin

Các mẫu thiết kế hướng ₫ối tượngbai 8 1

17 4 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Các Mẫu Thiết Kế Hướng Đối Tượng Bài 8.1
Trường học Trường Đại Học
Thể loại bài thực hành
Định dạng
Số trang 17
Dung lượng 120,53 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Microsoft Word Bai 8 1 docx 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[.]

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 9.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 9.1, ta s sử dụng thuật toán tiến hóa ã viết ở bài thực hành 5.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 9.1 Chng trình gồm 1 form chứa :

file mê cung và Lu file mê cung

cung theo chuẩn 20 x 20 cell

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

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

chọn icon "Windows Form Application" trong listbox "Templates" bên phi, thiết lập th mục chứa Project trong listbox "Location", nhập tên Project vào

Trang 2

textbox "Name:" (td BaiTH81), click button OK ể to Project theo các thông

số ã khai báo

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

ợ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.GetExecutingAssembly();

//to ối tợng Stream miêu t nh bitmap

Stream myStream =

myAssembly.GetManifestResourceStream("BaiTH91.Resources.dot.bmp");

//to ối tợng nh bitmap cho cell dot

dotbm = newBitmap(myStream);

//to ối tợng nh bitmap cho cell space

myStream =

myAssembly.GetManifestResourceStream("BaiTH91.Resources.space.bmp");

spacebm = newBitmap(myStream);

//to ối tợng nh bitmap cho cell space

myStream =

myAssembly.GetManifestResourceStream("BaiTH91.Resources.wall.bmp");

wallbm = newBitmap(myStream);

this.ClientSize = newSize(COLS * CSIZE+300,ROWS * CSIZE);

this.MouseDown += newMouseEventHandler(Frm_MouseDown);

//tiêu ề form

this.Text = "Laby Builder";

//to mê cung

laby = newLabyrinth(ROWS, COLS);

//to Panel và menu

CreateCenterPanel();

CreateMenus();

//ịnh nghĩa các hằng cần dùng

privateconstlong serialVersionUID = 1L;

privateconstString SER_EXPORT_MENU = "Save labyrinth";

privateconstString SER_IMPORT_MENU = "Load labyrinth";

privateconstint ROWS = 20, COLS = 20;

privateconstint CSIZE = 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;

privateint xl, yl;

//hàm to menu

privatevoid CreateMenus()

{

//to 2 option phục vụ thực hiện 2 tác vụ Export/Import mê cung

mi_export = new MenuItem(SER_EXPORT_MENU, Export_Click);

mi_import = new MenuItem(SER_IMPORT_MENU, 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

protectedoverridevoid OnPaint(PaintEventArgs e)

{

Graphics g = e.Graphics;

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 + CSIZE + 20, yl);

g.DrawImage(wallbm, xl + 2 * (CSIZE + 20), yl);

//lu vị trí các icon mẫu cell

this.xl = xl; this.yl = yl;

yl += 50;

g.DrawString("Mẫu cell ang chọn:", myFont, brush, xl, yl, format1);

yl += 25;

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);

}

privatevoid Frm_MouseDown(object sender, MouseEventArgs 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 + CSIZE) return;

//tính tọa ộ luận lý chuột ợc click

int c = (e.X - xl) / (CSIZE + 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(150, 500);

Invalidate(rc);

}

//hàm xử lý option Export

Trang 5

privatevoid Export_Click(object sender, EventArgs e)

{

exportMazeData();

}

//hàm xử lý option Import

privatevoid Import_Click(object sender, EventArgs e)

{

chargerLabyrinthe();

}

//hàm to Panel chính

privatevoid CreateCenterPanel()

{

centerPanel = new LabyPanel(laby);

Controls.Add(centerPanel);

}

publicstatic DialogResult InputBox(string title, string promptText, refstring 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(9, 20, 372, 13);

textBox.SetBounds(12, 36, 372, 20);

buttonOk.SetBounds(228, 72, 75, 23);

buttonCancel.SetBounds(309, 72, 75, 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(396, 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

publicvoid 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

publicvoid 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 (IOException e)

{

MessageBox.Show("Không ọc ợc file " + dlg.FileName);

return;

}

catch (LabyFaultEntourException e)

{

laby.EntourofWalls();

}

catch (BeginCellNotNullException e)

{

laby.setContenuCase(1, 1, LabyItem.NULL);

Trang 7

}

catch (Exception e)

{

MessageBox.Show("Lỗi cha xác ịnh.");

return;

}

centerPanel.setLaby(laby);

}

//lu mê cung ra file

publicvoid sauverLabyrintheEnXML()

{

centerPanel.modifLaby();

LabyrinthLoader.chargerLabyrintheEnXML("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.EditLaby;

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à EditLaby 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

7 Dời chuột về folder EditLaby, ấ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à LabyErrorException.cs, chọn button Add ể máy to 1 class mới ây là class miêu t 1 loi lỗi Exception mà chng trình s dùng Viết code cho class này nh sau :

namespace BaiTH81.EditLaby {

classLabyErrorException : Exception {

//chỉ số version

privateconstlong serialVersionUID = 1L;

public LabyErrorException(String message)

: base(message)

{

}

}

}

7 Dời chuột về folder EditLaby, ấ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à BeginCellNotNullException.cs, chọn button Add ể máy to 1 class mới ây là class miêu t 1 loi lỗi Exception mà chng trình s dùng Viết code cho class này nh sau :

namespace BaiTH81.EditLaby {

classBeginCellNotNullException : LabyErrorException {

// chỉ số version

Trang 8

privateconstlong serialVersionUID = 1L;

public BeginCellNotNullException(String message)

: base(message)

{

}

}

8 Dời chuột về folder EditLaby, ấ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à LabyFaultEntourException.cs, chọn button Add

ể máy to 1 class mới ây là class miêu t 1 loi lỗi Exception mà chng trình s dùng Viết code cho class này nh sau :

namespace BaiTH81.EditLaby {

classLabyFaultEntourException : LabyErrorException {

// chỉ số version

privateconstlong serialVersionUID = 1L;

public LabyFaultEntourException(String message)

: base(message)

{

}

}

}

9 Dời chuột về folder EditLaby, ấ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.EditLaby {

enumLabyItem {

ANY, //cell joker

NULL, //cell trống

POINT, //cell iểm

WALL, //cell tờng không i qua ợc

AGENT //cell chứa ngời i

}

publicenumDirection {

UP, DOWN, LEFT, RIGHT, STOP

}

}

10 Dời chuột về folder EditLaby, ấ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à LabyPanel.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.EditLaby {

classLabyPanel : Panel {

privateconstint ROWS = 20, COLS = 20;

privateconstint CSIZE = 30;

// Serializable trivia

privateconstlong serialVersionUID = 1L;

//ma trận cell của mê cung ang hiệu chỉnh

privateLabyrinth laby;

privateLabyItem[,] Cells;

privateint hcnt, ccnt;

//loi cell ang chọn

privateLabyItem actionSelected = LabyItem.NULL;

privateBitmap agentbm, dotbm, spacebm, wallbm;

protectedbool edit_enable = true;

privateMyPoint npos, opos = newMyPoint(1, 1);

//hàm copy nội dung mê cung

publicvoid setLaby(Labyrinth laby)

{

this.laby = laby;

hcnt = laby.Ysize();

ccnt = laby.Xsize();

Cells = newLabyItem[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.AGENT) npos = newMyPoint(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 * CSIZE, opos.y * CSIZE);

rc.Size = new Size(CSIZE, CSIZE);

Invalidate(rc);

if (npos != null)

{

opos = npos;

rc.Location = new Point(opos.x * CSIZE, opos.y * CSIZE);

rc.Size = new Size(CSIZE, CSIZE);

Invalidate(rc);

//ngủ chờ 1s

//Thread.Sleep(500);

}*/

}

Trang 10

//hàm cập nhật li mê cung

publicvoid modifLaby()

{

for (int h = 0; h < hcnt; h++)

{

for (int c = 0; c < ccnt; c++)

{

laby.setContenuCase(h, c, Cells[h, c]);

}

}

}

publicLabyItem ActionSelected

{

set { actionSelected = value; }

}

//hàm khởi to

public LabyPanel(Labyrinth laby)

{

this.MouseDown += newMouseEventHandler(Frm_MouseDown); //this.Paint += new PaintEventHandler(OnPaint);

//to ối tợng qun lý assembly

System.Reflection.Assembly myAssembly =

System.Reflection.Assembly.GetExecutingAssembly();

//to ối tợng Stream miêu t nh bitmap

Stream myStream =

myAssembly.GetManifestResourceStream("BaiTH91.Resources.dot.bmp"); //to ối tợng nh bitmap cho cell dot

dotbm = newBitmap(myStream);

//to ối tợng nh bitmap cho cell space

myStream =

myAssembly.GetManifestResourceStream("BaiTH91.Resources.space.bmp"); spacebm = newBitmap(myStream);

//to ối tợng nh bitmap cho cell space

myStream =

myAssembly.GetManifestResourceStream("BaiTH91.Resources.wall.bmp"); wallbm = newBitmap(myStream);

//to ối tợng nh bitmap cho cell space

myStream =

myAssembly.GetManifestResourceStream("BaiTH91.Resources.agent.jpg"); agentbm = newBitmap(myStream);

setLaby(laby);

this.ClientSize = newSize(ccnt * CSIZE, hcnt * CSIZE);

// v li mê cung

Refresh();

Ngày đăng: 09/04/2023, 06:14

🧩 Sản phẩm bạn có thể quan tâm