unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, AppEvnts, ExtCtrls, StdCtrls, TeEngine, TeeProcs, Chart, Series,
ExtDlgs;
type
TForm1 = class abstract(TForm)
Button1: TButton;
LabeledEdit1: TLabeledEdit;
LabeledEdit2: TLabeledEdit;
LabeledEdit3: TLabeledEdit;
LabeledEdit4: TLabeledEdit;
LabeledEdit5: TLabeledEdit;
LabeledEdit6: TLabeledEdit;
Chart1: TChart;
LabeledEdit7: TLabeledEdit;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Series1: TLineSeries;
SaveTextFileDialog1: TSaveTextFileDialog;
private
{ Private declarations }
public
{ Public declarations }
end;
TStorage = class;
TControl = class;
// граничный класс
TBorder = class(TForm1)
public
//Старт
procedure StartBtn(Sender: TObject);
//Проверка ввода
procedure InputParam (Sender: TObject);
//Построение графика
procedure Plot (betta : real; time : integer);
//диалог получения нового имени выходного файла
function GetOutName (old : string) : string;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
/// True
_Controller: TControl;
//дописали конструктор
constructor Create(AOwner: TComponent); override;
end;
//класс-хранилище
TStorage = class
output : string;
//запись в файл выходных данных и параметров последнего расчета
procedure SaveData (ro, h, r, w, db, w0, t, betta : real);
//считывание папарметров предыдущего расчета
procedure LoadFromFile (var t: array of string; var OutName : string;
var result : boolean);
private
/// True
_Controller: TControl;
end;
//класс- контроллер
TFinishEvent = procedure(Sender: TObject) of object;
TControl = class
private
FFinish: TFinishEvent;
/// True
_Border: TBorder;
/// True
_Storage: TStorage;
procedure Finish();
//формирование начальных значений полей
procedure GetData (var t: array of string);
procedure OnTimer (Sender: TObject);
public
property OnFinish: TFinishEvent read FFinish write FFinish;
//вычисление функции и перех к сохранению результатов
procedure Calc(ro, h, r, w, db, w0, t : real);
constructor Create (Aowner:Tcomponent);
end;
var
Controller: TControl;
Storage: TStorage;
Border: TBorder;
today : TDatetime;
T1 : TTimer;
wtime : integer;
procedure Link ();
implementation
{$R *.dfm}
procedure Link ();
begin
Border._Controller := Controller;
Controller._Border := Border;
Controller._Storage := Storage;
Storage._Controller := Controller;
end;
constructor TBorder.Create(AOwner: TComponent); //задание начальых параметров
var
param : TextFile;
t : array [0..6] of string;
i : integer;
begin
inherited;
today := Now;
//связываем классы между собой
Link;
//интрефейс
Label1.Caption := 'Параметры ротора';
Label2.Caption := 'Параметры прибора';
Label3.Caption := 'Параметры исследования';
Label4.Caption := 'Грфик зависимости выходного угла от веремни';
LabeledEdit1.EditLabel.Caption := 'Плотность, г/см3';
LabeledEdit2.EditLabel.Caption := 'Высота, см';
LabeledEdit3.EditLabel.Caption := 'Радиус, см';
LabeledEdit4.EditLabel.Caption := 'Скорость вращения, об/мин';
LabeledEdit5.EditLabel.Caption := 'Демпфирование, Н*с';
LabeledEdit6.EditLabel.Caption := 'Скорость основания, рад/сек';
LabeledEdit7.EditLabel.Caption := 'Время, сек';
LabeledEdit1.OnExit := InputParam; //обработка ввода
LabeledEdit2.OnExit := InputParam;
LabeledEdit3.OnExit := InputParam;
LabeledEdit4.OnExit := InputParam;
LabeledEdit5.OnExit := InputParam;
LabeledEdit6.OnExit := InputParam;
LabeledEdit7.OnExit := InputParam;
Button1.OnClick := StartBtn; //Старт
OnClose := FormClose;
//получить массив начальных данных
_Controller.GetData (t);
LabeledEdit1.Text := t[0]; //плотность гр на см3
LabeledEdit2.Text := t[1]; //Высота см
LabeledEdit3.Text := t[2]; //радиус основания см
LabeledEdit4.Text := t[3]; //скорость вращения об в мин
LabeledEdit5.Text := t[4]; //демпфирование
LabeledEdit6.Text := t[5]; //скорость основания рад в сек
LabeledEdit7.Text := t[6]; //время сек
end;
procedure TBorder.InputParam (Sender: TObject); //обработка ввода данных в TChart
var
V : real;
code : integer;
begin
with sender as TLabeledEdit do
begin
Val (Text, v, code);
if code <> 0 then Text := 'введите число!';
end;
end;
procedure TBorder.StartBtn(Sender: TObject); //старт
var
ro, h, r, w, db, w0, t : real;
begin
//введеные параметры
ro := StrtoFloat(LabeledEdit1.Text);
h := StrtoFloat(LabeledEdit2.Text);
r := StrtoFloat(LabeledEdit3.Text);
w := StrtoFloat(LabeledEdit4.Text);
db := StrtoFloat(LabeledEdit5.Text);
W0 := StrtoFloat(LabeledEdit6.Text);
t := StrtoFloat(LabeledEdit7.Text);
//считали поля и передали все контроллеру
_Controller.Calc (ro, h, r, w, db, w0, t);
end;
procedure TBorder.Plot (betta: real; time: integer); //построение граффиков
begin
Chart1.Series[0].AddXY(time, betta);
end;
function TBorder.GetOutName (old : string) : string;
begin
//настройка диалога сохранения
//по умолчанию ставим директорию с предыдущим файлом
saveTextFileDialog1.InitialDir := old;
saveTextFileDialog1.Filter := 'Text file|*.txt';
saveTextFileDialog1.DefaultExt := 'txt';
saveTextFileDialog1.FilterIndex := 1;
//оповестим пользователя, что мы от него хотим
ShowMessage ('Выходной файл...');
if saveTextFileDialog1.Execute //если пользователь указал имя
then Result := SaveTextFileDialog1.FileName //то его и передадим
else Result := GetCurrentDir + '\' + DateToStr(today) + '.txt';
//сохраним у себя в корне под текущей датой
end;
procedure TControl.GetData (var t: array of string); //формирование нач. данных
var
outname : string;
result : boolean;
begin
//попробуем загрузить из файла данные и имя выходного файла
Controller._Storage.LoadFromFile (t, outname, result);
if not result then //если файла не существует, то по умолчанию...
begin
t[0] := '30';
t[1] := '4';
t[2] := '2';
t[3] := '6000';
t[4] := '2';
t[5] := '0,05';
t[6] := '100';
OutName := GetCurrentDir + '\' + DateToStr(today) + '.txt';
end;
_Storage.output := OutName; //передаем в хранилище имя выходного файла
end;
procedure TControl.Calc (ro, h, r, w, db, w0, t : real); //вычисление
var
Cz, Hg, m, betta : real;
time : integer;
begin
_Border.Chart1.Series[0].Clear; //а вдруг там уже что-то есть?
//вычисление функции
m := ro * pi * sqr(r) * h; //гр
Cz := m * sqr(r) / 2; //гр * см2
Hg := Cz * w * 2 * pi / 360 / 60; // гр * см2 * рад / с
for time := 0 to Trunc(t) do
begin
betta := Hg / (Db * 1000 * 100) * W0 * time * 57.3; //град в сек
_Border.Plot (betta, time); //построение графика
end;
//получение нового имени вых. файла и передача в хранилище
_Storage.output := _Border.GetOutName (_Storage.output);
//запись выходных файлов настроек и вычислений
_Storage.SaveData (ro, h, r, w, db, w0, t, betta);
end;
procedure TControl.Finish(); //завершение работы
begin
if Assigned(FFinish) then FFinish(Self);
// Cтандартное по закрытию
ShowMessage ('Вы были с нами: ' + FloatToStr (round(wtime/100)) + 'сек');
end;
constructor TControl.Create (aowner:Tcomponent);
begin
inherited create;
wtime:=0;
T1 := TTimer.Create(Aowner);
T1.Enabled := true;
T1.OnTimer := OnTimer;
T1.Interval := 10;
end;
procedure TControl.OnTimer (Sender: TObject);
begin
inc (wtime);
end;
procedure TStorage.LoadFromFile (var t: array of string; var OutName : string;
var result : boolean);
//загружаем из файла массив данных, имя выходног офайла и если получилось, то
//ставим result true
var
param : TextFile;
i : integer;
begin
Result := false; //пессимистично считаем, что файла нет
if FileExists ('input.txt') then //Если файл существует
begin //верим в то что это именно тот файл и считываем из него данные
Result:=true; //нашли!
AssignFile (param, 'input.txt');
Reset (param);
i := 0;
while (not EOF(param)) and (i<=6) do //данные
begin
readln (param, t[i]);
inc (i);
end;
if not EOF (param) then readln (param, OutName); //имя выходного файла
CloseFile (param);
end;
end;
procedure TStorage.SaveData(ro: Real; h: Real; r: Real; w: Real; //запись в файл
db: Real; w0: Real; t: Real; betta: Real);
var
input, output : TextFile;
begin
//сохранение настроек
AssignFile (input, 'input.txt');
Rewrite (input);
writeln (input, floattostr (ro));
writeln (input, floattostr (h));
writeln (input, floattostr (r));
writeln (input, floattostr (w));
writeln (input, floattostr (db));
writeln (input, floattostr (w0));
writeln (input, floattostr (t));
writeln (input, Storage.output);
CloseFile (input);
//сохранение выхода
if FileExists (Storage.output)
then
begin
AssignFile (output, Storage.output);
Append (output);
Writeln (output, floattostr (ro) + '|' + floattostr (h)+ '|' + floattostr (r) +
'|' + floattostr (w) + '|' + floattostr (db) + '|' + floattostr (w0)
+ '|' + floattostr (t) + '==>' + floattostr (betta));
CloseFile (output);
end
else
begin
AssignFile (output, Storage.output);
Rewrite (output);
Writeln (output, floattostr (ro) + '|' + floattostr (h)+ '|' + floattostr (r) +
'|' + floattostr (w) + '|' + floattostr (db) + '|' + floattostr (w0) +
'|' + floattostr (t) + '==>' + floattostr (betta));
CloseFile (output);
end;
ShowMessage ('Данные вычисления сохранены в ' + Storage.output);
end;
procedure TBorder.FormClose(Sender: TObject; var Action: TCloseAction);
begin
_Controller.Finish;
end;
end.