Foros Club Delphi

Foros Club Delphi (https://www.clubdelphi.com/foros/index.php)
-   OOP (https://www.clubdelphi.com/foros/forumdisplay.php?f=5)
-   -   Pilas y tshape (https://www.clubdelphi.com/foros/showthread.php?t=78897)

PaulaGV 23-05-2012 18:54:32

Pilas y tshape
 
hola!!!les cuento que estoy trabando con una pila y esta pila contiene shape, primero tengo que crear o modificar tantos shape como el usuario quiera(figuras geométricas, color de la figura, borde de la figura), a medida que los crea el programita los apila, luego cuando el usuario lo desee tengo que mostrar esa pila de figuras geométricas en el form.
Mi problema es el siguiente:

1-mi idea al comienzo, era crear una función a la que le envié un shape y que me lo devuelva ya modificado.Pero cuando quise instanciar la función no me deja, es decir en esta parte:
Código Delphi [-]
type
  TForm1 = class(TForm)
    Button1: TButton;
    Shape1: TShape;
    Button2: TButton;
    procedure FormCreate(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    function crearFigura(f:tshape):tshape;
  private
    { Private declarations }
  public
    { Public declarations }
  end;
2-entonces pense otra solucion: en un procedimiento,modificar un shape que ya coloque en el form, insertarlo en la pila, y crear un nuevo shape. Pero tampoco funciona, por que como dije antes no muestra ninguna figura al final:
-----------------------------------------------
//procedimiento que dasapila
Código Delphi [-]
procedure TForm1.Button3Click(Sender: TObject);
var
figura:TShape;
begin
while pila.Count>0 do
figura:=TShape(pila.pop);
figura.Parent:=Form1;
end;
----------------------------
//procedimiento que modifica la figura
Código Delphi [-]
Procedure TForm1.crearfigura;
begin
with Shape1 do
begin
  Brush.Color:=RGB(Random(255),Random(255),Random(255));
  case Random(6) of
  1:begin
  Shape:= stCircle;
  ListBox1.Items.Add('Circulo');
  end;
  2:begin
  Shape:=stRectangle;
  ListBox1.Items.Add('Rectangulo');
  end;
  3:begin
  Shape:=stSquare;
  ListBox1.Items.Add('cuadrado');
  end;
  4:begin
  Shape:=stRoundRect;
  ListBox1.Items.Add('Rectangulo bordes redondeado');
  end;
  5:begin
   Shape:=stEllipse;
  ListBox1.Items.Add('elipse');
  end;
  6:begin
Shape:=stRoundSquare;
  ListBox1.Items.Add('cuadrado bordes redondeado');
  end;
  end;
  case Random(6) of
  1:Pen.Style:=psSolid;
  2:Pen.Style:=psDash;
  3:Pen.Style:=psDot;
  4:Pen.Style:=psDashDot;
  5:Pen.Style:=psDashDotDot;
  6:Pen.Style:=psClear;
  end;

end;
end;
-----------------------------------------------
//insertar figura en la pila
Código Delphi [-]
procedure TForm1.Button1Click(Sender: TObject);
var
fig:tshape;
begin
crearFigura;
fig:=Shape1;
pila.Push(TObject(fig));
tshape.Create(Shape1);
end;
------------------------------------------------
//creo la pila

Código Delphi [-]
procedure TForm1.FormCreate(Sender: TObject);
begin
pila:=tstack.Create;
end;

no se si estoy trabajando bien la manera en que apilo y desapilo, por que no puedo lograr que las figuras aparezcan en el form, así que o no apila nunca, o no desapila, o estoy mostrando de manera incorrecta la pila de figuras.

desde ya muchas gracias!!!:D

Casimiro Notevi 23-05-2012 20:08:17

A ver si alguien puede echarte una mano.
Por cierto, recuerda poner títulos descriptivos a tus preguntas, gracias :)

ecfisa 23-05-2012 20:44:01

Hola Paula.

Espero haber entendido lo que deseas hacer... de todos modos te pongo un ejemplo que tal vez te sirva de guía:

Código Delphi [-]
...
implementation

uses Contnrs, TypInfo;

var
  Stack: TStack;

procedure TForm1.FormCreate(Sender: TObject);
begin
  Randomize;
  Stack:= TStack.Create;
end;

procedure TForm1.PushShapes(Cant: Integer);
var
  Shape: TShape;
  i: Integer;
begin
  for i:= 1 to Cant do
  begin
    Shape:= TShape.Create(Self);
    Shape.Left:= 300;
    Shape.Top := 50;
    Shape.Height:= 150;
    Shape.Width := 150;
    Shape.Brush.Color:= RGB(Random(255),Random(255),Random(255));
    Shape.Shape:= TShapeType(Random(7));
    Shape.Pen.Style:= TPenStyle(Random(7));
    ListBox1.Items.Add(Copy(GetEnumName(TypeInfo(TShapeType),Ord(Shape.Shape)),3,MaxInt));
    Stack.Push(Shape);
  end;
end;

procedure TForm1.btnPushClick(Sender: TObject);
begin
  PushShapes(10);
end;

procedure TForm1.btnPopClick(Sender: TObject);
begin
  if Stack.Count > 0 then
  begin
    TShape(Stack.Pop).Parent:= Self;
    ListBox1.Items.Delete(ListBox1.Count-1);
  end;
end;

procedure TForm1.FormDestroy(Sender: TObject);
var
  i: Integer;
begin
  for i:= Stack.Count-1 downto 0 do 
    Stack.Pop;
  Stack.Free;
end;
Para hacer mas reducido el código usé la función GetEnumNames, pero tiene la contra que pone en el ListBox el nombre de la figura en inglés.

Saludos.

PaulaGV 23-05-2012 22:24:08

pilas y tshape
 
hola ecfisa!!! agradezco mucho tu respuesta, es muy completa, diría que demasiado para mi nivel de conocimientos...si no es mucho pedir, me podrías decir que estoy haciendo mal en el código que subí? así puedo aprender de mis errores, en vez de solo implementar tu respuesta...:D
mas que nada el tema de insertar el shape en la pila, sacarlo y mostrarlo en el form.

PaulaGV 23-05-2012 22:52:31

pilas y shape
 
probé el código, y esta muy bueno, pero no es exactamente lo que yo quiero hacer.
1-tengo tres botones "agregar figura a la pila", "mostrar pila" y "borra figura".
2-tengo un listbox, en donde, se colocan los nombres de cada figura.
3-tengo un shape, donde se visualiza las figuras.
4-entonces cada vez que presiono "agregar figura a la pila", aleatoriamente se genera la figura, y se coloca el respectivo nombre en el listbox, la imagen correspondiente en el shape, e inserto la imagen en la pila. Esto lo puedo repetir tantas veces como quiera.
5-luego, recién cuando presiono "mostrar pila" aparecen todas las imágenes que inserte en la pila anteriormente, en el form, no se si es posible que, aunque las imágenes queden superpuestas, aun así que se vean las que estaban abajo de ellas, como que cada vez que se la apila una figura, la siguiente se apila "corriendoce" un poquito a la izquierda(por ejemplo)para que se vea la de abajo(solo un pequeño borde).
6-cuando presiono "borrar figura" la pila y el listbox quedan vacios.

PaulaGV 24-05-2012 03:53:56

pilas y shape
 
holaaa!:D
bueno, les cuento que puede acercarme mucho mas a lo que quería hacer!igual me faltan un par de cositas.
acá esta el código:
Código Delphi [-]
var
  Form1: TForm1;
  pila:TStack;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
figura:TShape;
begin
figura:=TShape.Create(Self);
    figura.Left:= 200;
    figura.Top := 150;
    figura.Height:= 150;
    figura.Width := 250;
figura.Brush.Color:=RGB(Random(255),Random(255),Random(255));

case Random(6) of
  1:begin
  figura.shape:= stCircle;
  ListBox1.Items.Add('Circulo');
  Shape1.Brush.Color:=figura.Brush.Color;
  Shape1.Shape:=figura.Shape;
  end;
  2:begin
  figura.shape:=stRectangle;
  ListBox1.Items.Add('Rectangulo');
  Shape1.Brush.Color:=figura.Brush.Color;
  Shape1.Shape:=figura.Shape;
  end;
  3:begin
  figura.shape:=stSquare;
  ListBox1.Items.Add('cuadrado');
  Shape1.Brush.Color:=figura.Brush.Color;
  Shape1.Shape:=figura.Shape;
  end;
  4:begin
  figura.Shape:=stRoundRect;
  ListBox1.Items.Add('Rectangulo bordes redondeado');
  Shape1.Brush.Color:=figura.Brush.Color;
  Shape1.Shape:=figura.Shape;
  end;
  5:begin
  figura.Shape:=stEllipse;
  ListBox1.Items.Add('elipse');
  Shape1.Brush.Color:=figura.Brush.Color;
  Shape1.Shape:=figura.Shape;
  end;
  6:begin
  figura.Shape:=stRoundSquare;
  ListBox1.Items.Add('cuadrado bordes redondeado');
  Shape1.Brush.Color:=figura.Brush.Color;
  Shape1.Shape:=figura.Shape;
  end;
end;

  case Random(6) of
  1:begin
  figura.Pen.Style:=psSolid;
  Shape1.Pen.Style:=figura.Pen.Style;
  end;
  2:begin
  figura.Pen.Style:=psDash;
  Shape1.Pen.Style:=figura.Pen.Style;
  end;
  3:begin
  figura.Pen.Style:=psDot;
  Shape1.Pen.Style:=figura.Pen.Style;
  end;
  4:begin
  figura.Pen.Style:=psDashDot;
  Shape1.Pen.Style:=figura.Pen.Style;
  end;
  5:begin
  figura.Pen.Style:=psDashDotDot;
  Shape1.Pen.Style:=figura.Pen.Style;
  end;
  6:begin
  figura.Pen.Style:=psClear;
  Shape1.Pen.Style:=figura.Pen.Style;
  end;
  end;
  pila.Push(figura);
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
ListBox1.Items.Clear;

end;

procedure TForm1.Button3Click(Sender: TObject);
begin
if pila.Count>0 then
begin
  TShape(pila.Pop).Parent:=Self;
  
end;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
pila:=TStack.Create;

end;
end.

ahora lo que quiero hacer es borrar esa pila que se me genero, es decir la que quedo en el form, como podría hacerlo?
después leí en la "ayuda" de delphi que hay una propiedad que se llama AutoSize, pero no la pude aplicar, no me aparece en cuadro de propiedades :confused:
conocen alguna propiedad que le asigne a un shape todos los atributos de otro shape?

ecfisa 24-05-2012 05:42:47

Cita:

Empezado por PaulaGV (Mensaje 433363)
probé el código, y esta muy bueno, pero no es exactamente lo que yo quiero hacer...

Hola Paula.

A ver si con este código nos aproximamos un poco a lo que buscas:
Código Delphi [-]
implementation

uses Contnrs;

var
  Pila: TStack;
  Shape: TShape;

(* Crear Stack, valores iniciales *)
procedure TForm1.FormCreate(Sender: TObject);
begin
  WindowState:= wsMaximized;
  Pila:= Tstack.Create;
  ListBox1.Align:= alLeft;
  Randomize;
end;

(* Agregar un Shape *)
procedure TForm1.btnAgregarClick(Sender: TObject);
begin
 Shape:= TShape.Create(Self);
  with Shape do
  begin
    Height:= 150;
    Width := 250;
    Left:= Random(Self.ClientWidth-500)+250;
    Top := Random(Self.ClientHeight-320)+150;
    Brush.Color:=RGB(Random(255),Random(255),Random(255));
    case Random(6) of
      0:begin
          Shape:= stCircle;
          ListBox1.Items.Add('Circulo');
      end;
      1:begin
          Shape:=stRectangle;
          ListBox1.Items.Add('Rectangulo');
        end;
      2:begin
          Shape:=stSquare;
          ListBox1.Items.Add('cuadrado');
        end;
      3:begin
          Shape:=stRoundRect;
          ListBox1.Items.Add('Rectangulo bordes redondeado');
        end;
      4:begin
          Shape:=stEllipse;
          ListBox1.Items.Add('elipse');
        end;
      5:begin
          Shape:=stRoundSquare;
          ListBox1.Items.Add('cuadrado bordes redondeado');
        end;
    end;
    case Random(6) of
      0:Pen.Style:=psSolid;
      1:Pen.Style:=psDash;
      2:Pen.Style:=psDot;
      3:Pen.Style:=psDashDot;
      4:Pen.Style:=psDashDotDot;
      5:Pen.Style:=psClear;
    end;
    Parent:= Self;
  end;
  pila.Push(Shape);
end;

(* Borrar un Shape *)
procedure TForm1.btnBorrarClick(Sender: TObject);
var
  i: Integer;
begin
  if Pila.Count > 0 then
  begin
    TShape(Pila.Pop).Free;
    ListBox1.Items.Delete(ListBox1.Count-1);
  end;
end;

(* Borrar todos los Shapes *)
procedure TForm1.btnBorraTodoClick(Sender: TObject);
var
  i: Integer;
begin
  for i:= Pila.Count-1 downto 0 do
    TShape(Pila.Pop).Free;
end;

(* Liberar *)
procedure TForm1.FormDestroy(Sender: TObject);
var
  i: Integer;
begin
  for i:= Pila.Count-1 downto 0 do
    TShape(Pila.Pop).Free;
  Pila.Free;
end;

Saludos.

PaulaGV 24-05-2012 18:42:38

genial!!!muchas gracias :D una ultima pregunta!! que exactamente lo que hace esta instrucción Parent:= Self:confused:

ecfisa 24-05-2012 19:54:33

Cita:

Empezado por PaulaGV (Mensaje 433428)
genial!!!muchas gracias :D una ultima pregunta!! que exactamente lo que hace esta instrucción Parent:= Self:confused:

Hola Paula.

La propiedad Parent se introduce en la clase TControl e indica el componente contenedor donde se dibujará la instancia.

Por ejemplo si:
Código Delphi [-]
  Label1.Parent:= Form1;
La etiqueta se dibujará en el contenedor llamado Form1 de la clase TForm.

Otro caso:
Código Delphi [-]
  Button1.Parent:= Panel1;
El botón se dibujará en el contenedor llamado Panel1 de la clase TPanel.

Saludos.

PaulaGV 25-05-2012 03:56:35

muy claras tus respuestas!!!muchas gracias:D se que dije que eran mis ultimas preguntas, pero tengo una mas, la ultima je, para que utilizas Randomize esa instrucción nunca la use.

ecfisa 25-05-2012 04:54:16

Hola Paula.

Te ruego que pongas esta última pregunta en un nuevo hilo. El motivo de poner la consulta en un nuevo hilo, es facilitar las búsquedas temáticas. De manera que si alguien busca por la palabra Randomize, pueda encontrar más facilmente las respuestas.

Saludos y muchas gracias. :)

PaulaGV 25-05-2012 05:03:09

echo,tenes razón, me disculpo!!:o


La franja horaria es GMT +2. Ahora son las 13:44:52.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
Traducción al castellano por el equipo de moderadores del Club Delphi