Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > Delphi программирование > Общие вопросы Delphi
Регистрация

Восстановить пароль
Повторная активизация e-mail

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 17.12.2008, 16:28   #1
Bayazet
Форумчанин
 
Регистрация: 08.12.2008
Сообщений: 156
По умолчанию

добрыйдень. передомною была поставленна задача написать программу сапер (ну, игрушка, как стандартная). Когда я ее написал, препод дал след. задание: из своей программы сделать компонент. и вот тут попал в тупик.

вот код моего сопера (т.к. я уже засветил код преподу, поэтому нужно именно из моего заделать компонет ):

Код:
unit main;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs,StdCtrls, Buttons, ExtCtrls, Grids;

const
  minWidth = 12 * 30 + 40;

type
  TBit = class(TSpeedButton)
  private
  public
    x : integer;          //координата Х
    y : integer;          //координата Y
    mine : WordBool;      //содержание полем мины
    clicked : WordBool;   //нажималось ли уже на поле
    unsafe : WordBool;    //подозрительно поле (с флажком)
    around : integer;     //количество мин вокруг
  end;
  TB = array of TBit;
  TButtons = array of TB;
  TForm1 = class(TForm)
    BitBtn1: TBitBtn;
    Edit1: TEdit;
    Label1: TLabel;
    Edit2: TEdit;
    Label2: TLabel;
    Button1: TButton;
    BitBtn2: TBitBtn;
    SpeedButton1: TSpeedButton;
    Label3: TLabel;
    Panel1: TPanel;
    Label4: TLabel;
    Panel2: TPanel;
    Timer1: TTimer;
    procedure FormCreate(Sender: TObject);
    procedure BitBtn1Click(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure SpeedButton1MouseDown(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    procedure Timer1Timer(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

procedure MinesAround(i, j : integer);  //открывание соседних полей с пустым
procedure ShowAll;                      //вскрытие игрового поля после окончания игры

var
  MainForm: TForm1;
  buttons : TButtons;
  size, mines_count : integer;   //размер поля, количество мин
  opened : integer = 0;          //количество открытых полей
  m_click : integer = 0;         //количество поставленных флажков
  m_true : integer = 0;          //количество верно поставленных флажков
  first : WordBool = true;       //первый ли раз запускается приложение
  endgame : WordBool = false;    //условие окончания игры
  time : integer;                //секундомер
  T : Double;                    //время игры
implementation

{$R *.dfm}
{$B+}

procedure TForm1.FormCreate(Sender: TObject);
  var
    tab : integer;
    i, j : integer;
begin
  time := 0;
  endgame := false;
  m_click := 0;
  m_true := 0;
  opened := 0;
  setLength(buttons,size);
  tab := (minWidth - size*30) div 2;
  If tab < 10 then tab := 10;
  for i := 0 to size-1 do
    setLength(buttons[i], size);
  for i := 0 to size-1 do
    for j := 0 to size-1 do
    begin
      buttons[i,j] := TBit.Create(self);
      buttons[i,j].Parent := self;
      buttons[i,j].Height := 30;
      buttons[i,j].Width := 30;
      buttons[i,j].Top := i * buttons[i,j].Height + 80;
      buttons[i,j].Left := j * buttons[i,j].Width + tab;
      buttons[i,j].mine := false;
      buttons[i,j].clicked := false;
      buttons[i,j].unsafe := false;
      buttons[i,j].OnMouseDown  := SpeedButton1MouseDown;
      buttons[i,j].x := i;
      buttons[i,j].y := j;
    end;
    MainForm.Height := size * 30 + 120;
    MainForm.Width := size * 30 + 40;
    If MainForm.Width < minWidth then MainForm.Width := minWidth;
    MainForm.Position := poDesktopCenter;
end;

Последний раз редактировалось rpy3uH; 17.12.2008 в 17:48.
Bayazet вне форума Ответить с цитированием
Старый 17.12.2008, 16:32   #2
Bayazet
Форумчанин
 
Регистрация: 08.12.2008
Сообщений: 156
По умолчанию

Код:
procedure TForm1.BitBtn1Click(Sender: TObject);
  var
    count, mc : integer;
    i, j : integer;
begin
  If not first then
    For i := 0 to size-1 do
      For j := 0 to size-1 do
        buttons[i,j].Free;
  size := StrToInt(MainForm.Edit1.Text);
  mines_count := StrToInt(MainForm.Edit2.Text);
  If (size in [3..30]) and (mines_count in [1..size*size-2]) then
  begin
    Panel1.Font.Name := 'Arial';
    first := false;
    Panel2.Font.Name := 'Arial';
    Panel2.Caption := '0:00:00';
    Panel1.Caption := Edit2.Text;
    MainForm.FormCreate(Sender);
    mc := mines_count;
    Panel1.Caption := IntToStr(mines_count);
    While mc > 0 do
    begin
      randomize;
      i := random(size);
      j := random(size);
      If not buttons[i,j].mine then
      begin
        buttons[i,j].mine := true;
        mc := mc-1;
      end;
    end;
    For i := 0 to size-1 do
      For j := 0 to size-1 do
      begin
        count := 0;
        If (i-1 in [0..size-1]) and (j-1 in [0..size-1]) then If buttons[i-1, j-1].mine then count := count + 1;
        If (i-1 in [0..size-1]) and (j in [0..size-1])   then If buttons[i-1, j].mine   then count := count + 1;
        If (i-1 in [0..size-1]) and (j+1 in [0..size-1]) then If buttons[i-1, j+1].mine then count := count + 1;
        If (i in [0..size-1])   and (j-1 in [0..size-1]) then If buttons[i, j-1].mine   then count := count + 1;
        If (i in [0..size-1])   and (j+1 in [0..size-1]) then If buttons[i, j+1].mine   then count := count + 1;
        If (i+1 in [0..size-1]) and (j-1 in [0..size-1]) then If buttons[i+1, j-1].mine then count := count + 1;
        If (i+1 in [0..size-1]) and (j in [0..size-1])   then If buttons[i+1, j].mine   then count := count + 1;
        If (i+1 in [0..size-1]) and (j+1 in [0..size-1]) then If buttons[i+1, j+1].mine then count := count + 1;
        buttons[i,j].around := count;
      end;
    Timer1.Enabled := true;
  end
  else ShowMessage('Размеры поля должны быть от 3 до 30' + #$D + 'Количество мин - меньше квадрата размера поля');
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  close;
end;

procedure MinesAround(i, j : integer);
begin
  If (i in [0..size-1]) and (j in [0..size-1]) then
  begin
    If not buttons[i,j].clicked then
    begin
      buttons[i,j].Font.Name := 'Arial';
      If buttons[i,j].around = 0 then buttons[i,j].Caption := ''
                                 else buttons[i,j].Caption := IntToStr(buttons[i,j].around);
      buttons[i,j].clicked := true;
      buttons[i,j].Flat := true;
      buttons[i,j].Enabled := false;
      opened := opened + 1;
      If buttons[i,j].around = 0 then begin
                                        MinesAround(i-1,j-1);
                                        MinesAround(i-1,j);
                                        MinesAround(i-1,j+1);
                                        MinesAround(i,j-1);
                                        MinesAround(i,j+1);
                                        MinesAround(i+1,j-1);
                                        MinesAround(i+1,j);
                                        MinesAround(i+1,j+1);
                                      end;

    end;
  end;
end;
Bayazet вне форума Ответить с цитированием
Старый 17.12.2008, 16:34   #3
BOBAH13
Android Developer
Старожил Подтвердите свой е-майл
 
Аватар для BOBAH13
 
Регистрация: 19.02.2007
Сообщений: 3,708
По умолчанию

Гм... а вот интересно TForm1 - это не компонент ? это не класс который наследует другие классы VCL ? что сложного все это объединить в методы одного класса ( ну или нескольких ) потом переименовать тот же TForm1 на тот же TSaper и написать procedure Register; вот и будет вам компонент. А вы нам зачем собственно дали код ? не ужели опять из серии вот код сделайте за короткие сроки
BOBAH13 вне форума Ответить с цитированием
Старый 17.12.2008, 16:38   #4
Bayazet
Форумчанин
 
Регистрация: 08.12.2008
Сообщений: 156
По умолчанию

Код:
procedure ShowAll;
  var
    i, j : integer;
begin
  For i := 0 to size-1 do
    for j := 0 to size-1 do
    begin
      If not buttons[i,j].clicked then begin
                                         buttons[i,j].Font.Color := clPurple;
                                         buttons[i,j].Flat := true;
                                         If buttons[i,j].mine then begin
                                                                     buttons[i,j].Font.Name := 'Wingdings';
                                                                     buttons[i,j].Font.Size := 12;
                                                                     buttons[i,j].Caption := #77;
                                                                     buttons[i,j].Flat := false;
                                                                   end
                                           else buttons[i,j].Caption := IntToStr(buttons[i,j].around);
                                       end
                                  else begin
                                         If buttons[i,j].unsafe then
                                           If buttons[i,j].mine then begin
                                                                       buttons[i,j].Font.Color := clGreen;
                                                                       buttons[i,j].Font.Size := 15;
                                                                       buttons[i,j].Caption := #252;
                                                                     end
                                                                else begin
                                                                       buttons[i,j].Font.Color := clMaroon;
                                                                       buttons[i,j].Font.Size := 15;
                                                                       buttons[i,j].Caption := #251;
                                                                     end;
                                       end;
    end;
end;

procedure TForm1.SpeedButton1MouseDown(Sender: TObject;
  Button: TMouseButton; Shift: TShiftState; X, Y: Integer);

var
    now : TBit;
begin
  If not endgame then
  begin
    now := sender as TBit;
    If (button = mbLeft) and (not now.clicked) then
    begin
      If now.mine then begin
                         ShowMessage('ВЗБДЫЩЬ!');
                         endgame := true;
                       end
                  else
                    MinesAround(now.x, now.y);
    end;
    If button = mbRight then
      If now.unsafe then
      begin
        now.Font.Color := clBlack;
        now.Font.Name := 'Arial';
        now.Caption := '';
        now.clicked := false;
        now.Font.Size := 8;
        now.unsafe := false;
        m_click := m_click - 1;
        If now.mine then m_true := m_true - 1;
      end
      else
      begin
        now.Font.Name := 'Wingdings';
        now.Font.Color := clRed;
        now.Caption := #80;
        now.Font.Size := 15;
        now.clicked := true;
        now.unsafe := true;
        m_click := m_click + 1;
        If now.mine then m_true := m_true + 1;
      end;
    Panel1.Caption := IntToStr(mines_count - m_click);
    If (m_click = mines_count) or (opened = size*size - mines_count) then endgame := true;
    If endgame then
    begin
      MainForm.Timer1.Enabled := false;
      If ((m_click = m_true) and (m_click = mines_count)) or (opened = size*size - mines_count) then
      begin
        Panel1.Font.Name := 'Wingdings';
        Panel1.Caption := #74;
        ShowMessage('You win!' + #$D + 'your time - ' + IntToStr(time) + ' sec');
        ShowAll;
      end
      else
      begin
        Panel1.Font.Name := 'Wingdings';
        Panel1.Caption := #76;
        ShowMessage('You lose!' + #$D + 'your time - ' + IntToStr(time) + ' sec');
        ShowAll;
      end;
    end;
  end;
end;

procedure TForm1.Timer1Timer(Sender: TObject);
begin
  time := time + 1;
  T := time / 24 / 60 / 60;
  MainForm.Panel2.Caption := TimeToStr(T);
end;

end.
Bayazet вне форума Ответить с цитированием
Старый 17.12.2008, 16:48   #5
Bayazet
Форумчанин
 
Регистрация: 08.12.2008
Сообщений: 156
По умолчанию

нет, как я понял, необходимо создать компонент, который можно поместить на форму, задать несколько параметров и запустить.

но как можно на форму поместить компонент, прародителем которого является форма?о.О
может, стоит прародителем сделать TPanel, но тогда там получается как-то сложно
Bayazet вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц

Опции темы Поиск в этой теме
Поиск в этой теме:

Расширенный поиск


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Создание компонента, определить handle носителя. Deight Компоненты Delphi 6 22.11.2008 09:45
Создание компонента russianstrike Компоненты Delphi 15 01.10.2008 19:22
Создание компонента. Черничный Компоненты Delphi 2 01.06.2008 23:28
Создание собственного компонента Леха207 Помощь студентам 1 03.07.2007 12:45