- •Введение
- •Список вопросов, рассматриваемых в модуле 1.
- •Продемонстрированные в приложении особенности
- •Пример Mod1Ex4 (Инкапсуляция, обработка ошибок, наследование) Постановка задачи
- •Продемонстрированные в приложении особенности
- •Пример Mod1Ex5 (Полиморфизм)
- •Продемонстрированные в приложении особенности
- •Список вопросов, рассматриваемых в модуле 2.
- •Описание модельных примеров модуля 2. Пример Mod2Ex1 Постановка
- •Листинги примеров Пример Mod1Ex1
- •Пример Mod1Ex2
- •Пример Mod1Ex3
- •Пример Mod1Ex4
- •Пример Mod2Ex1
- •Пример Mod2Ex2
- •Пример Mod2Ex3
Пример Mod2Ex2
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace XOGame
{ enum XOCell{X,O,None}
public partial class Form1 : Form
{
Button[,] field;
XOCell b;//предыдущий игрок-х(true) или о(false)
public Form1()
{ InitializeComponent();
b = XOCell.X;
this.ClientSize = new Size(340, 340);
field = new Button[3, 3];
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3;j++ )
{ field[i, j] = new Button();
field[i, j].Text = "";
field[i, j].Bounds =
new Rectangle(
10 + j * ((ClientSize.Width - 20) / 3),
10 + i * ((ClientSize.Height - 20) / 3),
((ClientSize.Width - 20) / 3),
((ClientSize.Height - 20) / 3)
);
this.Controls.Add(field[i, j]);
field[i, j].Click += Button_Click;
}
}
private void Button_Click(object sender, EventArgs e)
{ if (b == XOCell.X) { ((Button)sender).Text = "O"; b = XOCell.O; }
else { ((Button)sender).Text = "X"; b = XOCell.X; }
((Button)sender).Click -= Button_Click;
//определить результат игры-продолжение,ничья, победа Х, победа О
AnalyzeResult();
}
private void AnalyzeResult()
{ //для доски 3х3 используем простой исчерпывающий анализ
//все горизонтали
TestLine(field[0, 0], field[0, 1], field[0, 2]);
TestLine(field[1, 0], field[1, 1], field[1, 2]);
TestLine(field[2, 0], field[2, 1], field[2, 2]);
//все вертикали
TestLine(field[0, 0], field[1, 0], field[2, 0]);
TestLine(field[0, 1], field[1, 1], field[2, 1]);
TestLine(field[0, 2], field[2, 1], field[2, 2]);
//диагонали
TestLine(field[0, 0], field[1, 1], field[2, 2]);
TestLine(field[0, 2], field[1, 1], field[2, 0]);
}
//проверка одной линии
private void TestLine(Button b1, Button b2, Button b3)
{ if ((b1.Text == b2.Text) && (b1.Text == b3.Text))
{ if (b1.Text != "")
{ this.Text = "победил " + b1.Text;
this.BlockAllField();
}
}
}
//блокировка всех кнопок
private void BlockAllField()
{ for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
{
field[i, j].Click -= Button_Click;
}
}
}
}
Пример Mod2Ex3
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WindowsFormsApplication1
{
[Serializable]
class Book
{
private string title;
private int count;
public Book(string title, int count)
{ this.title = title;
if (count>0) this.count = count;
else throw new Exception("Количество экземпляров должно быть положительным!");
}
public Book(string title)
{ this.title = title;
this.count = 1;
}
public int Count { get { return count; } }
public void AddInstance() { count++; }
public void RemoveInstance()
{ if (count >1) count--;
else throw new Exception("Последний экземпляр книги!");
}
public override string ToString()
{ return String.Format("Книга: Название - {0} Экземпляров - {1}", title, count);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WindowsFormsApplication1
{
[Serializable]
class Library
{
private List<Book> books;
public Library()
{
books = new List<Book>();
}
public List<Book> Books { get { return books; } }
public void Add(Book book)
{
if (books.Contains(book)) book.AddInstance();
else books.Add(book);
}
public void Remove(Book book)
{ if (books.Contains(book))
if (book.Count>0) book.RemoveInstance();
else books.Remove(book);
else throw new Exception("Такой книги нет!");
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private Library library;
private string fileName=null;
public Form1()
{
InitializeComponent();
}
private void RefreshLibraryView()
{ lstLibrary.Items.Clear();
foreach(Book book in library.Books)
lstLibrary.Items.Add(book);
}
private void btnAddBook_Click(object sender, EventArgs e)
{ library.Add(new Book(txtBookTitle.Text));
RefreshLibraryView();
}
private void btnOpenLibrary_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.InitialDirectory = Application.StartupPath;
if (ofd.ShowDialog() == DialogResult.OK)
{
BinaryFormatter binFormat = new BinaryFormatter();
fileName = ofd.FileName;
Stream fStream = File.OpenRead(fileName);
library = (Library)binFormat.Deserialize(fStream);
fStream.Close();
}
else
{
library = new Library();
}
this.Activate();
RefreshLibraryView();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
while (fileName == null)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.InitialDirectory = Application.StartupPath;
if (sfd.ShowDialog() == DialogResult.OK)
{
fileName = sfd.FileName;
}
}
BinaryFormatter binFormat = new BinaryFormatter();
Stream fStream =
new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None);
binFormat.Serialize(fStream, library);
fStream.Close();
this.Hide();
}
private void btnAddInstance_Click(object sender, EventArgs e)
{
if (lstLibrary.SelectedItem != null)
{
library.Add((Book)(lstLibrary.SelectedItem));
RefreshLibraryView();
}
}
private void btnAddBook_Click_1(object sender, EventArgs e)
{
library.Add(new Book(txtBookTitle.Text));
RefreshLibraryView();
}
private void btnRemoveInstance_Click(object sender, EventArgs e)
{
if (lstLibrary.SelectedItem != null)
{
try
{
library.Remove((Book)(lstLibrary.SelectedItem));
}
catch
{
}
RefreshLibraryView();
}
}
private void button1_Click(object sender, EventArgs e)
{
if (lstLibrary.SelectedItem != null)
{
library.Add((Book)(lstLibrary.SelectedItem));
RefreshLibraryView();
}
}
}
}
