4. Список литературы

advertisement
Московский городской Дворец детского (юношеского) творчества
Отдел оборонно-массовой работы
Сектор информационных технологий
Лаборатория технических средств обучения
Подготовка практических задач по программе
«Прикладное программирование в С#»
(для 1-го года занятий)
Автор Андреев Д.Р.
Москва
2008
Оглавление:
1. Введение
2. Темы учебного плана и номера задач по этим темам.
3. Практические задачи и листинги.
4. Список литературы.
1. Введение
Целью данной работы была подготовка практических задач для повышения
эффективности обучения по программе «Прикладное программирование в C#» (первого
года занятий).
Работа выполнена на основе собственного опыта работы с учетом опыта работы
других педагогов (Козловой И.Ю., Кондрахина П.М). Были определены наиболее
познавательные, применимые на практике и интересные для учащихся задачи.
Основными причинами написания данной работы являются:
Отсутствие подобного материала
Среда разработки, изучаемая по дано программе, используется сравнительно не
давно, и автору не знакомы наборы задач по данной программе, ориентированные на
обучающихся 13-15 лет.
Более эффективное использование времени преподавателя
Преподавание по программе «Прикладное программирование в С#» 1 года занятий
в лаборатории ТСО проводится таким образом, что одно из двух занятий в неделю
проходит без компьютеров (с использованием проекционного оборудования).
Педагогу, выдавшему листинги программ, рассматриваемых на занятии, почти не
придется писать на доске. Это увеличивает время объяснения материала педагогом и
позволяет ему полностью сосредоточиться на объяснении.
Повышение наглядности материала и возможность немедленного
закрепления его учащимися
В связи с тем, что раз в неделю отсутствует возможность немедленного
закрепления материала на компьютере, показ (раздача) готовых листингов программ
улучшат восприятие новой темы. Кроме этого, многие учащиеся неаккуратно пишут в
тетрадке объемные программы, и уже через неделю не могут разобраться в написанном.
Возможность освоения материала учащимися, пропустившими занятия
Учащийся, пропустивший занятия, имеет возможность выполнения дома
практических задач и проверки своих знаний на основе сравнения своих результатов с
правильными.
Использование работы
Задачи расположены в порядке повышения сложности. Ко многим задачам
имеются усложненные варианты.
В начале занятия педагог выдает листинги программ по изучаемой теме, в конце
занятия - домашнее усложненное задание. На практическом занятии рассматривается
правильность выполнения домашнего задания и различные способы его выполнения,
после чего выдается листинг с наиболее рациональным способом выполнения задачи,
даются еще более усложненные задачи на данную тему. Такая схема может
использоваться на основе разработанного методического материала.
Подготовлена «Таблица тем учебного плана и номеров задач по этим темам», по
которой педагог может легко найти задачи по нужной теме и распечатать их (показать на
проекторе, выдать в электронном виде). Приводятся задачи по всем темам программы.
Также подготовлено приложение, в котором находятся листинги базовых задач (в
таблице такие задачи выделены жирным шрифтом).
Данный материал предназначен для педагога, преподающего основы языка «C#», и
учащихся, занимающихся в группе и/или самообразованием.
2. Темы учебного плана и номера задач по этим темам.
Колич Постановка задачи
ество
1. Переменные,
3
1.1. Hellow World
преобразование
1.2. Конвертер валют
типов данных.
1.3. Калькулятор
Тема
2. Условные
операторы
4
2.1. Калькулятор (с обработкой ошибок)
2.2. Нахождение наибольшего из 3-х чисел
2.3. Секундомер
2.4. Таймер
3. Циклы
6
4. Массивы
3
5. Закрепление
пройденных тем
6
6. Глобальные
переменные
7. Функции и
классы
2
8. Работа с
файлами
3
9. Закрепление
пройденных тем
5
3.1. Вычисление факториала
3.2. Пошаговый вывод цикла for
3.3. Генерирование листбокса случайных чисел
3.4. Проверка является ли число простым
3.5. Кафе
3.6. Сумма первых N
4.1. Средняя температура
4.2. Нахождение суммы элементов
4.3. Сортировка массива (2 метода)
5.1. Будильник
5.2. Бегущая срока
5.3. Системы предварительной продажи билетов
5.4. Работа с матрицами
5.5. Тестирование
5.6. Форма ввода пароля
6.1. Угадай число
6.2. Растояниемер
7.1. Банк и банкомат
7.2. Здания
7.3. Поле боя
7.4. Работа с дробями
8.1. Угадай число (с сохранением статистики)
8.2. Удаление повторяющихся строк
8.3. Просмотр изображений
9.1. Игра собери картинку
9.2. Игра танчики
9.3. Текстовый редактор
9.4. Браузер картинок
9.5. Игра сапер
4
3. Практические задачи и листинги.
в электронном виде размещены на сервере подразделения. В печатном виде
занимают 22 страницы.
3. Практические задачи и листинги.
1.1. Hellow World
Написать программу для вывода сообщения “Hellow World” или любого другого на выбор
при помощи элементов Label, TextBox и Message Box
1.2. Конвертор валют
Написать программы для перевода из одной валюты в другую. Предусмотреть
возможность ручного ввода курса.
Усложнение: Добавить несколько валют и возможность выбора.
1.3. Калькулятор
Написать программу для выполнения простейших арифметических операций (сложение,
вычитание, умножение, деление).
Усложнение: Добавить дополнительные операции: нахождение квадратного корня,
деление по модулю.
2.1. Калькулятор (с обработкой ошибок)
Добавить в программу калькулятор обработку деления на ноль и ввод “неправильных”
значений.
2.2. Нахождение наибольшего из 3-х чисел
Написать программу для нахождения наибольшего из 3-х чисел
Усложнение: Наибольшее из 4-х чисел.
2.3. Секундомер
Написать секундомер, выводящий секунды, минуты, часы.
Усложнение: Добавить возможность сохранять промежуточные секунды.
2.4. Таймер
Написать таймер выводящий секунды, минуты. По окончанию отсчета выдать звуковой
сигнал.
Усложнение: Добавить возможность добавления нескольких отсчетов.
3.1. Вычисление факториала
Вычислить факториал указанного числа
3.2. Пошаговый вывод цикла for
Вывести работу цикла for на каждом шаге
3.3. Генерирование листбокса случайных чисел
Сгенерировать указанное количество случайных чисел.
3.4. Проверка является ли число простым
Проверить является ли введенное пользователем число простым
3.5. Кафе
Написать программу для вычисления стоимости заказа в зависимости от выбранных
элементов меню.
Усложнение: Добавить возможность скидок при достижении определенный стоимости.
3.6. Сумма первых N
Написать программу для вычисления первых N натуральных чисел.
Усложнение: добавить возможность вычисления, начиная с указанного числа.
4.1. Средняя температура
Вычислить среднюю температуру из набора, введенного пользователем.
Усложнение: Добавить возможность ввода температуры за разные месяцы и
независимость её подсчета.
4.2. Нахождение суммы элементов
Сгенерировать массив случайных чисел заданного пользователем размера. Вычислить
сумму элементов и среднее арифметическое
Усложнение: Добавить возможность изменения размера массива без потери значений.
4.3. Сортировка массива методом пузырька
Отсортировать массив методом пузырька.
Алгоритм состоит в повторяющихся проходах по сортируемому массиву. За каждый
проход элементы последовательно сравниваются попарно и, если порядок в паре
неверный, выполняется обмен элементов. Проходы по массиву повторяются до тех пор,
пока на очередном проходе не окажется, что обмены больше не нужны, что означает —
массив отсортирован. При проходе алгоритма, элемент, стоящий не на своём месте,
«всплывает» до нужной позиции как пузырёк в воде, отсюда и название алгоритма.
4.3. Сортировка массива сортировкой выбором
Шаги алгоритма:
1. находим минимальное значение в текущем списке
2. производим обмен этого значения со значением на первой позиции
3. теперь сортируем хвост списка, исключив из рассмотрения уже отсортированный
первый элемент
Если вы захотите сами изобрести алгоритм сортировки, то вполне вероятно, что вы
напишете алгоритм подобный сортировке методом вставок, потому что он, по-видимому,
наиболее интуитивно понятный и легко описываемый.
5.1. Будильник
Написать программу — будильник, для вывода звукового сигнала в указанное время.
5.2. Бегущая срока
Написать бегущую строку. Предусмотреть кругового движения строки.
Усложнение: Добавить возможность бегущих картинок
5.3. Системы предварительной продажи билетов
Написать систему с возможностью бронирования мест в зале, разбронирования и вывода в
любом виде положения по залу.
Усложнение: Добавить возможность работы с несколькими залами.
5.4. Работа с матрицами
Написать программу для ввода матрицы заданного размера, вывода в любом виде
матрицы, вычисления определителя, суммы элементов, транспонирования матрицы.
5.5. Тестирование
Написать программу для вывода нескольких, заранее заданных вопросов. Использовать
несколько форм. По результатам вывести итоговый бал.
6.1. Угадай число
Написать игру угадай число. Пользователь должен угадать заранее сгенерированное
число. В случае ошибки выдать подсказку (Больше, меньше).
6.2. Растояниемер
Измерить расстояние между двумя точками на форме.
7.1. Банк и банкомат
Написать класс реализующий счет пользователя в банке. Реализовать функции положить,
снять деньги со счета, а также проверить баланс.
Написать программу «банкомат» для работы со счетом пользователя
Усложнение: Добавить возможность работы с несколькими счетами.
7.2. Здания
Реализовать класс для описания здания (высота, этажность, количество квартир,
подъездов). Добавить функции вычисления высоты этажа, количества квартир в подъезде
и .т.д.
7.3. Поле боя
Реализовать клас «боевая техника», учитывающий её основные характеристики (броня,
скорость, огневая мощь), а также с функциями передвижения и огня.
7.4. Работа с дробями
Написать класс для работы с дробями с рациональными дробями. Предусмотреть
возможность сложения, вычитания, умножения, деления, сравнения дробей, без
округления.
8.1. Угадай число (с сохранением статистики)
Добавить в игру «Угадай число» возможнось хранения статистики (количество игр,
количестве ходов на игру)
Усложнение: Добавить MDI-интерфейс (возможность работы одновременно с
несколькими документами)
8.2. Удаление повторяющихся строк
Написать программу для удаления повторяющихся строк из текстового файла.
8.3. Просмотр изображений
Написать программу для просмотра картинки из файла. Реализовать «правильное»
масштабирование.
Усложнение: Добавить возможность просмотра всех картинок из указанной папки.
9.1. Игра собери картинку
Написать игру для сбора картинки разбитую на блоки, путем замены двух соседних
9.2. Игра танчики
Используя программу «Поле боя» сделать многопользовательскую игру.
9.3. Текстовый редактор
Написать простейший текстовый редактор, с возможность сохранения и загрузки файла.
9.4. Браузер картинок
Расширить программу «просмотр картинки» функциями:
1) открытие папки (папок) и просмотр последовательно картинок в них
2) Листание картинок и слайд шоу
3) Управление с клавиатуры
9.5. Игра сапер
Написать игру – аналог сапера Windows
4. Список литературы
1. Г. Шилдт. Полный справочник по C#. Издательство: Вильямс, 2007 г.
Твердый переплет, 704 стр.
2. Н. Культин. C# в задачах и примерах. Издательство: БХВ-Петербург, 2007 г.
Мягкая обложка, 240 стр.
Приложение 1. Листинги программ (57 страниц).
Приложение 1. Листинги программ.
1.2. Конвертор валют
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
namespace converter
{
/// <summary>
/// Summary description for WinForm.
/// </summary>
public class WinForm : System.Windows.Forms.Form
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.TextBox textBox2;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
public WinForm()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.textBox1 = new System.Windows.Forms.TextBox();
this.textBox2 = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// label1
//
this.label1.Font = new System.Drawing.Font("Tahoma", 8.25F,
System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.label1.Location = new System.Drawing.Point(16, 8);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(176, 32);
this.label1.TabIndex = 0;
this.label1.Text = "Введите курс, цену в долларах и щелкните на
кнопке Пересчет";
//
// label2
//
this.label2.Location = new System.Drawing.Point(16, 40);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(100, 24);
this.label2.TabIndex = 1;
this.label2.Text = "Цена (USD)";
//
// label3
//
this.label3.Location = new System.Drawing.Point(16, 64);
this.label3.Name = "label3";
this.label3.TabIndex = 2;
this.label3.Text = "Курс (RUR/USD)";
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(112, 40);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(80, 21);
this.textBox1.TabIndex = 3;
this.textBox1.Text = "";
this.textBox1.KeyPress += new
System.Windows.Forms.KeyPressEventHandler(this.textBox1_KeyPress);
//
// textBox2
//
this.textBox2.Location = new System.Drawing.Point(112, 64);
this.textBox2.Name = "textBox2";
this.textBox2.Size = new System.Drawing.Size(80, 21);
this.textBox2.TabIndex = 4;
this.textBox2.Text = "";
this.textBox2.KeyPress += new
System.Windows.Forms.KeyPressEventHandler(this.textBox2_KeyPress);
//
// label4
//
this.label4.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.label4.Location = new System.Drawing.Point(16, 96);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(176, 48);
this.label4.TabIndex = 5;
//
// button1
//
this.button1.Location = new System.Drawing.Point(16, 152);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(80, 23);
this.button1.TabIndex = 6;
this.button1.Text = "Пересчет";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// button2
//
this.button2.Location = new System.Drawing.Point(112, 152);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(80, 23);
this.button2.TabIndex = 7;
this.button2.Text = "Завершить";
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// WinForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 14);
this.ClientSize = new System.Drawing.Size(208, 187);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Controls.Add(this.label4);
this.Controls.Add(this.textBox2);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Font = new System.Drawing.Font("Tahoma", 8.25F,
System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.MaximizeBox = false;
this.Name = "WinForm";
this.Text = "Конвертер";
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new WinForm());
}
// нажатие клавиши в поле Цена
private void textBox1_KeyPress(object sender,
System.Windows.Forms.KeyPressEventArgs e)
{
if (!Char.IsDigit(e.KeyChar) &&
!(Char.IsControl(e.KeyChar))) {
if (!((e.KeyChar.ToString() == ",") &&
(textBox1.Text.IndexOf(",") == -1)))
e.Handled = true;
}
}
// нажатие клавиши в поле Курс
private void textBox2_KeyPress(object sender,
System.Windows.Forms.KeyPressEventArgs e)
{
if (!Char.IsDigit(e.KeyChar) &&
!(Char.IsControl(e.KeyChar))) {
if (!((e.KeyChar.ToString() == ",") &&
(textBox2.Text.IndexOf(",") == -1)))
e.Handled = true;
}
}
// щелчок на кнопке Пересчет
private void button1_Click(object sender, System.EventArgs e)
{
double k;
// курс ( отношение рубля к доллару )
double usd;
// цена в долларах
double rub;
// цена в рублях
label4.Text = "";
// конструкция try { ... } catch { ... }
// позволяет отлавливать возникающие ошибки
try{
// исходные данные
usd = System.Convert.ToDouble(textBox1.Text);
k = System.Convert.ToDouble(textBox2.Text);
// пересчет цены из долларов в рубли
rub = usd * k;
// вывод результата
label4.Text = usd.ToString("N") +
" USD = " + rub.ToString("C");
}
catch{
if ((textBox1.Text == "") || (textBox2.Text == "")){
MessageBox.Show("Ошибка исходных данных.\n" +
"Необходимо ввести данные в оба поля.",
"Конвертер", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
else
MessageBox.Show("Ошибка исходных данных.\n" +
"Неверный формат данных водном из полей.",
"Конвертер", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
// щелчок на кнопке Завершить
private void button2_Click(object sender, System.EventArgs e)
{
this.Close();
}
}
}
1.3. Калькулятор (с обработкой ошибок)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace Calc
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnPlus_Click(object sender, EventArgs e)
{
double a, b, c;
a = Convert.ToDouble(txtN1.Text);
b = Convert.ToDouble(txtN2.Text);
c = a + b;
lblRes.Text= c.ToString();
}
private void btmMin_Click(object sender, EventArgs e)
{
double a, b, c;
a = Convert.ToDouble(txtN1.Text);
b = Convert.ToDouble(txtN2.Text);
c = a - b;
lblRes.Text= c.ToString();
}
private void btnUms_Click(object sender, EventArgs e)
{
double a, b, c;
a = Double.Parse(txtN1.Text);
b = Double.Parse(txtN2.Text);
c = a * b;
lblRes.Text= c.ToString();
}
private void btnDel_Click(object sender, EventArgs e)
{
double a, b, c;
a = Double.Parse(txtN1.Text);
b = Double.Parse(txtN2.Text);
if (b == 0)
{
lblRes.Text = "Делить на 0 нельзя!";
}
else
{
c = a / b;
lblRes.Text= c.ToString();
}
}
}
}
2.3. Секундомер
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
namespace beeper
{
/// <summary>
/// Summary description for WinForm.
/// </summary>
public class WinForm : System.Windows.Forms.Form
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components;
private System.Windows.Forms.NumericUpDown numericUpDown1;
private System.Windows.Forms.NumericUpDown numericUpDown2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Label label3;
private DateTime t1, // точка отсчета времени
t2;
// время срабатывания таймера
// таймер
private System.Windows.Forms.Timer timer1;
// конструктор формы
public WinForm()
{
InitializeComponent();
// параметры компонентов numericUpDown
numericUpDown1.Maximum = 59;
numericUpDown1.Minimum = 0;
numericUpDown2.Maximum = 59;
numericUpDown2.Minimum = 0;
// кнопка Пуск/Стоп не доступна
button1.Enabled = false;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.numericUpDown1 = new
System.Windows.Forms.NumericUpDown();
this.numericUpDown2 = new
System.Windows.Forms.NumericUpDown();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.button1 = new System.Windows.Forms.Button();
this.label3 = new System.Windows.Forms.Label();
this.timer1 = new System.Windows.Forms.Timer(this.components);
((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDown2)).BeginInit();
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// numericUpDown1
//
this.numericUpDown1.Location = new System.Drawing.Point(16, 32);
this.numericUpDown1.Name = "numericUpDown1";
this.numericUpDown1.Size = new System.Drawing.Size(40, 20);
this.numericUpDown1.TabIndex = 0;
this.numericUpDown1.ValueChanged += new
System.EventHandler(this.numericUpDown1_ValueChanged);
//
// numericUpDown2
//
this.numericUpDown2.Location = new System.Drawing.Point(104, 32);
this.numericUpDown2.Name = "numericUpDown2";
this.numericUpDown2.Size = new System.Drawing.Size(40, 20);
this.numericUpDown2.TabIndex = 1;
this.numericUpDown2.ValueChanged += new
System.EventHandler(this.numericUpDown1_ValueChanged);
//
// label1
//
this.label1.Location = new System.Drawing.Point(56, 32);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(40, 23);
this.label1.TabIndex = 2;
this.label1.Text = "минут";
//
// label2
//
this.label2.Location = new System.Drawing.Point(144, 32);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(48, 23);
this.label2.TabIndex = 3;
this.label2.Text = "секунд";
//
// groupBox1
//
this.groupBox1.Controls.Add(this.numericUpDown2);
this.groupBox1.Controls.Add(this.label2);
this.groupBox1.Controls.Add(this.label1);
this.groupBox1.Controls.Add(this.numericUpDown1);
this.groupBox1.Location = new System.Drawing.Point(8, 40);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(200, 76);
this.groupBox1.TabIndex = 4;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Интервал";
//
// button1
//
this.button1.Location = new System.Drawing.Point(8, 124);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(200, 23);
this.button1.TabIndex = 5;
this.button1.Text = "Пуск";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// label3
//
this.label3.Font = new System.Drawing.Font("Tahoma", 12F,
System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.label3.Location = new System.Drawing.Point(8, 8);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(200, 32);
this.label3.TabIndex = 6;
this.label3.Text = "00:00";
this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// timer1
//
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
//
// WinForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(218, 157);
this.Controls.Add(this.label3);
this.Controls.Add(this.button1);
this.Controls.Add(this.groupBox1);
this.FormBorderStyle =
System.Windows.Forms.FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
this.Name = "WinForm";
this.Text = "Таймер";
((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDown2)).EndInit();
this.groupBox1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new WinForm());
}
// изменилось значение поля компонента
// numericUpDown1 или numericUpDown2
private void numericUpDown1_ValueChanged(object sender, System.EventArgs
e)
{
if ((numericUpDown1.Value == 0) &&
(numericUpDown2.Value == 0))
button1.Enabled = false;
else
button1.Enabled = true;
}
// щелчок на кнопке Пуск/Стоп
private void button1_Click(object sender, System.EventArgs e)
{
if (!timer1.Enabled) {
// при помощи t1 инициализируем переменную типа
// DateTime, содержащую время 00:00:00 (ч:м:с)
// t2 = t1 + установленное значение таймера
t1 = new
DateTime(DateTime.Now.Year,DateTime.Now.Month,DateTime.Now.Day);
t2 = t1.AddMinutes((double)numericUpDown1.Value);
t2 = t2.AddSeconds((double)numericUpDown2.Value);
groupBox1.Enabled = false;
button1.Text = "Стоп";
if (t2.Minute < 9)
label3.Text = "0" + t2.Minute.ToString() + ":";
else
label3.Text = t2.Minute.ToString() + ":";
if (t2.Second < 9)
label3.Text += "0" + t2.Second.ToString();
else
label3.Text += t2.Second.ToString();
// сигнал от таймера поступает каждую секунду
timer1.Interval = 1000;
// пуск таймера
timer1.Enabled = true;
}
else {
// таймер работает, останавливаем
timer1.Enabled = false;
button1.Text = "Пуск";
groupBox1.Enabled = true;
numericUpDown1.Value = t2.Minute;
numericUpDown2.Value = t2.Second;
}
}
// обработка события таймера
private void timer1_Tick(object sender, System.EventArgs e)
{
t2 = t2.AddSeconds(-1);
if (t2.Minute < 9)
label3.Text = "0" + t2.Minute.ToString() + ":";
else
label3.Text = t2.Minute.ToString() + ":";
if (t2.Second < 9)
label3.Text += "0" + t2.Second.ToString();
else
label3.Text += t2.Second.ToString();
if (Equals(t1,t2)) {
timer1.Enabled = false;
MessageBox.Show(
"Заданный интервал времени истек.", "Таймер",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
button1.Text = "Пуск";
groupBox1.Enabled = true;
numericUpDown1.Value = 0;
numericUpDown2.Value = 0;
}
}
}
}
2.4. Таймер
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
namespace beeper
{
/// <summary>
/// Summary description for WinForm.
/// </summary>
public class WinForm : System.Windows.Forms.Form
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components;
private System.Windows.Forms.NumericUpDown numericUpDown1;
private System.Windows.Forms.NumericUpDown numericUpDown2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Label label3;
private DateTime t1, // точка отсчета времени
t2;
// время срабатывания таймера
// таймер
private System.Windows.Forms.Timer timer1;
// конструктор формы
public WinForm()
{
InitializeComponent();
// параметры компонентов numericUpDown
numericUpDown1.Maximum = 59;
numericUpDown1.Minimum = 0;
numericUpDown2.Maximum = 59;
numericUpDown2.Minimum = 0;
// кнопка Пуск/Стоп не доступна
button1.Enabled = false;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.numericUpDown1 = new
System.Windows.Forms.NumericUpDown();
this.numericUpDown2 = new
System.Windows.Forms.NumericUpDown();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.button1 = new System.Windows.Forms.Button();
this.label3 = new System.Windows.Forms.Label();
this.timer1 = new System.Windows.Forms.Timer(this.components);
((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDown2)).BeginInit();
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// numericUpDown1
//
this.numericUpDown1.Location = new System.Drawing.Point(16, 32);
this.numericUpDown1.Name = "numericUpDown1";
this.numericUpDown1.Size = new System.Drawing.Size(40, 20);
this.numericUpDown1.TabIndex = 0;
this.numericUpDown1.ValueChanged += new
System.EventHandler(this.numericUpDown1_ValueChanged);
//
// numericUpDown2
//
this.numericUpDown2.Location = new System.Drawing.Point(104, 32);
this.numericUpDown2.Name = "numericUpDown2";
this.numericUpDown2.Size = new System.Drawing.Size(40, 20);
this.numericUpDown2.TabIndex = 1;
this.numericUpDown2.ValueChanged += new
System.EventHandler(this.numericUpDown1_ValueChanged);
//
// label1
//
this.label1.Location = new System.Drawing.Point(56, 32);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(40, 23);
this.label1.TabIndex = 2;
this.label1.Text = "минут";
//
// label2
//
this.label2.Location = new System.Drawing.Point(144, 32);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(48, 23);
this.label2.TabIndex = 3;
this.label2.Text = "секунд";
//
// groupBox1
//
this.groupBox1.Controls.Add(this.numericUpDown2);
this.groupBox1.Controls.Add(this.label2);
this.groupBox1.Controls.Add(this.label1);
this.groupBox1.Controls.Add(this.numericUpDown1);
this.groupBox1.Location = new System.Drawing.Point(8, 40);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(200, 76);
this.groupBox1.TabIndex = 4;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Интервал";
//
// button1
//
this.button1.Location = new System.Drawing.Point(8, 124);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(200, 23);
this.button1.TabIndex = 5;
this.button1.Text = "Пуск";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// label3
//
this.label3.Font = new System.Drawing.Font("Tahoma", 12F,
System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.label3.Location = new System.Drawing.Point(8, 8);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(200, 32);
this.label3.TabIndex = 6;
this.label3.Text = "00:00";
this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// timer1
//
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
//
// WinForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(218, 157);
this.Controls.Add(this.label3);
this.Controls.Add(this.button1);
this.Controls.Add(this.groupBox1);
this.FormBorderStyle =
System.Windows.Forms.FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
this.Name = "WinForm";
this.Text = "Таймер";
((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDown2)).EndInit();
this.groupBox1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new WinForm());
}
// изменилось значение поля компонента
// numericUpDown1 или numericUpDown2
private void numericUpDown1_ValueChanged(object sender, System.EventArgs
e)
{
if ((numericUpDown1.Value == 0) &&
(numericUpDown2.Value == 0))
button1.Enabled = false;
else
button1.Enabled = true;
}
// щелчок на кнопке Пуск/Стоп
private void button1_Click(object sender, System.EventArgs e)
{
if (!timer1.Enabled) {
// при помощи t1 инициализируем переменную типа
// DateTime, содержащую время 00:00:00 (ч:м:с)
// t2 = t1 + установленное значение таймера
t1 = new
DateTime(DateTime.Now.Year,DateTime.Now.Month,DateTime.Now.Day);
t2 = t1.AddMinutes((double)numericUpDown1.Value);
t2 = t2.AddSeconds((double)numericUpDown2.Value);
groupBox1.Enabled = false;
button1.Text = "Стоп";
if (t2.Minute < 9)
label3.Text = "0" + t2.Minute.ToString() + ":";
else
label3.Text = t2.Minute.ToString() + ":";
if (t2.Second < 9)
label3.Text += "0" + t2.Second.ToString();
else
label3.Text += t2.Second.ToString();
// сигнал от таймера поступает каждую секунду
timer1.Interval = 1000;
// пуск таймера
timer1.Enabled = true;
}
else {
// таймер работает, останавливаем
timer1.Enabled = false;
button1.Text = "Пуск";
groupBox1.Enabled = true;
numericUpDown1.Value = t2.Minute;
numericUpDown2.Value = t2.Second;
}
}
// обработка события таймера
private void timer1_Tick(object sender, System.EventArgs e)
{
t2 = t2.AddSeconds(-1);
if (t2.Minute < 9)
label3.Text = "0" + t2.Minute.ToString() + ":";
else
label3.Text = t2.Minute.ToString() + ":";
if (t2.Second < 9)
label3.Text += "0" + t2.Second.ToString();
else
label3.Text += t2.Second.ToString();
if (Equals(t1,t2)) {
timer1.Enabled = false;
MessageBox.Show(
"Заданный интервал времени истек.", "Таймер",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
button1.Text = "Пуск";
groupBox1.Enabled = true;
numericUpDown1.Value = 0;
numericUpDown2.Value = 0;
}
}
}
}
3.1.Вычисление факториала
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace Ugaday
{
public partial class Form1 : Form
{
int a;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Random rand = new Random();
a = rand.Next(0, 100);
}
private void button1_Click(object sender, EventArgs e)
{
int b;
b = (int)numericUpDown1.Value;
if (a > b)
{
MessageBox.Show("Не айс! Больше");
}
else if (a < b)
{
MessageBox.Show("Не айс! Меньше");
}
else
{
MessageBox.Show("Жжошь! Давай ещё!");
Random rand = new Random();
a = rand.Next(0, 100);
}
}
}
}
3.5. Кафе
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
namespace cafe
{
/// <summary>
/// Summary description for WinForm.
/// </summary>
public class WinForm : System.Windows.Forms.Form
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private System.Windows.Forms.CheckBox checkBox1;
private System.Windows.Forms.CheckBox checkBox2;
private System.Windows.Forms.CheckBox checkBox3;
private System.Windows.Forms.CheckBox checkBox4;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Button button1;
private double summ; // стоимость заказа
public WinForm()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.checkBox1 = new System.Windows.Forms.CheckBox();
this.checkBox2 = new System.Windows.Forms.CheckBox();
this.checkBox3 = new System.Windows.Forms.CheckBox();
this.checkBox4 = new System.Windows.Forms.CheckBox();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// checkBox1
//
this.checkBox1.Location = new System.Drawing.Point(16, 48);
this.checkBox1.Name = "checkBox1";
this.checkBox1.TabIndex = 0;
this.checkBox1.Text = "Сэндвич";
this.checkBox1.CheckedChanged += new
System.EventHandler(this.checkBox1_CheckedChanged);
//
// checkBox2
//
this.checkBox2.Location = new System.Drawing.Point(16, 72);
this.checkBox2.Name = "checkBox2";
this.checkBox2.TabIndex = 1;
this.checkBox2.Text = "Картошка";
this.checkBox2.CheckedChanged += new
System.EventHandler(this.checkBox2_CheckedChanged);
//
// checkBox3
//
this.checkBox3.Location = new System.Drawing.Point(16, 96);
this.checkBox3.Name = "checkBox3";
this.checkBox3.TabIndex = 2;
this.checkBox3.Text = "Соус";
this.checkBox3.CheckedChanged += new
System.EventHandler(this.checkBox3_CheckedChanged);
//
// checkBox4
//
this.checkBox4.Location = new System.Drawing.Point(16, 120);
this.checkBox4.Name = "checkBox4";
this.checkBox4.TabIndex = 3;
this.checkBox4.Text = "Coca-Cola";
this.checkBox4.CheckedChanged += new
System.EventHandler(this.checkBox4_CheckedChanged);
//
// label1
//
this.label1.Location = new System.Drawing.Point(128, 16);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(88, 23);
this.label1.TabIndex = 4;
this.label1.Text = "label1";
this.label1.Paint += new
System.Windows.Forms.PaintEventHandler(this.label1_Paint);
//
// label2
//
this.label2.Location = new System.Drawing.Point(16, 16);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(104, 23);
this.label2.TabIndex = 5;
this.label2.Text = "Стоимость заказа:";
//
// button1
//
this.button1.Location = new System.Drawing.Point(16, 152);
this.button1.Name = "button1";
this.button1.TabIndex = 6;
this.button1.Text = "Ok";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// WinForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(232, 187);
this.Controls.Add(this.button1);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.checkBox4);
this.Controls.Add(this.checkBox3);
this.Controls.Add(this.checkBox2);
this.Controls.Add(this.checkBox1);
this.MaximizeBox = false;
this.Name = "WinForm";
this.Text = "Кафе";
this.Load += new System.EventHandler(this.WinForm_Load);
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new WinForm());
}
// загрузка формы
private void WinForm_Load(object sender, System.EventArgs e)
{
// сделать недоступным переключатель Соус
checkBox3.Enabled = false;
}
// щелчок на переключателе Сэндвич
private void checkBox1_CheckedChanged(object sender, System.EventArgs e)
{
if (checkBox1.Checked) summ += 54.00;
else summ -= 54.00;
label1.Refresh();
}
// щелчок на переключателе Картошка
private void checkBox2_CheckedChanged(object sender, System.EventArgs e)
{
if (checkBox2.Checked) {
summ += 24.50;
// сделать доступным переключатель Соус
if (!checkBox3.Enabled) checkBox3.Enabled = true;
}
else{
summ -= 24.50;
// сбросить переключатель Соус
if (checkBox3.Checked) checkBox3.Checked = false;
// сделать его недоступным
checkBox3.Enabled = false;
}
label1.Refresh();
}
// щелчок на переключателе Соус
private void checkBox3_CheckedChanged(object sender, System.EventArgs e)
{
if (checkBox3.Checked) summ += 10.50;
else summ -= 10.50;
label1.Refresh();
}
// щелчок на переключателе Coca-Cola
private void checkBox4_CheckedChanged(object sender, System.EventArgs e)
{
if (checkBox4.Checked) summ += 18.00;
else summ -= 18.00;
label1.Refresh();
}
// обработка события Paint компонента label1
private void label1_Paint(object sender, System.Windows.Forms.PaintEventArgs
e)
{
// вывести в поле компонента сумму заказа
label1.Text = summ.ToString("C");
}
// щелчок на кнопке Ok
private void button1_Click(object sender, System.EventArgs e)
{
if (checkBox1.Checked && checkBox2.Checked &&
checkBox3.Checked && checkBox4.Checked) {
// пользователь заказал полный набор,
// предоставляется скидка 10%
MessageBox.Show("Вам предоставляется скидка 10%\n" +
"Стоимость заказа: " + (summ*0.9).ToString("C"),
"Кафе");
}
else {
if (checkBox1.Checked || checkBox2.Checked ||
checkBox3.Checked || checkBox4.Checked)
MessageBox.Show("Стоимость заказа: " +
summ.ToString("C"),"Кафе");
else
MessageBox.Show("Вы ничего не заказали!",
"Кафе");
}
}
}
}
3.1 Средняя температура
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
namespace stop_watch
{
/// <summary>
/// Summary description for WinForm.
/// </summary>
public class WinForm : System.Windows.Forms.Form
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label5;
// минуты, секунды, миллисекунды
private int m, s, ms;
// таймер
private System.Windows.Forms.Timer timer1;
// конструктор формы
public WinForm()
{
InitializeComponent();
// обнуление показаний
m = 0; s = 0; ms = 0;
label1.Text = "00";
label2.Text = "00";
label3.Text = "00";
// период обработки события таймера
timer1.Interval = 10;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.panel1 = new System.Windows.Forms.Panel();
this.label5 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.timer1 = new System.Windows.Forms.Timer(this.components);
this.panel1.SuspendLayout();
this.SuspendLayout();
//
// label1
//
this.label1.Font = new System.Drawing.Font("Tahoma", 10F,
System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.label1.Location = new System.Drawing.Point(32, 16);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(24, 23);
this.label1.TabIndex = 0;
this.label1.Text = "00";
//
// label2
//
this.label2.Font = new System.Drawing.Font("Tahoma", 10F,
System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.label2.Location = new System.Drawing.Point(64, 16);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(24, 23);
this.label2.TabIndex = 1;
this.label2.Text = "00";
//
// label3
//
this.label3.Font = new System.Drawing.Font("Tahoma", 10F,
System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.label3.Location = new System.Drawing.Point(96, 16);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(24, 23);
this.label3.TabIndex = 2;
this.label3.Text = "00";
//
// button1
//
this.button1.Location = new System.Drawing.Point(16, 64);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(64, 23);
this.button1.TabIndex = 3;
this.button1.Text = "Пуск";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// button2
//
this.button2.Location = new System.Drawing.Point(96, 64);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(64, 23);
this.button2.TabIndex = 4;
this.button2.Text = "Сброс";
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// panel1
//
this.panel1.BorderStyle =
System.Windows.Forms.BorderStyle.FixedSingle;
this.panel1.Controls.Add(this.label5);
this.panel1.Controls.Add(this.label4);
this.panel1.Controls.Add(this.label1);
this.panel1.Controls.Add(this.label2);
this.panel1.Controls.Add(this.label3);
this.panel1.Location = new System.Drawing.Point(16, 8);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(144, 48);
this.panel1.TabIndex = 5;
//
// label5
//
this.label5.Font = new System.Drawing.Font("Tahoma", 9.75F,
System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.label5.Location = new System.Drawing.Point(86, 16);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(8, 23);
this.label5.TabIndex = 7;
this.label5.Text = ".";
//
// label4
//
this.label4.Font = new System.Drawing.Font("Tahoma", 9.75F,
System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.label4.Location = new System.Drawing.Point(54, 16);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(8, 23);
this.label4.TabIndex = 6;
this.label4.Text = ":";
//
// timer1
//
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
//
// WinForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(178, 97);
this.Controls.Add(this.panel1);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.FormBorderStyle =
System.Windows.Forms.FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
this.Name = "WinForm";
this.StartPosition =
System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Секундомер";
this.panel1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new WinForm());
}
// щелчок на кнопке Пуск/Стоп
private void button1_Click(object sender, System.EventArgs e)
{
if (timer1.Enabled) {
// останавливаем таймер
timer1.Enabled = false;
button1.Text = "Пуск";
button2.Enabled = true;
}
else {
// запускаем таймер
timer1.Enabled = true;
button1.Text = "Стоп";
button2.Enabled = false;
}
}
// щелчок на кнопке Сброс
private void button2_Click(object sender, System.EventArgs e)
{
// обнуление показаний
m = 0; s = 0; ms = 0;
label1.Text = "00";
label2.Text = "00";
label3.Text = "00";
label4.Text = ":";
}
// обработка события таймера
private void timer1_Tick(object sender, System.EventArgs e)
{
if (ms == 99) {
if (s == 59) {
if (m == 99) m = 0;
else m++;
s = 0;
}
else s++;
ms = 0;
}
else ms++;
// форматирование данных индикатора s:m:ms
if (m.ToString().Length == 1)
label1.Text = "0" + m.ToString();
else
label1.Text = m.ToString();
if (s.ToString().Length == 1)
label2.Text = "0" + s.ToString();
else
label2.Text = s.ToString();
if (ms.ToString().Length == 1)
label3.Text = "0" + ms.ToString();
else
label3.Text = ms.ToString();
// мигание разделителя минуты/секунды
if (ms == 1) label4.Text = ":";
if (ms == 50) label4.Text = "";
}
}
}
5.1. Будильник
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
namespace alarm_clock
{
/// <summary>
/// Summary description for WinForm.
/// </summary>
public class WinForm : System.Windows.Forms.Form
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components;
private System.Windows.Forms.NotifyIcon notifyIcon1;
private System.Windows.Forms.ContextMenu contextMenu1;
private System.Windows.Forms.Timer timer1;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.NumericUpDown numericUpDown1;
private System.Windows.Forms.NumericUpDown numericUpDown2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.CheckBox checkBox1;
// импортируем API метод PlaySound библиотеки winmm.dll
// позволяющий проигрывать звуковые файлы
[System.Runtime.InteropServices.DllImport("winmm.dll")]
private static extern bool
PlaySound(string lpszName, int hModule, int dwFlags);
// время срабатывания будильника
private DateTime alarm;
private System.Windows.Forms.MenuItem menuItem1;
private System.Windows.Forms.MenuItem menuItem2;
private System.Windows.Forms.MenuItem menuItem3;
private System.Windows.Forms.MenuItem menuItem4;
private System.Windows.Forms.MenuItem menuItem5;
// конструктор формы
public WinForm()
{
InitializeComponent();
// параметры компонентов numericUpDown
numericUpDown1.Maximum = 23;
numericUpDown1.Minimum = 0;
numericUpDown2.Maximum = 59;
numericUpDown2.Minimum = 0;
numericUpDown1.Value = DateTime.Now.Hour;
numericUpDown2.Value = DateTime.Now.Minute;
// контекстное меню значка панели задач
notifyIcon1.ContextMenu = contextMenu1;
notifyIcon1.Text = "Будильник не установлен.";
notifyIcon1.Visible = true;
// период обработки события сигнала от таймера
timer1.Interval = 1000;
timer1.Enabled = true;
label2.Text = DateTime.Now.ToLongTimeString();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.Resources.ResourceManager resources = new
System.Resources.ResourceManager(typeof(WinForm));
this.notifyIcon1 = new
System.Windows.Forms.NotifyIcon(this.components);
this.contextMenu1 = new System.Windows.Forms.ContextMenu();
this.menuItem1 = new System.Windows.Forms.MenuItem();
this.menuItem2 = new System.Windows.Forms.MenuItem();
this.menuItem3 = new System.Windows.Forms.MenuItem();
this.menuItem4 = new System.Windows.Forms.MenuItem();
this.menuItem5 = new System.Windows.Forms.MenuItem();
this.timer1 = new System.Windows.Forms.Timer(this.components);
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.checkBox1 = new System.Windows.Forms.CheckBox();
this.label4 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.numericUpDown2 = new
System.Windows.Forms.NumericUpDown();
this.numericUpDown1 = new
System.Windows.Forms.NumericUpDown();
this.button1 = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.groupBox1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numericUpDown2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).BeginInit();
this.SuspendLayout();
//
// notifyIcon1
//
this.notifyIcon1.Icon =
((System.Drawing.Icon)(resources.GetObject("notifyIcon1.Icon")));
this.notifyIcon1.Text = "notifyIcon1";
this.notifyIcon1.Visible = true;
//
// contextMenu1
//
this.contextMenu1.MenuItems.AddRange(new
System.Windows.Forms.MenuItem[] {
this.menuItem1,
this.menuItem2,
this.menuItem3,
this.menuItem4,
this.menuItem5});
//
// menuItem1
//
this.menuItem1.Index = 0;
this.menuItem1.Text = "Hide/Show aClock";
this.menuItem1.Click += new
System.EventHandler(this.menuItem1_Click);
//
// menuItem2
//
this.menuItem2.Index = 1;
this.menuItem2.Text = "-";
//
// menuItem3
//
this.menuItem3.Index = 2;
this.menuItem3.Text = "About";
this.menuItem3.Click += new
System.EventHandler(this.menuItem3_Click);
//
// menuItem4
//
this.menuItem4.Index = 3;
this.menuItem4.Text = "-";
//
// menuItem5
//
this.menuItem5.Index = 4;
this.menuItem5.Text = "Exit";
this.menuItem5.Click += new
System.EventHandler(this.menuItem5_Click);
//
// timer1
//
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
//
// groupBox1
//
this.groupBox1.Controls.Add(this.checkBox1);
this.groupBox1.Controls.Add(this.label4);
this.groupBox1.Controls.Add(this.label3);
this.groupBox1.Controls.Add(this.numericUpDown2);
this.groupBox1.Controls.Add(this.numericUpDown1);
this.groupBox1.Location = new System.Drawing.Point(16, 40);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(120, 136);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Сигнал";
//
// checkBox1
//
this.checkBox1.Location = new System.Drawing.Point(24, 96);
this.checkBox1.Name = "checkBox1";
this.checkBox1.Size = new System.Drawing.Size(72, 24);
this.checkBox1.TabIndex = 4;
this.checkBox1.Text = "вкл/выкл";
this.checkBox1.CheckedChanged += new
System.EventHandler(this.checkBox1_CheckedChanged);
//
// label4
//
this.label4.Location = new System.Drawing.Point(64, 64);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(40, 23);
this.label4.TabIndex = 3;
this.label4.Text = "минут";
//
// label3
//
this.label3.Location = new System.Drawing.Point(64, 32);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(40, 23);
this.label3.TabIndex = 2;
this.label3.Text = "часов";
//
// numericUpDown2
//
this.numericUpDown2.Location = new System.Drawing.Point(24, 64);
this.numericUpDown2.Name = "numericUpDown2";
this.numericUpDown2.Size = new System.Drawing.Size(40, 20);
this.numericUpDown2.TabIndex = 1;
//
// numericUpDown1
//
this.numericUpDown1.Location = new System.Drawing.Point(24, 32);
this.numericUpDown1.Name = "numericUpDown1";
this.numericUpDown1.Size = new System.Drawing.Size(40, 20);
this.numericUpDown1.TabIndex = 0;
//
// button1
//
this.button1.Location = new System.Drawing.Point(16, 184);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(120, 23);
this.button1.TabIndex = 1;
this.button1.Text = "Ok";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// label1
//
this.label1.Location = new System.Drawing.Point(24, 16);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(48, 16);
this.label1.TabIndex = 2;
this.label1.Text = "Сейчас:";
//
// label2
//
this.label2.Location = new System.Drawing.Point(80, 16);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(48, 16);
this.label2.TabIndex = 3;
this.label2.Text = "00:00:00";
//
// WinForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(154, 221);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.button1);
this.Controls.Add(this.groupBox1);
this.FormBorderStyle =
System.Windows.Forms.FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
this.Name = "WinForm";
this.StartPosition =
System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Будильник";
this.groupBox1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.numericUpDown2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).EndInit();
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new WinForm());
}
// вкл/выкл будильника
private void checkBox1_CheckedChanged(object sender, System.EventArgs e)
{
if (checkBox1.Checked) {
numericUpDown1.Enabled = false;
numericUpDown2.Enabled = false;
// установить время сигнала
alarm = new DateTime(
DateTime.Now.Year,
DateTime.Now.Month,
DateTime.Now.Day,
Convert.ToInt16(numericUpDown1.Value),
Convert.ToInt16(numericUpDown2.Value),
0, 0);
// если установленное время будильника меньше
// текущего, нужно увеличить дату срабатывания
// на единицу (+1 день)
if (DateTime.Compare(DateTime.Now,alarm) > 0)
alarm = alarm.AddDays(1);
notifyIcon1.Text = "Будильник: " +
alarm.ToShortTimeString();
}
else {
numericUpDown1.Enabled = true;
numericUpDown2.Enabled = true;
notifyIcon1.Text =
"Будильник не установлен.";
}
}
// щелчок на кнопке Ok
private void button1_Click(object sender, System.EventArgs e)
{
// скрыть окно программы
this.Hide();
}
// сигнал от таймера
private void timer1_Tick(object sender, System.EventArgs e)
{
label2.Text = DateTime.Now.ToLongTimeString();
if (checkBox1.Checked) {
// будильник установлен
if (DateTime.Compare(DateTime.Now,alarm) > 0) {
checkBox1.Checked = false;
PlaySound(Application.StartupPath +
"\\ring.wav", 0, 1 );
this.Show();
}
}
}
// выбор из контекстного меню contextMenu1
// команды Show/Hide (menuItem1)
private void menuItem1_Click(object sender, System.EventArgs e)
{
if (this.Visible) this.Hide();
else this.Show();
}
// выбор из контекстного меню contextMenu1
// команды About (menuItem3)
private void menuItem3_Click(object sender, System.EventArgs e)
{
MessageBox.Show("Программа aClock.\n\n" +
"Простой будильник.\n\n" +
"Сделано в Borland® C#Builder®\n" +
"for the Microsoft® .NET Framework\n",
"aClock 0.02",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
// выбор из контекстного меню contextMenu1
// команды Exit (menuItem5)
private void menuItem5_Click(object sender, System.EventArgs e)
{
this.Close();
}
}
}
6.1. Угадай число
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace Ugaday
{
public partial class Form1 : Form
{
int a;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Random rand = new Random();
a = rand.Next(0, 100);
}
private void button1_Click(object sender, EventArgs e)
{
int b;
b = (int)numericUpDown1.Value;
if (a > b)
{
MessageBox.Show("Не айс! Больше");
}
else if (a < b)
{
MessageBox.Show("Не айс! Меньше");
}
else
{
MessageBox.Show("Жжошь! Давай ещё!");
Random rand = new Random();
a = rand.Next(0, 100);
}
}
}
}
7.1. Банк и банкомат
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
namespace stop_watch
{
/// <summary>
/// Summary description for WinForm.
/// </summary>
public class WinForm : System.Windows.Forms.Form
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label5;
// минуты, секунды, миллисекунды
private int m, s, ms;
// таймер
private System.Windows.Forms.Timer timer1;
// конструктор формы
public WinForm()
{
InitializeComponent();
// обнуление показаний
m = 0; s = 0; ms = 0;
label1.Text = "00";
label2.Text = "00";
label3.Text = "00";
// период обработки события таймера
timer1.Interval = 10;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.panel1 = new System.Windows.Forms.Panel();
this.label5 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.timer1 = new System.Windows.Forms.Timer(this.components);
this.panel1.SuspendLayout();
this.SuspendLayout();
//
// label1
//
this.label1.Font = new System.Drawing.Font("Tahoma", 10F,
System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.label1.Location = new System.Drawing.Point(32, 16);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(24, 23);
this.label1.TabIndex = 0;
this.label1.Text = "00";
//
// label2
//
this.label2.Font = new System.Drawing.Font("Tahoma", 10F,
System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.label2.Location = new System.Drawing.Point(64, 16);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(24, 23);
this.label2.TabIndex = 1;
this.label2.Text = "00";
//
// label3
//
this.label3.Font = new System.Drawing.Font("Tahoma", 10F,
System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.label3.Location = new System.Drawing.Point(96, 16);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(24, 23);
this.label3.TabIndex = 2;
this.label3.Text = "00";
//
// button1
//
this.button1.Location = new System.Drawing.Point(16, 64);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(64, 23);
this.button1.TabIndex = 3;
this.button1.Text = "Пуск";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// button2
//
this.button2.Location = new System.Drawing.Point(96, 64);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(64, 23);
this.button2.TabIndex = 4;
this.button2.Text = "Сброс";
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// panel1
//
this.panel1.BorderStyle =
System.Windows.Forms.BorderStyle.FixedSingle;
this.panel1.Controls.Add(this.label5);
this.panel1.Controls.Add(this.label4);
this.panel1.Controls.Add(this.label1);
this.panel1.Controls.Add(this.label2);
this.panel1.Controls.Add(this.label3);
this.panel1.Location = new System.Drawing.Point(16, 8);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(144, 48);
this.panel1.TabIndex = 5;
//
// label5
//
this.label5.Font = new System.Drawing.Font("Tahoma", 9.75F,
System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.label5.Location = new System.Drawing.Point(86, 16);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(8, 23);
this.label5.TabIndex = 7;
this.label5.Text = ".";
//
// label4
//
this.label4.Font = new System.Drawing.Font("Tahoma", 9.75F,
System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.label4.Location = new System.Drawing.Point(54, 16);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(8, 23);
this.label4.TabIndex = 6;
this.label4.Text = ":";
//
// timer1
//
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
//
// WinForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(178, 97);
this.Controls.Add(this.panel1);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.FormBorderStyle =
System.Windows.Forms.FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
this.Name = "WinForm";
this.StartPosition =
System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Секундомер";
this.panel1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new WinForm());
}
// щелчок на кнопке Пуск/Стоп
private void button1_Click(object sender, System.EventArgs e)
{
if (timer1.Enabled) {
// останавливаем таймер
timer1.Enabled = false;
button1.Text = "Пуск";
button2.Enabled = true;
}
else {
// запускаем таймер
timer1.Enabled = true;
button1.Text = "Стоп";
button2.Enabled = false;
}
}
// щелчок на кнопке Сброс
private void button2_Click(object sender, System.EventArgs e)
{
// обнуление показаний
m = 0; s = 0; ms = 0;
label1.Text = "00";
label2.Text = "00";
label3.Text = "00";
label4.Text = ":";
}
// обработка события таймера
private void timer1_Tick(object sender, System.EventArgs e)
{
if (ms == 99) {
if (s == 59) {
if (m == 99) m = 0;
else m++;
s = 0;
}
else s++;
ms = 0;
}
else ms++;
// форматирование данных индикатора s:m:ms
if (m.ToString().Length == 1)
label1.Text = "0" + m.ToString();
else
label1.Text = m.ToString();
if (s.ToString().Length == 1)
label2.Text = "0" + s.ToString();
else
label2.Text = s.ToString();
if (ms.ToString().Length == 1)
label3.Text = "0" + ms.ToString();
else
label3.Text = ms.ToString();
// мигание разделителя минуты/секунды
if (ms == 1) label4.Text = ":";
if (ms == 50) label4.Text = "";
}
}
}
8.1. Угадай число (с сохранением статистики)
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
namespace guess_number
{
/// <summary>
/// Summary description for WinForm.
/// </summary>
public class WinForm : System.Windows.Forms.Form
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components;
private System.Windows.Forms.StatusBar statusBar1;
private System.Windows.Forms.StatusBarPanel statusBarPanel1;
private System.Windows.Forms.StatusBarPanel statusBarPanel2;
/*
Для отображения элементов statusBarPannel1 и
statusBarPannel2 их необходимо добавить
в коллекцию Pannels компонента statusBar1,
а также свойству ShowPanels присвоить значение true.
*/
// количесвтво знаков загаданного числа
private const int CN = 3;
private int t,
// количество сделанных попыток
s;
// количетсво прощедших секунд
// загаданное число
private int[] n = new int[CN];
private System.Windows.Forms.Label label1;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Timer timer1;
// конструктор формы
public WinForm()
{
InitializeComponent();
statusBar1.ShowPanels = true;
statusBar1.SizingGrip = false;
statusBar1.Panels[0].Text = " Попыток: 0";
statusBar1.Panels[1].Text = " Затрачено времени: 0 сек.";
groupBox1.Enabled = false;
timer1.Interval = 1000;
timer1.Enabled = false;
textBox1.MaxLength = CN;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.statusBar1 = new System.Windows.Forms.StatusBar();
this.statusBarPanel1 = new System.Windows.Forms.StatusBarPanel();
this.statusBarPanel2 = new System.Windows.Forms.StatusBarPanel();
this.label1 = new System.Windows.Forms.Label();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.label3 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.textBox1 = new System.Windows.Forms.TextBox();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.timer1 = new System.Windows.Forms.Timer(this.components);
((System.ComponentModel.ISupportInitialize)(this.statusBarPanel1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.statusBarPanel2)).BeginInit();
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// statusBar1
//
this.statusBar1.Location = new System.Drawing.Point(0, 207);
this.statusBar1.Name = "statusBar1";
this.statusBar1.Panels.AddRange(new
System.Windows.Forms.StatusBarPanel[] {
this.statusBarPanel1,
this.statusBarPanel2});
this.statusBar1.ShowPanels = true;
this.statusBar1.Size = new System.Drawing.Size(234, 22);
this.statusBar1.TabIndex = 0;
this.statusBar1.Text = "statusBar1";
//
// statusBarPanel1
//
this.statusBarPanel1.Text = "statusBarPanel1";
this.statusBarPanel1.Width = 80;
//
// statusBarPanel2
//
this.statusBarPanel2.AutoSize =
System.Windows.Forms.StatusBarPanelAutoSize.Spring;
this.statusBarPanel2.Text = "statusBarPanel2";
this.statusBarPanel2.Width = 138;
//
// label1
//
this.label1.Location = new System.Drawing.Point(8, 8);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(192, 40);
this.label1.TabIndex = 1;
this.label1.Text = "Угадайте загаданное компьютером трехзначное
число. Введите свой в" +
"ариант и нажмите <Enter>.";
//
// groupBox1
//
this.groupBox1.Controls.Add(this.label3);
this.groupBox1.Controls.Add(this.label2);
this.groupBox1.Controls.Add(this.textBox1);
this.groupBox1.Location = new System.Drawing.Point(8, 56);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(216, 112);
this.groupBox1.TabIndex = 2;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Число";
//
// label3
//
this.label3.Location = new System.Drawing.Point(8, 80);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(192, 24);
this.label3.TabIndex = 2;
this.label3.Text = "Цифр на правильных позициях: 0";
//
// label2
//
this.label2.Location = new System.Drawing.Point(8, 56);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(192, 23);
this.label2.TabIndex = 1;
this.label2.Text = "Угадано цифр: 0";
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(8, 24);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(80, 20);
this.textBox1.TabIndex = 0;
this.textBox1.Text = "";
this.textBox1.KeyPress += new
System.Windows.Forms.KeyPressEventHandler(this.textBox1_KeyPress);
//
// button1
//
this.button1.Location = new System.Drawing.Point(8, 176);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(104, 23);
this.button1.TabIndex = 3;
this.button1.Text = "Начать";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// button2
//
this.button2.Location = new System.Drawing.Point(120, 176);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(104, 23);
this.button2.TabIndex = 4;
this.button2.Text = "Завершить";
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// timer1
//
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
//
// WinForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(234, 229);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.label1);
this.Controls.Add(this.statusBar1);
this.FormBorderStyle =
System.Windows.Forms.FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
this.Name = "WinForm";
this.StartPosition =
System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Угадай число";
((System.ComponentModel.ISupportInitialize)(this.statusBarPanel1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.statusBarPanel2)).EndInit();
this.groupBox1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new WinForm());
}
// щелчок на кнопке Начать
private void button1_Click(object sender, System.EventArgs e)
{
if (!timer1.Enabled) {
// генерация числа
Random rnd = new Random();
n[0] = rnd.Next(9) + 1;
for (int i = 1; i < CN; i++)
n[i] = rnd.Next(10);
t = 0; s = 0;
textBox1.Text = string.Empty;
button1.Text = "Стоп";
textBox1.Select();
groupBox1.Enabled = true;
timer1.Enabled = true;
}
else {
timer1.Enabled = false;
groupBox1.Enabled = false;
textBox1.Text = string.Empty;
button1.Text = "Начать";
label2.Text = "Угадано цифр: 0";
label3.Text = "Цифр на правильных позициях: 0";
statusBar1.Panels[0].Text = " Попыток: 0";
statusBar1.Panels[1].Text = " Затрачено времени: 0 сек.";
}
}
// нажатие клавиши в поле ввода числа
private void textBox1_KeyPress(object sender,
System.Windows.Forms.KeyPressEventArgs e)
{
// учет угаданных цифр
Boolean[] r = new Boolean[CN];
int pn = 0,
rn = 0;
// цифры на правильных позициях
// угаданные цифры
// допустим ввод только цифр и использование
// управляющих клавиш (Enter, Backspace и др.)
if (Char.IsDigit(e.KeyChar) ||
Char.IsControl(e.KeyChar)) {
// была нажата клавиша <Enter>
if (e.KeyChar.Equals((char)13)) {
t++;
// счетчик сделанных попыток
statusBar1.Panels[0].Text =
" Попыток: " + t.ToString();
// считаем угаданные цифры и позиции
for(int i = 0; i < textBox1.TextLength; i++) {
for(int j = 0; j < CN; j++)
if ((Convert.ToInt16(
textBox1.Text.Substring(i,1)) == n[j])
&& (!r[j])) {
rn++;
r[j] = true;
break;
}
if (Convert.ToInt16(textBox1.Text.Substring(i,1))
== n[i])
pn++;
}
label2.Text = "Угадано цифр: " + rn.ToString();
label3.Text = "Цифр на правильных позициях: " +
pn.ToString();
// загаданное число угадано
if (pn == CN) {
timer1.Enabled = false;
groupBox1.Enabled = false;
MessageBox.Show("Вы угадали!\n" +
"Загаданное число: " + textBox1.Text +
"\nСовершено попыток: " + t.ToString() +
"\nЗатрачено времени: " + s.ToString() + "
сек.",
"Угадай число",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
textBox1.Text = string.Empty;
button1.Text = "Начать";
label2.Text = "Угадано цифр: 0";
label3.Text = "Цифр на правильных
позициях: 0";
statusBar1.Panels[0].Text = " Попыток: 0";
statusBar1.Panels[1].Text = " Затрачено
времени: 0 сек.";
}
}
}
else e.Handled = true;
}
// щелчок на кнопке Завершить
private void button2_Click(object sender, System.EventArgs e)
{
this.Close();
}
// обработка события таймера
private void timer1_Tick(object sender, System.EventArgs e)
{
s++;
statusBar1.Panels[1].Text = " Затрачено времени: " +
s.ToString() + " сек.";
}
}
}
9.1. Игра собери картинку
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
namespace puzzle
{
/// <summary>
/// Summary description for WinForm.
/// </summary>
public class WinForm : System.Windows.Forms.Form
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private System.Windows.Forms.MainMenu mainMenu1;
private System.Windows.Forms.MenuItem menuItem1;
private System.Windows.Forms.MenuItem menuItem2;
// размер игрового поля
private const int nw = 4, nh = 4;
// рабочая графическая поверхность
private System.Drawing.Graphics g;
// картинка, загружаемая из файла
private Bitmap pics;
// ширина и высота клетки
private int cw, ch;
// игровое поле
private int[,] field = new int[nw,nh];
// координаты пустой клетки
private int ex, ey;
// показывает, отображаются ли номера фишек
private Boolean showNumbers = false;
// новая игра
private void newGame() {
// распологаем фишки в правильном порядке
for(int j = 0; j < nh; j++)
for(int i = 0; i < nw; i++)
field[i,j] = j*nw + i + 1;
// последняя фишка - пустая
field[nw-1, nh-1] = 0;
ex = nw-1; ey = nh-1;
this.mixer();
this.drawField();
// перемешиваем фишки
// выводим игровое поле
}
// процедура перемешивает фишки
private void mixer() {
int x, y,
// эту клетку переместить в пустую
d; // направление перемещения, относительно пустой
// генератор случайных чисел
Random rnd = new Random();
for(int i = 0; i < nw * nh * 10; i++)
// nw * nh * 10 - кол-во перестановок
{
x = ex;
y = ey;
d = rnd.Next(4);
switch (d) {
case 0: if (x > 0) x--; break;
case 1: if (x < nw-1) x++; break;
case 2: if (y > 0) y--; break;
case 3: if (y < nh-1) y++; break;
}
// здесь определили фишку, которую
// нужно переместить в пустую клетку
field[ex,ey] = field[x,y];
field[x,y] = 0;
// запоминаем координаты пустой фишки
ex = x; ey = y;
}
}
// процедура отрисовывает поле field
private void drawField() {
// содержимое клеток
for(int i = 0; i < nw; i++)
for(int j = 0; j < nh; j++) {
if (field[i,j] != 0)
// выводим фишку с картинкой:
// ( ((field[i,j] - 1) % nw) * cw,
// (int)((field[i,j] - 1) / nw) * ch ) // координаты левого верхнего угла области
источника
g.DrawImage(pics,
new Rectangle(i*cw, j*ch, cw, ch),
new Rectangle(
((field[i,j] - 1) % nw) * cw,
(int)((field[i,j] - 1) / nw) * ch,
cw, ch),
GraphicsUnit.Pixel);
else
// выводим пустую фишку
g.FillRectangle(SystemBrushes.Control,
i*cw, j*ch, cw, ch);
// рисуем границу
g.DrawRectangle(Pens.Black,
i*cw, j*ch, cw, ch);
// номер фишки
if ((showNumbers) && field[i,j] != 0)
g.DrawString(Convert.ToString(field[i,j]),
new Font("Tahoma",10,FontStyle.Bold),
Brushes.Black, i*cw + 5, j*ch + 5);
}
}
// "перемещает" фишку в соседнюю пустую
// клетку, если она есть, конечно;
// (cx, cy) - клетка, в которой сделан щелчок,
// (ex, ey) - пустая клетка
private void move(int cx, int cy) {
// проверим, возможен ли обмен
if (!((( Math.Abs(cx - ex) == 1) && (cy - ey == 0)) ||
(( Math.Abs(cy - ey) == 1) && (cx - ex == 0))))
return;
// обмен. переместим фишку из (x, y) в (ex, ey)
field[ex,ey] = field[cx,cy];
field[cx,cy] = 0;
ex = cx; ey = cy;
// отрисовать поле
this.drawField();
if (this.finish()) {
field[nw-1, nh-1] = nh*nw;
this.drawField();
// игра закончена. сыграть еще раз?
// No - завершить работу программы,
// Yes - новая игра
if (MessageBox.Show("Congratulations!\n" +
"Еще раз?", "Собери картинку",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question)
== System.Windows.Forms.DialogResult.No)
this.Close();
else this.newGame();
}
}
// проверяет, расположены ли фишки в правильном порядке
private Boolean finish() {
int i = 0, j = 0,
c;
// счетчик фишек
for(c = 1; c < nw*nh; c++) {
if (field[i,j] != c) return false;
// к следующей клетке
if (i < nw - 1) i++;
else { i = 0; j++; }
}
return true;
}
public WinForm()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.mainMenu1 = new System.Windows.Forms.MainMenu();
this.menuItem1 = new System.Windows.Forms.MenuItem();
this.menuItem2 = new System.Windows.Forms.MenuItem();
//
// mainMenu1
//
this.mainMenu1.MenuItems.AddRange(new
System.Windows.Forms.MenuItem[] {
this.menuItem1,
this.menuItem2});
//
// menuItem1
//
this.menuItem1.Index = 0;
this.menuItem1.Text = "Новая игра";
this.menuItem1.Click += new
System.EventHandler(this.menuItem1_Click);
//
// menuItem2
//
this.menuItem2.Index = 1;
this.menuItem2.Text = "Показать номера фишек";
this.menuItem2.Click += new
System.EventHandler(this.menuItem2_Click);
//
// WinForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 271);
this.FormBorderStyle =
System.Windows.Forms.FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
this.Menu = this.mainMenu1;
this.Name = "WinForm";
this.StartPosition =
System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Собери картинку";
this.MouseDown += new
System.Windows.Forms.MouseEventHandler(this.WinForm_MouseDown);
this.Load += new System.EventHandler(this.WinForm_Load);
this.Paint += new
System.Windows.Forms.PaintEventHandler(this.WinForm_Paint);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new WinForm());
}
// загрузка формы
private void WinForm_Load(object sender, System.EventArgs e)
{
try {
// загружаем файл картинки
pics = new Bitmap("psource.bmp");
}
catch(Exception exc) {
MessageBox.Show("Файл 'psource.bmp' не найден.\n" +
exc.ToString(), "Файл не найден",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
this.Close();
return;
}
// определяем высоту и ширину клетки (фишки)
cw = (int)(pics.Width / nw);
ch = (int)(pics.Height / nh);
// ширина и высота рабочей области формы
this.ClientSize =
new System.Drawing.Size(cw * nw + 1, ch * nh + 1);
// рабочая графическая поверхность
g = this.CreateGraphics();
this.newGame();
}
// щелчок мыши на игровом поле
private void WinForm_MouseDown(object sender,
System.Windows.Forms.MouseEventArgs e)
{
// преобразуем координаты мыши в координаты клетки
this.move((int)(e.X / cw), (int)(e.Y / ch));
}
// обработка события Paint
private void WinForm_Paint(object sender,
System.Windows.Forms.PaintEventArgs e)
{
// отрисовать игровое поле
this.drawField();
}
// щелчок на пункте меню Новая игра
private void menuItem1_Click(object sender, System.EventArgs e)
{
g.FillRectangle(
SystemBrushes.Control,
0, 0, cw * nw + 1, ch * nh + 1);
this.newGame();
}
// щелчок на пункте меню Показать/Скрыть номера фишек
private void menuItem2_Click(object sender, System.EventArgs e)
{
if (showNumbers) {
showNumbers = false;
menuItem2.Text = "Показать номера фишек";
this.drawField();
}
else {
showNumbers = true;
menuItem2.Text = "Скрыть номера фишек";
this.drawField();
}
}
}
}
Download