• Jueves 28 de Marzo de 2024, 16:22

Mostrar Mensajes

Esta sección te permite ver todos los posts escritos por este usuario. Ten en cuenta que sólo puedes ver los posts escritos en zonas a las que tienes acceso en este momento.


Mensajes - luchojimenez

Páginas: [1] 2 3
1
C/C++ / Re:curva de koch en c++
« en: Sábado 30 de Junio de 2012, 02:38 »
Código: [Seleccionar]
/*El siguiente programa ha sido probado y testeado bajo MS-DOS*/
/*Programado en Borland C++ 5.0*/
/*Grafica el Fractal de Von Koch en forma recursiva.*/


#include <stdio.h>
#include <conio.h>
#include <graphics.h>
#include <math.h>
#define PI 3.14159

/************************Funciones*****************/

/*Dibuja una linea de longitud r y angulo angulo*/

void draw(double r,double angulo);

/*Simplemente arma el denominado copo de Koch */

void copoKoch(int orden, double r);

/*Grafica la curva de Von Koch en forma recursiva como es de esperarse*/

void koch(int orden,double r,double angulo);

/*Inicia el modo grafico*/

int iniModoGrafico(int *X_max, int *Y_max);

/****************************************************/
int
main(void)
{


  int Xm,Ym;
  float lado;  /*Longitud de cada lado de */
  int orden;  /*Indica el orden del fractal.Orden 0 es el caso Base*/


  printf("Ingrese el orden: ");
  scanf("%d",&orden);

  printf("Ingrese el lado: ");
  scanf("%f",&lado);

  iniModoGrafico(&Xm,&Ym);
  moveto( ((Xm+1)/2)-(Xm+1)/4,((Ym+1) /2)+(Ym+1)/4);

  copoKoch(orden,lado);

   getch();
   closegraph();

return 0;

}

/**************************/
void copoKoch(int orden, double r)
{
    koch(orden,r,PI/3);
    koch(orden,r,-PI/3);
    koch(orden,r,PI);

}
/**************************/
void draw(double r,double angulo)
{
     linerel(r*cos(angulo), -r*sin (angulo));

}
/*********************************/

int iniModoGrafico(int *X_max, int *Y_max)
{
   int controlador = DETECT, modo, numerror;

   initgraph(&controlador, &modo, "C:\\BC5\\BGI");
numerror = graphresult();   /*Si queres podes usar numerror*/

   if (numerror != grOk)            /* grOk vale 0 si no hay error */
      return numerror;

   *X_max = getmaxx();
   *Y_max = getmaxy();

   return 0;
}
/**************************/
void koch(int orden,double r,double angulo)
{
   if(orden==0)
     draw(r,angulo);

   else
   {
     koch(orden-1,r/3,angulo);
     koch(orden-1,r/3,angulo+(PI/3));
     koch(orden-1,r/3,angulo-(PI/3));
     koch(orden-1,r/3,angulo);
   }

}

/**************************/





2
C/C++ / Re:curva de koch en c++
« en: Sábado 30 de Junio de 2012, 02:37 »
bueno creo  logre encontrar una en la web un codigo que dibuja el copo de koch me sera muy util para empezar a dibujar otro tipos de figuras co0n funciones recursivas

3
C/C++ / Re:curva de koch en c++
« en: Miércoles 27 de Junio de 2012, 18:14 »
funcion  inciar  curva de  koch algoritmo
Iniciar_Koch( Punto_Inicial, Longitud, Número_Iteraciones )

   1. Declarar: Cursor como un punto y un ángulo
   2. Inicializar Cursor:

       3. Cursor.punto ← Punto_Inicial
       4. Cursor.ángulo ← 0

   5. Dibujar_Koch( Cursor, Longitud, Número_Iteraciones )
   6. Terminar
Código: [Seleccionar]

void koch()

 {
float x ,y,lon,tet ;
int n_i;
x=100;
y=200;

tet=0;
dibujar_koch(x,y,lon,n_i,ang);
}   


4
C/C++ / Re:curva de koch en c++
« en: Miércoles 27 de Junio de 2012, 18:02 »
esta otra funcion avanzar es mucho mas  rapida  solo reemplace  la funcion putpixel(x,y14) por la  funcion line
Código: [Seleccionar]
void f(double x1,double y1,double ang,double d1)
{
    double x,y;
   
   
   
   
     
    d1=100;
   
   

    x=x1 + cos(ang)*d1;
    y=y1 + sin(ang)*d1;
       
   
     

    setcolor(14);
    line(x1,y1,x,y);


   
}

5
C/C++ / Re:curva de koch en c++
« en: Miércoles 27 de Junio de 2012, 17:37 »
ahora voy a intentar  realizar  la siguiente  funcion el cual tenemos por algoritmo en borland c++

Real Avanzar( Cursor, D )

   1. Declarar P como un punto: (x,y)
   2. P.x ← Cursor.punto.x + D*cos( Cursor.ángulo )
   3. P.y ← Cursor.punto.y + D*sen( Cursor.ángulo )
   4. Dibujar_Línea( Cursor.punto.x, Cursor.punto.y, P.x, P.y )
   5. Terminar( P )


si  me equivoco por favor corregirme

Código: [Seleccionar]
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<graphics.h>
#include<dos.h>
#define pi 3.141516

struct cursor
{
float x;
float y;
float ang;
};
float avanzar(float*cursor,D)
{
    struct punto{
        float x;
        float y;
    };
   
punto= new cursor;
p=new punto;
   
p.x=Cursor.punto.x + D*cos( Cursor.ángulo );
p.y=Cursor.punto.y + D*sen( Cursor.ángulo );
   
  line(Cursor.punto.x, Cursor.punto.y, P.x, P.y );
   
   
   

   
delete punto;
delete p;
}
void main()
{
   
    int gd=DETECT,gm;
    initgraph(&gd,&gm," ");
   
    closegraph();
}


todfavia no es funcional hay que depurar  y  solo  estoy confeccionando  las funciones
bueno estoy trabajando en codigo sobre las curvas de koch en c++  y borland c++ 5.5 todavia no he  logrado resultados  validos mas  sin embargos  les adjunto lo que he trabajado ahsta  ahora para    a ver  si alguien por  hay  puede hacerme  una correcion  de lo estoy  haciendo
Código: [Seleccionar]
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<graphics.h>
#include<math.h>
#define pi 3.141516

class tortuga{
    private:
    double x;
    double y;
    double ang;
    public:
    void tortuga(double x,double y,double ang)
{
    tortuga.x=x;
    tortuga.y=y;
    tortuga.ang=ang*pi/180;
}
void salta(double distancia)
{
double xx=x+distancia*cos(ang);
double yy=y-distancia*sin(ang);
salta(xx, yy);
}
void salta(double x, double y)
    {
this.x=x;
this.y=y;
}
 void gira(double ang)
{
    this.angulo+=angulo*pi/180;

}
void traza(double distancia){
double xx=x+distancia*Math.cos(angulo);
double yy=y-distancia*Math.sin(angulo);
Line(xx, yy, x,y);
salta(xx, yy);
}
   
};
void generaKoch(int nivel, double distancia){
if(nivel==0){
tortuga.traza(distancia);
}else{
generaKoch(nivel-1, distancia/3);
tortuga::gira(60.0);
generaKoch(nivel-1, distancia/3);
tortuga::gira(-120.0);
generaKoch(nivel-1, distancia/3);
tortuga:gira(60);
generaKoch(nivel-1, distancia/3);
}
}

void main()
{
int gdriver = DETECT, gmode,n=6;
    double d=50;
initgraph(&gdriver, &gmode, "c:\\tc\\bgi");
   
    generaKoch(n,d);
    system("pause");
closegraph();
}




aunque tambien trabaje  este funcion  la proimera no estoy seguro si funciona  no la he probado aun
Código: [Seleccionar]


void f(double x1,double y1,double D,double ang)
{
    double x,y;
   
   
   
   
     
    D=0;
   
    do
    {

    x=x1 + cos(ang)*D;
    y=y1 - sin(ang)*D;
       
    putpixel(x,y,14);
     

   
    D=D+0.005;
       
    }while(D<=100);

 

   
}



6
C/C++ / Re:curva de koch en c++
« en: Miércoles 27 de Junio de 2012, 17:10 »
bueno como nadie  se ha animado ha colaborarme  yo voy a tomar  este post  como una bitacora y referencias para futuros trabajos que lo requieran.
por otro lado navegando por internet  encontre este mate  en la pagina de c.conclase.net




La curva de Koch se construye dividiendo un segmento en tres partes iguales. El segundo segmento - el segmento del medio - forma la base de un triángulo equilátero, pero sin representar este segmento - la base. Esto significa que tenemos un segmento horizontal seguido de dos segmentos, estos dos últimos en forma de triángulo, y luego seguido de un tercer segmento horizontal. Esta estructura es la primitiva para construir esta curva. En siguientes repeticiones, cada segmento de esta curva primitiva es a su vez sometido al mismo algoritmo: segmento horizontal seguido de dos segmentos terminando en la "punta" de un triángulo equilátero y seguido por un tercer segmento horizontal.

La estructura primitiva se puede definir usando la siguiente regla o axioma de producción:

A → AIADDAIA,

donde A indica avanzar, lo cual implica trazar una línea recta,

I es girar a la izquierda, y

D es girar a la derecha.

En el caso de la curva de Koch, cada giro se hace con un ángulo de 60° = π/3 radianes. Los ángulos son 60° porque la curva de Koch se construye en base a un triángulo equilátero. Todos los ángulos de un triángulo equilátero son 60°.

Podemos observar el estado inicial de la curva de Koch, que simplemente es una línea recta, en la  Siguiendo la regla que tenemos, avanzamos una sola vez.
Para la primera iteración, obtenemos la secuencia: AIADDAIA con un ángulo de giro de 60°. Realmente estamos sustituyendo la regla de avanzar, inicialmente establecida, por la secuencia descrita por la regla de producción:

   1. Avanzar el primer tercio.
   2. Girar 60° a la izquierda.
   3. Avanzar otro tercio.
   4. Girar 60° a la derecha.
   5. Girar 60° a la derecha.
   6. Avanzar otro tercio.
   7. Girar 60° a la izquierda.
   8. Avanzar el último tercio.
En la segunda iteración, realizamos el mismo método basándonos en nuestra regla de producción. Aplicamos: A → AIADDAIA para cada 'A'. Esto implica que sustituimos cada 'A' por su definición para lograr el siguiente producto: AIADDAIA I AIADDAIA DD AIADDAIA I AIADDAIA. He aquí el elemento recursivo. Al seguir esta regla obtenemos una imagen

odríamos reescribir la definición de esta regla para reflejar la recursividad:

A0 → Avanzar

An+1 → AnIAnDDAnIAn

donde n indica el número de repeticiones.

Para trazar estas líneas y seguir la regla de producción, nos basamos en la idea de un cursor gráfico. Este cursor contiene una pareja de coordenadas que describe su posición actual y un ángulo que describe su orientación. Necesitamos definir previamente la longitud inicial de A0. Cada vez que "avancemos", calculamos la siguiente posición usando a) la posición actual del cursor como punto inicial, b) tomando un tercio de la longitud inicial, y c) aplicando trigonometría (senos y cosenos) con el ángulo del cursor. La razón de usar un tercio de la longitud es para reducir el tamaño de cada figura para que la imagen final se limite a una distancia adecuada. Si usáramos la misma longitud inicial para cada segmento, entonces obtendríamos una imagen bastante grande cuantas más iteraciones hiciéramos; es decir, cuanto mayor sea el valor de n. La imagen sería tan grande que posiblemente parte de ella sobresalga la pantalla. Por esta razón, optamos por dividir el segmento inicial en partes de menor longitud, para que la curva final sea más manejable.

7
C/C++ / Re:curva de koch en c++
« en: Miércoles 27 de Junio de 2012, 04:27 »
bueno compañeros hastra aqui levo el codigo todavia no soy capaz de lograr que dibuje la curva de koch mas sin embargo llevo avances , estoy tratanto de  utilizar el metodo de la tortuga para  sistemas de lindemayer y crear fractales , en el momento quiero lograr una funcion recursiva  que me dibuje en varios niveles el fractal o curva de koch
Código: [Seleccionar]
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<graphics.h>
#include<dos.h>
#define pi 3.141516

void  f(double x1,double y1,double ang,double d1);
double F(int dx,double x ,double y,double d1);
int k,tet;
void main()
{
   
   
    int gdriver = DETECT, gmode;
   
    initgraph(&gdriver, &gmode, "c:\\tc\\bgi");
         k=0;
   
        for(int n=1,tet=60;n<=15,tet<=500;n++,tet=tet+60)
        F(k=k+tet,100,200,50);
       
   
   
    system("pause");
    closegraph();
   
   
}
void f(double x1,double y1,double ang,double d1)
{
    double x,y;
   
   
   
   
     
    d1=0;
   
    do
    {

    x=x1 + cos(ang)*d1;
    y=y1 + sin(ang)*d1;
       
    putpixel(x,y,14);
     

   
    d1=d1+0.005;
       
    }while(d1<=100);

 

   
}
double F(int dx,double x,double y,double d1)
{
   
    int a=0;
   
    double conv,omeg;
    conv=pi/180;
    omeg=dx*conv;
    dx=omeg;
     
    f(x,y,a,d1);
    f(x+cos(a)*100,y+sin(a)*100,a-dx,d1);
   
    f(x+cos(a)*100+cos(a-dx)*100,y+sin(a)*100+sin(a-dx)*100,a+dx,d1);
    f(x+cos(a)*100+cos(a-dx)*100+cos(a+dx)*100,y+sin(a)*100+sin(a-dx)*100+sin(a+dx)*100,a,d1);
   
   
    return 0;
   
   
   
   
}






8
C/C++ / Re:Leer bmp y convertirlo a matriz
« en: Viernes 22 de Junio de 2012, 21:14 »
interesante proyecto yo tambien en un tiempo  me revente la cabeza con eso , pero   pregunto si es absolutamente nesesario hacerlo  en c++   porque en matlab es muy facil hacerlo,existen comandos que te cargan imagenes  en matriz de arrays  a las cuales les puedes hacer cualquier  modificacion de los arrays y aplicarle convoluciones  que vienen  por defecto con  matlab, la otra  seria trabajar con una libreria  como opengl o direct x  que  traen muchas opciones para  trabajar y manipular graficos

9
Retos / Re:TRIANGULO DE PASCAL
« en: Viernes 22 de Junio de 2012, 21:03 »
por  otro  lado  puedes  mezclar  el combinatorio  con  arreglos bidimensionales , claro  que antes  debes  definir  una funcion que  te resuelva el combinatorio(un poco de estaidsticas) y recuerda mi amigo google es tu amigo

10
Retos / Re:TRIANGULO DE PASCAL
« en: Viernes 22 de Junio de 2012, 21:01 »
bueno debes  considerar  los numeros  combinatorios  el cual modelan perfectamente coeficientes  de cualquier  polinomio te dejo un link para  que eches  un ojito  si te interesa
http://www.estadisticaparatodos.es/taller/triangulo/triangulo.html
por  otro lado se puede  utlizar   una funcion recurrente   a ver si funciona en genral con el si ulitzas  el combinatorio  no es  muy dificil sacar  un  algoritmo

11
C/C++ / curvas bezier y ecuaciones polinomianles en c++
« en: Viernes 22 de Junio de 2012, 20:50 »
le adjunto  este codigo  que modela  las curvas bezier en c++ las cuales  tienen  detras  un fuerte  conceptoi matematico como polinomios  y ecuaciones parametricas
 
Código: [Seleccionar]

#include<graphics.h>
#include<math.h>
#include<conio.h>

#include<dos.h>
#include<stdio.h>
int b3p(int x0,int y0,int x1,int y1,int x2,int y2);

void main()
{
   
    int gd=DETECT,gm;// define  los controladores  de tarjeta grafica en borland c++
   
   
   
   
   
   
    initgraph(&gd,&gm,"");//inicializa el modo grafico
   
     b3p(80,280,180,0,280,280);
   
   
   
    getch();
    closegraph();
}
int b3p(int x0,int y0,int x1,int y1,int x2,int y2)
{
    double x,y,xx,yy,t=0;
    line(x0,y0,x1,y1);
   
    line(x1,y1,x2,y2);
 
       do{
    x=x0*pow(1-t,2)+ x1*2*t*(1-t)+ x2*pow(t,2);//ecuacion parametrica polinomial de grado dos
    y=y0*pow(1-t,2)+ y1*2*t*(1-t)+ y2*pow(t,2);//ecuacion parametrica para el eje Y
    putpixel(x,y,3);//dibuja  un pixel en la cordenadas x,y y color 3
   
        t=t+0.001;//incremento mediante  el cual se dibujaran  los pixeles
   
        }while(t<=2);limite por el cual se dibujan los pixeles
return 0;
}
si alguien puede hacerles  corecciones o aportes  algo  se  agradece

12
C/C++ / girasol en c++ con borland c++ 5.5
« en: Viernes 22 de Junio de 2012, 20:42 »
bueno estoy  tratando de modelar  un girasol en  c++ con  borlannd c++ 5.5  ya logre  modelar lo de adentro  con unas ecuaciones parametricas  que  me consegui  en la web  que modelan perfectamente  los granos del centro de girasol
Código: [Seleccionar]
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<graphics.h>
#include<dos.h>


void main()
{
float x,y,ang,a,r;//xx,yy,ang1,k;
a=2.55;
//k=3.5;
int gdriver = DETECT, gmode,n;   
cout<<"dame el orden del centro del girasol un valor entre 1 a 1500"<<endl;
cin>>n;

initgraph(&gdriver, &gmode, "c:\\tc\\bgi");
   
    //ang1=0;
    if(n<=1500)
    {
       do{
          // do{
        ang=n*137.7;
           r=a*sqrt(n);
        x=380+ r*cos(ang);
        y=290 + r*sin(ang);
        //xx=380+ r*sin(k*ang1)*cos(ang1);
           //yy=290+r*sin(k*ang1)*sin(ang1);
        putpixel(x,y,14);
           
           
       
       
         n++;
           //ang1=ang1+0.0005;               
           //}while(ang1<=70);               
       }while(n<=1700);
       
   }
   

system("pause");
   
closegraph();
}



de repente  alguien pueda  ehcarme una mano  con mi trabajo , el cual es muy autodidsacta  sobre computacion  grafica

13
C/C++ / curva de koch en c++
« en: Viernes 22 de Junio de 2012, 20:35 »
bueno estoy trabajando en codigo sobre las curvas de koch en c++  y borland c++ 5.5 todavia no he  logrado resultados  validos mas  sin embargos  les adjunto lo que he trabajado ahsta  ahora para    a ver  si alguien por  hay  puede hacerme  una correcion  de lo estoy  haciendo
Código: [Seleccionar]
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<graphics.h>
#include<math.h>
#define pi 3.141516

class tortuga{
    private:
    double x;
    double y;
    double ang;
    public:
    void tortuga(double x,double y,double ang)
{
    tortuga.x=x;
    tortuga.y=y;
    tortuga.ang=ang*pi/180;
}
void salta(double distancia)
{
double xx=x+distancia*cos(ang);
double yy=y-distancia*sin(ang);
salta(xx, yy);
}
void salta(double x, double y)
    {
this.x=x;
this.y=y;
}
 void gira(double ang)
{
    this.angulo+=angulo*pi/180;

}
void traza(double distancia){
double xx=x+distancia*Math.cos(angulo);
double yy=y-distancia*Math.sin(angulo);
Line(xx, yy, x,y);
salta(xx, yy);
}
   
};
void generaKoch(int nivel, double distancia){
if(nivel==0){
tortuga.traza(distancia);
}else{
generaKoch(nivel-1, distancia/3);
tortuga::gira(60.0);
generaKoch(nivel-1, distancia/3);
tortuga::gira(-120.0);
generaKoch(nivel-1, distancia/3);
tortuga:gira(60);
generaKoch(nivel-1, distancia/3);
}
}

void main()
{
int gdriver = DETECT, gmode,n=6;
    double d=50;
initgraph(&gdriver, &gmode, "c:\\tc\\bgi");
   
    generaKoch(n,d);
    system("pause");
closegraph();
}




14
Programación de Aplicaciones para Dispositivos / Re:Controlar celular
« en: Domingo 6 de Noviembre de 2011, 04:34 »
bueno la clave es programar en la plataforma del celular  como j2me , android,

15
bueno estoy explorando j2me me gustaria crear un proyectico para el colegio donde doy clases de quimica, el modelo consistiria en un formulario con las letras a,b,c y d y que ese formulario se pueda enviar por el bluetooth  a un servidor que me representen esos datos  creando curvas  que me muestren informacion de los conceptos previos de los estudiantes,en netbeans he hecho cosas pero  hasta el momento no  he probado  con el bluetooth el cual se implemta en java me  mediante  jsr 082, sera que alguien me colabora con ese proyectico

16
C/C++ / colaborar con esta idea en sdl c++
« en: Miércoles 15 de Diciembre de 2010, 20:25 »
lo  quiero  es  hacer es   es  un  interrruptor  en OFF junto  a un bombillo y  que  cuando  se presione  una tecla se ponga  en ON  y  se  encienda  el bombillo, por favor  orientacion en sdl c++, no estoy pidiendo  codigo he  adui  my  gameloop
Código: C++
  1.  
  2.  
  3. while( gameIsRunning ) { //Events //Logic //Rendering }
  4. //Game Loop while( quit == false ) { //Start the frame timer fps.start();
  5. //Events while( SDL_PollEvent( &event ) ) { myDot.handle_input(); if( event.type == SDL_QUIT ) { quit = true; } }
  6. //Logic myDot.move();
  7. //Rendering SDL_FillRect( screen, &screen->clip_rect, SDL_MapRGB( screen->format, 0xFF, 0xFF, 0xFF ) ); myDot.show(); if( SDL_Flip( screen ) == -1 ) { return 1; }
  8. while( fps.get_ticks() < 1000 / FRAMES_PER_SECOND ){} }
  9.  
  10. void Dot::handle_input() { if( event.type == SDL_KEYDOWN ) { switch( event.key.keysym.sym ) { case SDLK_UP: yVel -= DOT_HEIGHT / 2; break; case SDLK_DOWN: yVel += DOT_HEIGHT / 2; break; case SDLK_LEFT: xVel -= DOT_WIDTH / 2; break; case SDLK_RIGHT: xVel += DOT_WIDTH / 2; break; } } else if( event.type == SDL_KEYUP ) { switch( event.key.keysym.sym ) { case SDLK_UP: yVel += DOT_HEIGHT / 2; break; case SDLK_DOWN: yVel -= DOT_HEIGHT / 2; break; case SDLK_LEFT: xVel += DOT_WIDTH / 2; break; case SDLK_RIGHT: xVel -= DOT_WIDTH / 2; break; } } x += xVel; if( ( x < 0 ) || ( x + DOT_WIDTH > SCREEN_WIDTH ) ) { x -= xVel; } y += yVel; if( ( y < 0 ) || ( y + DOT_HEIGHT > SCREEN_HEIGHT ) ) { y -= yVel; } }
  11.  
  12.  
  13.  
  14.  

17
C/C++ / manejo de sprite a partir de hojas de sprite en sdl en c++
« en: Miércoles 15 de Diciembre de 2010, 04:38 »
este ejemplo  lo consegui de la pagina lazy foo  el jemplo tomaron  unos dibujos para  la  animacion  una hoja sprite , a esta animacion se llama  sprite me gustaria  que  una alma  caritativa  me explicase  mucho para poder  impplementar  el codigo  en mis propias  hojas de sprite

Código: C++
  1.  
  2. //The headers
  3. #include "SDL/SDL.h"
  4. #include "SDL/SDL_image.h"
  5. #include <string>
  6.  
  7. //Screen attributes
  8. const int SCREEN_WIDTH = 640;
  9. const int SCREEN_HEIGHT = 480;
  10. const int SCREEN_BPP = 32;
  11.  
  12. //The frames per second
  13. const int FRAMES_PER_SECOND = 10;
  14.  
  15. //The dimenstions of the stick figure
  16. const int FOO_WIDTH = 64;
  17. const int FOO_HEIGHT = 205;
  18.  
  19. //The direction status of the stick figure
  20. const int FOO_RIGHT = 0;
  21. const int FOO_LEFT = 1;
  22.  
  23. //The surfaces
  24. SDL_Surface *foo = NULL;
  25. SDL_Surface *screen = NULL;
  26.  
  27. //The event structure
  28. SDL_Event event;
  29.  
  30. //The areas of the sprite sheet
  31. SDL_Rect clipsRight[ 4 ];
  32. SDL_Rect clipsLeft[ 4 ];
  33.  
  34. //The stick figure
  35. class Foo
  36. {
  37.     private:
  38.     //The offset
  39.     int offSet;
  40.  
  41.     //Its rate of movement
  42.     int velocity;
  43.  
  44.     //Its current frame
  45.     int frame;
  46.  
  47.     //Its animation status
  48.     int status;
  49.  
  50.     public:
  51.     //Initializes the variables
  52.     Foo();
  53.  
  54.     //Handles input
  55.     void handle_events();
  56.  
  57.     //Moves the stick figure
  58.     void move();
  59.  
  60.     //Shows the stick figure
  61.     void show();
  62. };
  63.  
  64. //The timer
  65. class Timer
  66. {
  67.     private:
  68.     //The clock time when the timer started
  69.     int startTicks;
  70.  
  71.     //The ticks stored when the timer was paused
  72.     int pausedTicks;
  73.  
  74.     //The timer status
  75.     bool paused;
  76.     bool started;
  77.  
  78.     public:
  79.     //Initializes variables
  80.     Timer();
  81.  
  82.     //The various clock actions
  83.     void start();
  84.     void stop();
  85.     void pause();
  86.     void unpause();
  87.  
  88.     //Gets the timer's time
  89.     int get_ticks();
  90.  
  91.     //Checks the status of the timer
  92.     bool is_started();
  93.     bool is_paused();
  94. };
  95.  
  96. SDL_Surface *load_image( std::string filename )
  97. {
  98.     //The image that's loaded
  99.     SDL_Surface* loadedImage = NULL;
  100.  
  101.     //The optimized surface that will be used
  102.     SDL_Surface* optimizedImage = NULL;
  103.  
  104.     //Load the image
  105.     loadedImage = IMG_Load( filename.c_str() );
  106.  
  107.     //If the image loaded
  108.     if( loadedImage != NULL )
  109.     {
  110.         //Create an optimized surface
  111.         optimizedImage = SDL_DisplayFormat( loadedImage );
  112.  
  113.         //Free the old surface
  114.         SDL_FreeSurface( loadedImage );
  115.  
  116.         //If the surface was optimized
  117.         if( optimizedImage != NULL )
  118.         {
  119.             //Color key surface
  120.             SDL_SetColorKey( optimizedImage, SDL_SRCCOLORKEY, SDL_MapRGB( optimizedImage->format, 0, 0xFF, 0xFF ) );
  121.         }
  122.     }
  123.  
  124.     //Return the optimized surface
  125.     return optimizedImage;
  126. }
  127.  
  128. void apply_surface( int x, int y, SDL_Surface* source, SDL_Surface* destination, SDL_Rect* clip = NULL )
  129. {
  130.     //Holds offsets
  131.     SDL_Rect offset;
  132.  
  133.     //Get offsets
  134.     offset.x = x;
  135.     offset.y = y;
  136.  
  137.     //Blit
  138.     SDL_BlitSurface( source, clip, destination, &offset );
  139. }
  140.  
  141. void set_clips()
  142. {
  143.     //Clip the sprites
  144.     clipsRight[ 0 ].x = 0;
  145.     clipsRight[ 0 ].y = 0;
  146.     clipsRight[ 0 ].w = FOO_WIDTH;
  147.     clipsRight[ 0 ].h = FOO_HEIGHT;
  148.  
  149.     clipsRight[ 1 ].x = FOO_WIDTH;
  150.     clipsRight[ 1 ].y = 0;
  151.     clipsRight[ 1 ].w = FOO_WIDTH;
  152.     clipsRight[ 1 ].h = FOO_HEIGHT;
  153.  
  154.     clipsRight[ 2 ].x = FOO_WIDTH * 2;
  155.     clipsRight[ 2 ].y = 0;
  156.     clipsRight[ 2 ].w = FOO_WIDTH;
  157.     clipsRight[ 2 ].h = FOO_HEIGHT;
  158.  
  159.     clipsRight[ 3 ].x = FOO_WIDTH * 3;
  160.     clipsRight[ 3 ].y = 0;
  161.     clipsRight[ 3 ].w = FOO_WIDTH;
  162.     clipsRight[ 3 ].h = FOO_HEIGHT;
  163.  
  164.     clipsLeft[ 0 ].x = 0;
  165.     clipsLeft[ 0 ].y = FOO_HEIGHT;
  166.     clipsLeft[ 0 ].w = FOO_WIDTH;
  167.     clipsLeft[ 0 ].h = FOO_HEIGHT;
  168.  
  169.     clipsLeft[ 1 ].x = FOO_WIDTH;
  170.     clipsLeft[ 1 ].y = FOO_HEIGHT;
  171.     clipsLeft[ 1 ].w = FOO_WIDTH;
  172.     clipsLeft[ 1 ].h = FOO_HEIGHT;
  173.  
  174.     clipsLeft[ 2 ].x = FOO_WIDTH * 2;
  175.     clipsLeft[ 2 ].y = FOO_HEIGHT;
  176.     clipsLeft[ 2 ].w = FOO_WIDTH;
  177.     clipsLeft[ 2 ].h = FOO_HEIGHT;
  178.  
  179.     clipsLeft[ 3 ].x = FOO_WIDTH * 3;
  180.     clipsLeft[ 3 ].y = FOO_HEIGHT;
  181.     clipsLeft[ 3 ].w = FOO_WIDTH;
  182.     clipsLeft[ 3 ].h = FOO_HEIGHT;
  183. }
  184.  
  185. bool init()
  186. {
  187.     //Initialize all SDL subsystems
  188.     if( SDL_Init( SDL_INIT_EVERYTHING ) == -1 )
  189.     {
  190.         return false;
  191.     }
  192.  
  193.     //Set up the screen
  194.     screen = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE );
  195.  
  196.     //If there was an error in setting up the screen
  197.     if( screen == NULL )
  198.     {
  199.         return false;
  200.     }
  201.  
  202.     //Set the window caption
  203.     SDL_WM_SetCaption( "Animation Test", NULL );
  204.  
  205.     //If everything initialized fine
  206.     return true;
  207. }
  208.  
  209. bool load_files()
  210. {
  211.     //Load the sprite sheet
  212.     foo = load_image( "foo.png" );
  213.  
  214.     //If there was a problem in loading the sprite
  215.     if( foo == NULL )
  216.     {
  217.         return false;
  218.     }
  219.  
  220.     //If everything loaded fine
  221.     return true;
  222. }
  223.  
  224. void clean_up()
  225. {
  226.     //Free the surface
  227.     SDL_FreeSurface( foo );
  228.  
  229.     //Quit SDL
  230.     SDL_Quit();
  231. }
  232.  
  233. Foo::Foo()
  234. {
  235.     //Initialize movement variables
  236.     offSet = 0;
  237.     velocity = 0;
  238.  
  239.     //Initialize animation variables
  240.     frame = 0;
  241.     status = FOO_RIGHT;
  242. }
  243.  
  244. void Foo::handle_events()
  245. {
  246.     //If a key was pressed
  247.     if( event.type == SDL_KEYDOWN )
  248.     {
  249.         //Set the velocity
  250.         switch( event.key.keysym.sym )
  251.         {
  252.             case SDLK_RIGHT: velocity += FOO_WIDTH / 4; break;
  253.             case SDLK_LEFT: velocity -= FOO_WIDTH / 4; break;
  254.         }
  255.     }
  256.     //If a key was released
  257.     else if( event.type == SDL_KEYUP )
  258.     {
  259.         //Set the velocity
  260.         switch( event.key.keysym.sym )
  261.         {
  262.             case SDLK_RIGHT: velocity -= FOO_WIDTH / 4; break;
  263.             case SDLK_LEFT: velocity += FOO_WIDTH / 4; break;
  264.         }
  265.     }
  266. }
  267.  
  268. void Foo::move()
  269. {
  270.     //Move
  271.     offSet += velocity;
  272.  
  273.     //Keep the stick figure in bounds
  274.     if( ( offSet < 0 ) || ( offSet + FOO_WIDTH > SCREEN_WIDTH ) )
  275.     {
  276.         offSet -= velocity;
  277.     }
  278. }
  279.  
  280. void Foo::show()
  281. {
  282.     //If Foo is moving left
  283.     if( velocity < 0 )
  284.     {
  285.         //Set the animation to left
  286.         status = FOO_LEFT;
  287.  
  288.         //Move to the next frame in the animation
  289.         frame++;
  290.     }
  291.     //If Foo is moving right
  292.     else if( velocity > 0 )
  293.     {
  294.         //Set the animation to right
  295.         status = FOO_RIGHT;
  296.  
  297.         //Move to the next frame in the animation
  298.         frame++;
  299.     }
  300.     //If Foo standing
  301.     else
  302.     {
  303.         //Restart the animation
  304.         frame = 0;
  305.     }
  306.  
  307.     //Loop the animation
  308.     if( frame >= 4 )
  309.     {
  310.         frame = 0;
  311.     }
  312.  
  313.     //Show the stick figure
  314.     if( status == FOO_RIGHT )
  315.     {
  316.         apply_surface( offSet, SCREEN_HEIGHT - FOO_HEIGHT, foo, screen, &clipsRight[ frame ] );
  317.     }
  318.     else if( status == FOO_LEFT )
  319.     {
  320.         apply_surface( offSet, SCREEN_HEIGHT - FOO_HEIGHT, foo, screen, &clipsLeft[ frame ] );
  321.     }
  322. }
  323.  
  324. Timer::Timer()
  325. {
  326.     //Initialize the variables
  327.     startTicks = 0;
  328.     pausedTicks = 0;
  329.     paused = false;
  330.     started = false;
  331. }
  332.  
  333. void Timer::start()
  334. {
  335.     //Start the timer
  336.     started = true;
  337.  
  338.     //Unpause the timer
  339.     paused = false;
  340.  
  341.     //Get the current clock time
  342.     startTicks = SDL_GetTicks();
  343. }
  344.  
  345. void Timer::stop()
  346. {
  347.     //Stop the timer
  348.     started = false;
  349.  
  350.     //Unpause the timer
  351.     paused = false;
  352. }
  353.  
  354. void Timer::pause()
  355. {
  356.     //If the timer is running and isn't already paused
  357.     if( ( started == true ) && ( paused == false ) )
  358.     {
  359.         //Pause the timer
  360.         paused = true;
  361.  
  362.         //Calculate the paused ticks
  363.         pausedTicks = SDL_GetTicks() - startTicks;
  364.     }
  365. }
  366.  
  367. void Timer::unpause()
  368. {
  369.     //If the timer is paused
  370.     if( paused == true )
  371.     {
  372.         //Unpause the timer
  373.         paused = false;
  374.  
  375.         //Reset the starting ticks
  376.         startTicks = SDL_GetTicks() - pausedTicks;
  377.  
  378.         //Reset the paused ticks
  379.         pausedTicks = 0;
  380.     }
  381. }
  382.  
  383. int Timer::get_ticks()
  384. {
  385.     //If the timer is running
  386.     if( started == true )
  387.     {
  388.         //If the timer is paused
  389.         if( paused == true )
  390.         {
  391.             //Return the number of ticks when the timer was paused
  392.             return pausedTicks;
  393.         }
  394.         else
  395.         {
  396.             //Return the current time minus the start time
  397.             return SDL_GetTicks() - startTicks;
  398.         }
  399.     }
  400.  
  401.     //If the timer isn't running
  402.     return 0;
  403. }
  404.  
  405. bool Timer::is_started()
  406. {
  407.     return started;
  408. }
  409.  
  410. bool Timer::is_paused()
  411. {
  412.     return paused;
  413. }
  414.  
  415. int main( int argc, char* args[] )
  416. {
  417.     //Quit flag
  418.     bool quit = false;
  419.  
  420.     //Initialize
  421.     if( init() == false )
  422.     {
  423.         return 1;
  424.     }
  425.  
  426.     //Load the files
  427.     if( load_files() == false )
  428.     {
  429.         return 1;
  430.     }
  431.  
  432.     //Clip the sprite sheet
  433.     set_clips();
  434.  
  435.     //The frame rate regulator
  436.     Timer fps;
  437.  
  438.     //The stick figure
  439.     Foo walk;
  440.  
  441.     //While the user hasn't quit
  442.     while( quit == false )
  443.     {
  444.         //Start the frame timer
  445.         fps.start();
  446.  
  447.         //While there's events to handle
  448.         while( SDL_PollEvent( &event ) )
  449.         {
  450.             //Handle events for the stick figure
  451.             walk.handle_events();
  452.  
  453.             //If the user has Xed out the window
  454.             if( event.type == SDL_QUIT )
  455.             {
  456.                 //Quit the program
  457.                 quit = true;
  458.             }
  459.         }
  460.  
  461.         //Move the stick figure
  462.         walk.move();
  463.  
  464.         //Fill the screen white
  465.         SDL_FillRect( screen, &screen->clip_rect, SDL_MapRGB( screen->format, 0xFF, 0xFF, 0xFF ) );
  466.  
  467.         //Show the stick figure on the screen
  468.         walk.show();
  469.  
  470.         //Update the screen
  471.         if( SDL_Flip( screen ) == -1 )
  472.         {
  473.             return 1;
  474.         }
  475.  
  476.         //Cap the frame rate
  477.         if( fps.get_ticks() < 1000 / FRAMES_PER_SECOND )
  478.         {
  479.             SDL_Delay( ( 1000 / FRAMES_PER_SECOND ) - fps.get_ticks() );
  480.         }
  481.     }
  482.  
  483.     //Clean up
  484.     clean_up();
  485.  
  486.     return 0;
  487. }
  488.  
  489.  
  490.  
  491.  
  492.  

este  es el sprite

lo que me  gustaria saber  es  como hace sdl para procesar el orden de las posiciones  en la hoja de  sprite

18
C/C++ / sobre cgi en c++
« en: Jueves 25 de Noviembre de 2010, 22:57 »
estuve  mirando  unos  tutoriales  sobre  en cgi  en linux, es  intersando  se pueden integrar codigos  c++  a  html , no si  laguien por  ahi  sabe  de  algun  tutorial , y  sobre servidores   gratis  que  soporten esta  opcion

19
C/C++ / funciones en gaphics.h
« en: Miércoles 17 de Noviembre de 2010, 17:16 »
como agregarle  un color por ejemplo rojo al interior del circulo y  fondo gris
 
Código: C++
  1.  
  2. #include <conio.h>
  3.  
  4. #include <stdlib.h>
  5. #include <dos.h>
  6. #include <graphics.h>
  7.  
  8. void main()
  9. {
  10. int monitor=DETECT,modo;
  11. initgraph(&monitor,&modo,"C:\tc\bgi");
  12. do
  13. {
  14. circle(150,240,80);
  15. }
  16. while(!kbhit());
  17. closegraph();
  18.  
  19. }
  20.  

20
C/C++ / Re: Ejercicio de Punteros
« en: Martes 16 de Noviembre de 2010, 20:52 »
el libro  que te pase esta repleto de  ejemplos
Código: C++
  1.  
  2. #include <string.h>
  3. #include <stdlib.h>
  4. #include <stdio.h>
  5. #include <ctype.h>
  6. #include <conio.h>
  7. #include <iostream.h>
  8. #define MAX 5
  9. char *p[MAX], *crecup(void);
  10. int spos=0;
  11. int rpos=0;
  12. char *crecup(void);
  13. void intro(void), calmac(char *c), revisar(void), eliminar(void);
  14. int main()
  15. {
  16. clrscr();
  17. char s[80];
  18. register int t;
  19. for(t=0;t<MAX; ++t) p[t] = NULL; //Inicializa el arreglo
  20. for(;;)
  21. {
  22. cout<<"nnOPCIONES DE ITERACION DE LA COLAnn";
  23. cout<<"I. Introducirn";
  24. cout<<"R. Revisarn";
  25. cout<<"E. Eliminarn";
  26. cout<<"S. Salirnn";
  27. cout<<"Seleccione la opci¢n : ";
  28.  
  29. gets(s);
  30. *s = toupper(*s);
  31. switch(*s)
  32. {
  33. case 'I':
  34. intro();
  35. break;
  36. case 'R':
  37. revisar();
  38. break;
  39. case 'E':
  40. eliminar();
  41. break;
  42. case 'S':
  43. exit(0);
  44. }
  45. }
  46. }
  47. //INTRODUCIR CITAS EN LA COLA
  48. void intro(void)
  49. {
  50. char s[256], *p;
  51. do
  52. {
  53. cout<<"Introduce la cita " <<spos+1 <<" : ";
  54. gets(s);
  55. if(*s==0) break; //no hay entradas
  56. p = (char *)malloc(strlen(s)+1);
  57. if(!p)
  58. {
  59. cout<<"No hay memoria n";
  60. return;
  61. }
  62. strcpy(p, s);
  63. if(*s)calmac(p);
  64. }while(*s);
  65. clrscr();
  66. }
  67. //ver que hay en la cola
  68.  
  69. void revisar(void)
  70. {
  71. clrscr();
  72. register int t;
  73. cout<<endl <<endl <<" LISTADO DE CITAS" <<endl <<endl;
  74. for(t=rpos;t<spos;++t)
  75. cout<<t+1 <<p[t] <<endl;
  76. }
  77. //Eliminar una cita de la cola
  78. void eliminar(void)
  79. {
  80. clrscr();
  81. char *p;
  82. if ((p=crecup())==NULL) return;
  83. cout<<endl <<"CITA ELIMINADA:" <<p;
  84. }
  85. //guardar una cita
  86. void calmac(char *c)
  87. {
  88. if(spos==MAX)
  89. {
  90. cout<<"n La Cola esta llena. Presione Intro n";
  91. return;
  92. }
  93. p[spos] = c;
  94. spos++;
  95. }
  96. //Recuperar una cita
  97. char *crecup(void)
  98. {
  99. if(rpos==spos)
  100. {
  101. cout<<"No hay mas citas n";
  102. return NULL;
  103. }
  104. rpos++;
  105. return p[rpos-1];
  106. }
  107.  
  108.  
  109.  
  110.  

este esd  el ejemplo de   planificador  de citas  lease  el libro  que  ahi  encuentra mas  y   estoy seguro  que  aprendera  a  hacer  colas  por si mismo

21
C/C++ / Re: Ejercicio de Punteros
« en: Martes 16 de Noviembre de 2010, 17:22 »
link  de  un libro  interesante


https://docs.google.com/leaf?id=0B1lz0N ... y=CJzg1KMH

22
C/C++ / representar un arbol binario en modo grafico
« en: Martes 16 de Noviembre de 2010, 04:27 »
nesesito representar  un  estructura tipo arbol binario  este  es mi codigo
Código: C++
  1.  
  2. #include <conio.h>  //De aquí utilizaremos la función kbhit()
  3. #include <stdlib.h> //De aquí sacaremos la función random()
  4. #include <dos.h> //Usaremos esta librería por la función delay(int valor) que nos permite            
  5.                  //establecer un retardo en milisegundos.
  6. #include <graphics.h> //Esta es la librería que nos permite usar gráficos.
  7.  
  8. void main()
  9. {
  10.  int gdriver=DETECT, gmode, contador=0;
  11.  initgraph(&gdriver,&gmode,"C:\BORLANDC\BGI");  //Iniciamos el modo gráfico.
  12. setbkcolor(11);
  13. do
  14. {
  15.  
  16. setbkcolor(11);
  17. setcolor(11);
  18. setlinestyle(0,0,2);
  19. circle(450, 240,20);
  20. line(290,120,445,220);
  21.  
  22.  
  23.  
  24.  
  25. setcolor(11);
  26. setlinestyle(0,0,2);
  27. circle(270, 120,20);
  28. line(270,125,150,240);
  29. setfillstyle(1,RED);
  30.  
  31. setcolor(11);
  32. setlinestyle(0,0,2);
  33. circle(150,240,20);
  34.  
  35. setfillstyle(1,RED);
  36.  
  37. setcolor(11);
  38. setlinestyle(0,0,2);
  39. circle(110, 290,20);
  40. line(150,240,110,290);
  41. setfillstyle(1,RED);
  42.  
  43. setcolor(11);
  44. setlinestyle(0,0,2);
  45. line(150,240,70,350);
  46. circle(70, 350,20);
  47. setfillstyle(1,RED);
  48.  
  49. setcolor(11);
  50. setlinestyle(0,0,2);
  51. circle(130, 350,20);
  52. line(110,290,130,350);
  53. setfillstyle(1,RED);
  54.  
  55. setcolor(11);
  56. setlinestyle(0,0,2);
  57. circle(190, 350,20);
  58. line(200,300,190,350);
  59. setfillstyle(1,RED);
  60.  
  61. line(150,240,200,300);
  62.  
  63. setcolor(11);
  64. setlinestyle(0,0,2);
  65. circle(250, 350,20);
  66. line(200,300,250,350);
  67. setfillstyle(1,RED);
  68.  
  69.  
  70. setcolor(11);
  71. setlinestyle(0,0,2);
  72. circle(200, 290,20);
  73. setfillstyle(1,RED);
  74.  
  75. setcolor(11);
  76. setlinestyle(0,0,2);
  77. circle(410, 290,20);
  78. line(410,290,445,240);
  79. setfillstyle(1,RED);
  80.  
  81. setcolor(11);
  82. setlinestyle(0,0,2);
  83. circle(490, 290,20);
  84. line(490,290,445,240);
  85. setfillstyle(1,RED);
  86.  
  87. }
  88. while(!kbhit());  //Si se pulsa alguna tecla, salimos del programa.
  89.  
  90.  closegraph();     //Cerramos el modo gráfico.
  91. }
  92.  
  93.  

por  favor  colabremem quw  hasta  aqui llegue  ahora nesesito  ingresarle  los  numeros  al interior  de  circuferencencias, rellenar  con color los circulos  tal  y como seria  en un arbol  binario , en los tres  recorridos , inorden,postorden y preorden

23
C/C++ / Re: funcion de pila solo me muestra un elemento
« en: Miércoles 20 de Octubre de 2010, 20:37 »
en ese caso perdone  amigo

24
C/C++ / Re: funcion lista para trbajar con ficheros
« en: Miércoles 20 de Octubre de 2010, 17:06 »
pero hay que  crear  ficheros  FILE*biblio por ejemplo, y para guardar el contenido  de la memoria dinamica

25
C/C++ / funcion lista para trbajar con ficheros
« en: Miércoles 20 de Octubre de 2010, 16:51 »
me  encantaria  que  esta funcion  guardara  el contenido de la memoria  dinamica   en un fichero de texto, no se por donde empezar


Código: C++
  1.  
  2. void ingresar(void)
  3. {
  4. struct libro *b;
  5. char n;
  6. system("cls");
  7.  
  8.  
  9. b = (struct libro *)malloc(sizeof(struct libro));
  10. do
  11.   {
  12. system("cls");
  13. if(!b)
  14. {
  15. cout<<endl <<"no hay memoria";
  16. return;
  17. }
  18.  
  19. leecad("nIntroduce el nombre del libro: ", b->nomlib, 50);
  20. if(!b->nomlib[0]) break; //parar el proceso
  21. leecad("Introduce el autor del libro: ", b->autlib, 50);
  22. leecad("Introduce la editorial del libro: ", b->editlib, 50);
  23. leecad("Introduce el codigo ISBN: ", b->cod,30);
  24. dl_insert(b, &ppio, &final);
  25. gotoxy(5,15);cout<<"Para introducir otro libro intro S/N"<<endl;
  26. gotoxy(5,16);cin>>n;
  27.  
  28. }
  29. while((n=='s')||(n=='S'));
  30. menu();
  31. clrscr();
  32. }
  33.  
  34.  

Páginas: [1] 2 3