Exemple #1
0
int main( void )
{
 dword FarFreeMemoryAtStart=(unsigned long)farcoreleft();

 printf("\n\n                        Reliable file system"
          "\n                                  by"
          "\n                                Dvorka"
          "\n"
          "\n                 Compiled at %s, %s\n", __DATE__, __TIME__
       );
 printf(  "                  Starting with far heap: %luB \n", FarFreeMemoryAtStart );

 randomize();







  InitializeSimulation( INIT_WRITE_TABLE, INIT_CREATE_DEVICES );   // create everything new

  FSCreatMasterBoot( 0x80, 512, 1 );
  FSCreatMasterBoot( 0x81, 512, 1 );
  FSCreatMasterBoot( 0x82, 512, 1 );

  // data stripe
  FSCreatPartition( 0x80, 1, 0, 500, ACTIVE_PARTITION );
  // parity stripe
  FSCreatPartition( 0x80, 2, 501, 1023, NONACTIVE_PARTITION );
  // data stripe
  FSCreatPartition( 0x81, 1, 0, 500, NONACTIVE_PARTITION );
  // swap party
  FSCreatPartition( 0x81, 2, 501, 1023, NONACTIVE_PARTITION );
  // data stripe
  FSCreatPartition( 0x82, 1, 0, 500, NONACTIVE_PARTITION );
  // data stripe
  FSCreatPartition( 0x82, 2, 501, 1001, NONACTIVE_PARTITION );

  // format parties
  FSFormat( 0x80, 1, RFS_DATA );
  FSFormat( 0x80, 2, RFS_DATA  );
  FSFormat( 0x81, 1, RFS_DATA );
  FSFormat( 0x81, 2, RFS_SWAP );
  FSFormat( 0x82, 1, RFS_DATA );
  FSFormat( 0x82, 2, RFS_DATA );



 FSOpenFileSystem( SWAP_ON, CACHE_ON, 10000lu );


 // nothing to do...


 FSShutdownFileSystem();







 printf("\n\n Memory statistic:");

 if( FarFreeMemoryAtStart!=((unsigned long) farcoreleft()))
 {
  printf("\n  Deallocation ERROR:");
  Beep(); Beep(); Beep();
 }
 else
  Beep();

 printf(
        "\n  Far free at start: %lu"
        "\n  and now          : %lu"
        "\n\n"
        ,
        FarFreeMemoryAtStart,
        ((unsigned long) farcoreleft())
       );

 printf("\n Bye! \n\n");

 return 0;
}
void main()
{
do{
clrscr();
tab[0]=losowanie();
cout<<"\n\t";
textcolor(14);
cprintf("1");
textcolor(15);
cprintf(". Losowanie \"Du¾ego Lotka\"");
cout<<"\n\t";
textcolor(14);
cprintf("2");
textcolor(15);
cprintf(". Losowanie \"Expres Lotka\"");
cout<<"\n\t";
textcolor(14);
cprintf("3");
textcolor(15);
cprintf(". Losowanie \"Multi Lotka\"");
cout<<"\n\t";
textcolor(14);
cprintf("4");
textcolor(15);
cprintf(". Skre˜lanie kuponu");
cout<<"\n\t";
textcolor(14);
cprintf("5");
textcolor(15);
cprintf(". Wyj˜cie");

do{los=getch();}
while(los<49||los>53);
switch(los)
 {
 case '1':
 clrscr();
 if(kuponduzy)
 {textcolor(15);
 textbackground(0);
 cprintf("Tw¢j kupon: ");
 j=0;
 do{cout<<"\n\t"<<j+1<<". ";
    i=0;
    do{cout<<duzy[j][i];i++;
       if(i!=6){cout<<", ";}
      }
    while(i!=6);
    j++;
   }
 while(j!=5);
 i=0;
  do{ randomize();
     tab[i]=losowanie();j=0;
     while(j!=i||tab[i]==0)
          {if(tab[i]==tab[j]||tab[i]==0)
             {i--;j=i-1;}
              j++;
          }
     i++;
    }
  while(i!=6);
 cout<<"\n\nOto wylosowane liczby: ";
 i=0;
 do{cout<<tab[i];if(i!=5){cout<<", ";}i++;}
 while(i!=6);
 i=j=k=0;
 do{zak[i]=0;i++;}
 while(i!=5);
 i=0;
 do{
    if(duzy[j][i]==tab[k]){zak[j]++;}
    k++;
    if(k==6){i++;k=0;}
    if(i==6){j++;i=0;}
   }
 while(j!=6);
 i=0;
 cout<<"\n\n";
 do{cout<<"\t"<<i+1<<". "<<zak[i]<<" trafionych\n";i++;}
 while(i!=5);
 }
 else{cout<<"Nie masz skre˜lonego kuponu do Du¾ego Lotka.";}
 getch();
 break;

 case '2':
 clrscr();
 if(kuponexpres)
 {
 textcolor(15);
 textbackground(0);
 cprintf("Tw¢j kupon: ");
 j=0;
 do{cout<<"\n\t"<<j+1<<". ";
    i=0;
    do{cout<<expres[j][i];i++;
       if(i!=5){cout<<", ";}
      }
    while(i!=5);
    j++;
   }
 while(j!=5);
 }
 else{cout<<"Nie masz skre˜lonego kuponu do Expres Lotka.";}
 getch();
 break;

 case '3':
 clrscr();
 if(kuponmulti)
 {
 textcolor(15);
 textbackground(0);
 cprintf("Tw¢j kupon: ");
 j=0;
 do{cout<<"\n\t"<<j+1<<". ";
    i=0;
    do{cout<<multi[j][i];i++;
       if(i!=20){cout<<", ";}
      }
    while(i!=20);
    j++;
   }
 while(j!=5);
 }
 else{cout<<"Nie masz skre˜lonego kuponu do Multi Lotka.";}
 getch();
 break;

 case '4':
 clrscr();
 textcolor(14);
 cout<<"\n\t";
 cprintf("1");
 textcolor(15);
 cprintf(". Skre˜lanie r©czne\r");
 textcolor(14);
 cout<<"\n\t";
 cprintf("2");
 textcolor(15);
 cprintf(". Chybiˆ - trafiˆ\n");
 do{skrl=getch();}
 while(skrl<49||skrl>50);
       switch (skrl)
       {
        case '1':
        clrscr();
        cout<<"Jaki kupon skre˜lamy?\n\t";
        textcolor(14);
        cprintf("1");
        textcolor(15);
        cprintf(". Du¾ego Lotka");
        cout<<"\n\t";
        textcolor(14);
        cprintf("2");
        textcolor(15);
        cprintf(". Expres Lotka");
        cout<<"\n\t";
        textcolor(14);
        cprintf("3");
        textcolor(15);
        cprintf(". Multi Lotka");
        do{skrlrecz=getch();}
        while(skrlrecz<49||skrlrecz>51);
        switch(skrlrecz)
              {
               case '1':
               j=0;
               do{clrscr();i=0;
                  cout<<"Dla "<<j+1<<" zakˆadu\n";
                  do{ cout<<"podaj "<<i+1<<" liczb©:\t";
                      cin>>duzy[j][i];i++;
                    }
                  while(i!=6);j++;
                 }
               while(j!=5);
               kuponduzy=1;
               break;

               case '2':
               j=0;
               do{clrscr();i=0;
                  cout<<"Dla "<<j+1<<" zakˆadu\n";
                  do{ cout<<"podaj "<<i+1<<" liczb©:\t";
                      cin>>expres[j][i];i++;
                    }
                  while(i!=5);j++;
                 }
               while(j!=5);
               kuponexpres=1;
               break;

               case '3':
               j=0;
               do{clrscr();i=0;
                  cout<<"Dla "<<j+1<<" zakˆadu\n";
                  do{ cout<<"podaj "<<i+1<<" liczb©:\t";
                      cin>>multi[j][i];i++;
                    }
                  while(i!=20);j++;
                 }
               while(j!=5);
               kuponmulti=1;
               break;
               default : ;
              }
        break;

        case '2':
        clrscr();
        cout<<"W co b©dziesz graˆ?\n\t";
        textcolor(14);
        cprintf("1");
        textcolor(15);
        cprintf(". Du¾y Lotek");
        cout<<"\n\t";
        textcolor(14);
        cprintf("2");
        textcolor(15);
        cprintf(". Expres Lotek");
        cout<<"\n\t";
        textcolor(14);
        cprintf("3");
        textcolor(15);
        cprintf(". Multi Lotek");
        do{skrlchyb=getch();}
        while(skrlchyb<49||skrlchyb>51);
              switch(skrlchyb)
                    {
                     case'1':
                     clrscr();
                     k=0;
                     do{i=0;
                        do{ randomize();
                           duzy[k][i]=losowanie();j=0;
                           while(j!=i||duzy[k][i]==0)
                                {if(duzy[k][i]==duzy[k][j]||duzy[k][i]==0)
                                    {i--;j=i-1;}
                                 j++;
                                }
                           i++;
                          }
                        while(i!=6);k++;
                       }
                     while(k!=5);
                     cout<<"Tw¢j kupon: ";
                     j=0;
                     do{cout<<"\n\t"<<j+1<<". ";
                        i=0;
                        do{cout<<duzy[j][i];i++;
                        if(i!=6){cout<<", ";}
                          }
                        while(i!=6);
                        j++;
                       }
                     while(j!=5);
                     kuponduzy=1;
                     getch();
                     break;
                     case'2':
                     break;
                     case'3':
                     break;
                     default: ;
                    }
        break;
        default : ;
       }
 break;

 }
}
while(los!=53);
/*
cout<<los;
cout<<"Jak¥ liczbe losowaä wykona†: ";
cin>>il;
randomize();

i=0;
do{
tab[i]=random(50);j=0;
  while(j!=i||tab[i]==0)
  {if(tab[i]==tab[j]||tab[i]==0)
       {i--;j=i-1;}
       j++;
  }
  i++;
  }
while(i!=6);
i=0;
cout<<" Losowanie nr "<<k+1<<":";
do{
cout<<"\t\b\b"<<tab[i]<<",";
  i++;
  }
while (i!=6);
cout<<endl;
*/
clrscr();
cout<<"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\t\tÉÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ»\n"
<<"\t\t\tº Program napisaˆ:          º\n"
<<"\t\t\tº  Krzysztof Szumny - Noisy º\n"
<<"\t\t\tº  [email protected]        º\n"
<<"\t\t\tº  gg: 1391200              º\n"
<<"\t\t\tÈÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍͼ\n";
delay(2000);


}
Exemple #3
0
/*
 * main:
 *	Drive the sucker.  There are two main modes -- either we store
 *	the seek pointers, if the table is to be sorted or randomized,
 *	or we write the pointer directly to the file, if we are to stay
 *	in file order.  If the former, we allocate and re-allocate in
 *	CHUNKSIZE blocks; if the latter, we just write each pointer,
 *	and then seek back to the beginning to write in the table.
 */
int
main(int ac, char *av[])
{
    char *sp, *nsp, dc;
    FILE *inf, *outf;
    off_t last_off, pos, *p;
    size_t length;
    int first;
    uint32_t cnt;
    STR *fp;
    static char string[257];

    setlocale(LC_ALL, "");

    getargs(ac, av);		/* evalute arguments */
    dc = Delimch;
    if ((inf = fopen(Infile, "r")) == NULL) {
        perror(Infile);
        exit(1);
    }

    if ((outf = fopen(Outfile, "w")) == NULL) {
        perror(Outfile);
        exit(1);
    }
    if (!STORING_PTRS)
        fseek(outf, (long)sizeof(Tbl), SEEK_SET);

    /*
     * Write the strings onto the file
     */

    Tbl.str_longlen = 0;
    Tbl.str_shortlen = 0xffffffff;
    Tbl.str_delim = dc;
    Tbl.str_version = VERSION;
    first = Oflag;
    add_offset(outf, ftello(inf));
    last_off = 0;
    do {
        sp = fgets(string, 256, inf);
        if (sp == NULL || (sp[0] == dc && sp[1] == '\n')) {
            pos = ftello(inf);
            length = (size_t)(pos - last_off) -
                     (sp != NULL ? strlen(sp) : 0);
            last_off = pos;
            if (length == 0)
                continue;
            add_offset(outf, pos);
            if ((size_t)Tbl.str_longlen < length)
                Tbl.str_longlen = length;
            if ((size_t)Tbl.str_shortlen > length)
                Tbl.str_shortlen = length;
            first = Oflag;
        }
        else if (first) {
            for (nsp = sp; !isalnum((unsigned char)*nsp); nsp++)
                continue;
            ALLOC(Firstch, Num_pts);
            fp = &Firstch[Num_pts - 1];
            if (Iflag && isupper((unsigned char)*nsp))
                fp->first = tolower((unsigned char)*nsp);
            else
                fp->first = *nsp;
            fp->pos = Seekpts[Num_pts - 1];
            first = false;
        }
    } while (sp != NULL);

    /*
     * write the tables in
     */

    fclose(inf);
    Tbl.str_numstr = Num_pts - 1;

    if (Cflag)
        Tbl.str_flags |= STR_COMMENTS;

    if (Oflag)
        do_order();
    else if (Rflag)
        randomize();

    if (Xflag)
        Tbl.str_flags |= STR_ROTATED;

    if (!Sflag) {
        printf("\"%s\" created\n", Outfile);
        if (Num_pts == 2)
            puts("There was 1 string");
        else
            printf("There were %u strings\n", Num_pts - 1);
        printf("Longest string: %u byte%s\n", Tbl.str_longlen,
               Tbl.str_longlen == 1 ? "" : "s");
        printf("Shortest string: %u byte%s\n", Tbl.str_shortlen,
               Tbl.str_shortlen == 1 ? "" : "s");
    }

    rewind(outf);
    Tbl.str_version = htobe32(Tbl.str_version);
    Tbl.str_numstr = htobe32(Tbl.str_numstr);
    Tbl.str_longlen = htobe32(Tbl.str_longlen);
    Tbl.str_shortlen = htobe32(Tbl.str_shortlen);
    Tbl.str_flags = htobe32(Tbl.str_flags);
    fwrite((char *)&Tbl, sizeof(Tbl), 1, outf);
    if (STORING_PTRS) {
        for (p = Seekpts, cnt = Num_pts; cnt--; ++p)
            *p = htobe64(*p);
        fwrite(Seekpts, sizeof(*Seekpts), (size_t)Num_pts, outf);
    }
    fclose(outf);
    exit(0);
}
Exemple #4
0
int main( void )
{
 dword FarFreeMemoryAtStart=(unsigned long)farcoreleft();

 printf("\n\n                        Reliable file system"
          "\n                                  by"
          "\n                            Jarda & Dvorka"
          "\n"
          "\n                 Compiled at %s, %s\n", __DATE__, __TIME__
       );
 printf(  "                  Starting with far heap: %luB \n", FarFreeMemoryAtStart );

 randomize();







 //- work with file system -

 #ifdef CREATE_EVERYTHING_NEW
  InitializeSimulation( TRUE, TRUE );   // create everything new

  FSCreatMasterBoot( 0x80, 512, 1 );
  FSCreatMasterBoot( 0x81, 512, 1 );
  FSCreatMasterBoot( 0x82, 512, 1 );

  // data stripe
  FSCreatPartition( 0x80, 1, 0, 500, ACTIVE_PARTITION  );
  // parity stripe
  FSCreatPartition( 0x80, 2, 501, 1023, NONACTIVE_PARTITION  );
  // data stripe
  FSCreatPartition( 0x81, 1, 0, 500, ACTIVE_PARTITION  );
  // swap party
  FSCreatPartition( 0x81, 2, 501, 1023, NONACTIVE_PARTITION  );
  // data stripe
  FSCreatPartition( 0x82, 1, 0, 500, ACTIVE_PARTITION  );
  // swap party
  FSCreatPartition( 0x82, 2, 501, 1023, NONACTIVE_PARTITION  );

  // format parties
  FSFormat( 0x80, 1, RFS_DATA );
  FSFormat( 0x80, 2, RFS_DATA  );
  FSFormat( 0x81, 1, RFS_DATA );
  FSFormat( 0x81, 2, RFS_SWAP );
  FSFormat( 0x82, 1, RFS_DATA );
  FSFormat( 0x82, 2, RFS_SWAP );

 #else
  InitializeSimulation();               // only init handles,...
 #endif



 // init file system ( inside init of cache )
 FSOpenFileSystem( SWAP_ON, CACHE_ON, 10000lu );







  #ifdef CACHE_TEST;

  word     PackageID=0,
           GetNumber=0,
           i;

  dword    Logical,
           Free;

  void far *Buffer=farmalloc(10*512); if( !Buffer ) exit(0);



  // allocates && creates package ( 0x81 or 1 - it has same effect )
  CacheManAllocateSector( 0x81, 1, 0, 1, Logical, GetNumber, PackageID, FPACK_CREAT );

  word j;
  word Number;


  // PackageID set in previous function
  for( i=1; i<=5; i++ )
  {
   // allocate allocates < logical, logical+6 >
   CacheManAllocateSector( 1, 1, 0lu, 7, Logical, GetNumber, PackageID, FPACK_ADD );


   printf("\n Get number: %u", GetNumber );

   // init buffer for save
   for( j=0; j<10*512; j++ ) ((byte far * )Buffer)[j]=0xCC;

   if( random(5) ) // probably add
    CacheManSaveSector( 1, 1, Logical, 7, PackageID, FPACK_ADD, Buffer );
   else
    CacheManSaveSector( 1, 1, Logical, 7, PackageID, FPACK_CREAT, Buffer );

   // load what's written from cache ( something )
   //  Number=(word)random(7) + 1u;
   Number=7;
   CacheManLoadSector( 1, 1, Logical, Number, PackageID, FPACK_ADD, Buffer );


   if( !random(10) ) // probably not commit
   {
    if( random(2) )
     CacheManCommitPackage( PackageID, FPACK_NOTHING ); // commit
    else
    {
     CacheManCommitPackage( PackageID, FPACK_DELETE );  // commit && del pack

     // create new PackID because in alloc and save used!
     CacheManAllocateSector( 1, 1, 0lu, 7, Logical, GetNumber, PackageID, FPACK_CREAT );

     printf("\n Get number: %u", GetNumber );
    }
   }

   // print free space on device
   GetPartyFreeSpace( 0x81, 1, Free );
   GetPartyFreeSpace( 0x81, 2, Free );
   printf("\n\n ----->");
  }



  farfree(Buffer);

  // UndoAlfLog( 0x81, 1, "TEST.ALF" );

  // RecoverUsingCml( "TEST.CML" );

  // RollbackOkaLog( 1, 1, "11TEST.OKA" );

  // RecoverParty( 1, 1 );

 #endif








  #ifdef CACHE_EXAMPLE;

  int      Handle;
  word     PackageID,
           GetNumber=0,
           i,
           j,
           bytes;

  dword    Previous=0,
	   Logical1,
	   Logical2,
	   Logical;

  #define BUFFER_SIZE 512

  void far *Buffer=farmalloc(BUFFER_SIZE);
  if( !Buffer ) { printf("All1 Error..");exit(0); }

  void far *BufferOut=farmalloc(BUFFER_SIZE);
  if( !BufferOut ) { printf("All2 Error..");exit(0); }


 // now read some nice data to buffer
 if ((Handle = open("input.txt", O_CREAT  | O_RDWR | O_BINARY,
                                   S_IWRITE | S_IREAD           )) == -1)
 { printf("Error.."); return ERR_FS_FATAL_ERROR; }

 if( _dos_read( Handle, Buffer, BUFFER_SIZE, &bytes) != 0 )
 { printf("Error.."); return ERR_FS_FATAL_ERROR; }

 close(Handle);

 // --- begin work ------------------------------------------------
//*
  for(i=0; i<512; i++ ) ((byte far *)Buffer)[i]=0xAA;
  CacheManAllocateSector( 1, 1, 0, 1, Logical1,
			  GetNumber, PackageID, FPACK_CREAT );
  CacheManSaveSector( 1, 1, Logical1, 1u, PackageID, FPACK_ADD, Buffer  );

  for(i=0; i<512; i++ ) ((byte far *)Buffer)[i]=0xBB;
  CacheManAllocateSector( 1, 1, 0, 1, Logical2,
			  GetNumber, PackageID, FPACK_ADD );
  CacheManSaveSector( 1, 1, Logical2, 1u, PackageID, FPACK_ADD, Buffer  );
//*/

  CacheManCompleteCommit( FPACK_DELETE );

//*
 for(i=0; i<512; i++ ) ((byte far *)BufferOut)[i]=0xEE;

 CacheManLoadSector( 1, 1, Logical1, 1u, PackageID, FPACK_CREAT, BufferOut  );

 if ((Handle = open("AA", O_CREAT  | O_RDWR | O_BINARY,
				   S_IWRITE | S_IREAD           )) == -1)
 { printf("Error.."); return ERR_FS_FATAL_ERROR; }

 if( _dos_write( Handle, BufferOut, BUFFER_SIZE, &bytes) != 0 )
 { printf("Error.."); return ERR_FS_FATAL_ERROR; }

 close(Handle);

 // ---

 for(i=0; i<512; i++ ) ((byte far *)BufferOut)[i]=0xEE;

 CacheManLoadSector( 1, 1, Logical2, 1u, PackageID, FPACK_ADD, BufferOut  );

 if ((Handle = open("BB", O_CREAT  | O_RDWR | O_BINARY,
				   S_IWRITE | S_IREAD           )) == -1)
 { printf("Error.."); return ERR_FS_FATAL_ERROR; }

 if( _dos_write( Handle, BufferOut, BUFFER_SIZE, &bytes) != 0 )
 { printf("Error.."); return ERR_FS_FATAL_ERROR; }

 close(Handle);
//*/

 // --- end work ------------------------------------------------


 // save buffer content ------------------------------------------------
 if ((Handle = open("output2.txt", O_CREAT  | O_RDWR | O_BINARY,
                                   S_IWRITE | S_IREAD           )) == -1)
 { printf("Error.."); return ERR_FS_FATAL_ERROR; }

 if( _dos_write( Handle, BufferOut, BUFFER_SIZE, &bytes) != 0 )
 { printf("Error.."); return ERR_FS_FATAL_ERROR; }

 close(Handle);






 farfree(Buffer);

 farfree(BufferOut);


 #endif






 #ifdef STRIP_EXAMPLE

  #define BUFFER_SIZE 512

  #define SECTOR      31

  byte far *Buffer=(byte far *)farmalloc(BUFFER_SIZE);
  if( !Buffer ) { printf("All1 Error..");exit(0); }



  printf("\n\n\n Test: ");

  ReadLogicalSector( 1, SECTOR, Buffer, 1 );

  Buffer[0]=0xAB;
  CLASSICWriteLogicalSector( 1, SECTOR, Buffer, 1 );

  ReadLogicalSector( 1, SECTOR, Buffer, 1 );
  ReadLogicalSector( 1, SECTOR, Buffer, 1 );

  farfree(Buffer);

 #endif



































 FSShutdownFileSystem(); // contains complete commit

 //-------------------------







 printf("\n\n Memory statistic:");

 if( FarFreeMemoryAtStart!=((unsigned long) farcoreleft()))
 {
  printf("\n  Deallocation ERROR:");
  Beep(); Beep(); Beep();
 }
 else
  Beep();

 printf(
        "\n  Far free at start: %lu"
        "\n  and now          : %lu"
        "\n\n"
        ,
        FarFreeMemoryAtStart,
        ((unsigned long) farcoreleft())
       );

 printf("\n Bye! \n\n");

 return 0;
}
Exemple #5
0
/* -------------------------------------------------------------------------------
 * NSGA2                                                       
 * ---------------------------------------------------------------------------- */
int nsga2(int nvar, int ncon, int nobj, double f[], double x[], double g[],
    int nfeval, double xl[], double xu[],	int popsize, int ngen, 
    double pcross_real, double pmut_real, double eta_c, double eta_m, 
    double pcross_bin, double pmut_bin, int printout, double seed)
{
	/* declaration of local variables and structures */
    int i, j;
    int nreal, nbin, *nbits, bitlength; 
    double *min_realvar, *max_realvar;
	double *min_binvar, *max_binvar;
	int *nbinmut, *nrealmut, *nbincross, *nrealcross;
    
    Global global;
    
    population *parent_pop;
    population *child_pop;
    population *mixed_pop;
    
    // "random" numbers seed
    if (seed==0) 
    {  
        // use of clock to generate "random" seed
        time_t seconds;
        seconds=time(NULL);
        seed=seconds;
    }
    
    // Files
	FILE *fpt1;
	FILE *fpt2;
	FILE *fpt3;
	FILE *fpt4;
	FILE *fpt5;
	FILE *fpt6;
    if (printout >= 1)
    {
		fpt1 = fopen("nsga2_initial_pop.out","w");
		fpt2 = fopen("nsga2_final_pop.out","w");
		fpt3 = fopen("nsga2_best_pop.out","w");
		if (printout == 2)
		{
			fpt4 = fopen("nsga2_all_pop.out","w");
		}
		fpt5 = fopen("nsga2_params.out","w");
		fpt6 = fopen("nsga2_run.out","w");
		fprintf(fpt1,"# This file contains the data of initial population\n");
		fprintf(fpt2,"# This file contains the data of final population\n");
		fprintf(fpt3,"# This file contains the data of final feasible population (if found)\n");
		if (printout == 2)
		{
			fprintf(fpt4,"# This file contains the data of all generations\n");
		}
		fprintf(fpt5,"# This file contains information about inputs as read by the program\n");
		fprintf(fpt6,"# This file contains runtime information\n");
	}
    
	// Input Handling
	nreal = nvar;	// number of real variables
	nbin = 0;  	    // number of binary variables
	
    min_realvar = (double *)malloc(nreal*sizeof(double));
    max_realvar = (double *)malloc(nreal*sizeof(double));
    
    j = 0;
    for (i=0; i<nvar; i++)
    {
        min_realvar[j] = xl[i];
        max_realvar[j] = xu[i];
        j += 1;
	}
	
	if (nbin != 0)
	{
        nbits = (int *)malloc(nbin*sizeof(int));
        min_binvar = (double *)malloc(nbin*sizeof(double));
        max_binvar = (double *)malloc(nbin*sizeof(double));
    }
    
    bitlength = 0;
    if (nbin!=0)
    {
        for (i=0; i<nbin; i++)
        {
            bitlength += nbits[i];
        }
    }
    
    // Performing Initialization
    if (printout >= 1)
    {
		fprintf(fpt5,"\n Population size = %d",popsize);
		fprintf(fpt5,"\n Number of generations = %d",ngen);
		fprintf(fpt5,"\n Number of objective functions = %d",nobj);
		fprintf(fpt5,"\n Number of constraints = %d",ncon);
		fprintf(fpt5,"\n Number of variables = %d",nvar);
		fprintf(fpt5,"\n Number of real variables = %d",nreal);
		if (nreal!=0)
		{
			for (i=0; i<nreal; i++)
			{
				fprintf(fpt5,"\n Lower limit of real variable %d = %e",i+1,min_realvar[i]);
				fprintf(fpt5,"\n Upper limit of real variable %d = %e",i+1,max_realvar[i]);
			}
			fprintf(fpt5,"\n Probability of crossover of real variable = %e",pcross_real);
			fprintf(fpt5,"\n Probability of mutation of real variable = %e",pmut_real);
			fprintf(fpt5,"\n Distribution index for crossover = %e",eta_c);
			fprintf(fpt5,"\n Distribution index for mutation = %e",eta_m);
		}
		fprintf(fpt5,"\n Number of binary variables = %d",nbin);
		if (nbin!=0)
		{
			for (i=0; i<nbin; i++)
			{
				fprintf(fpt5,"\n Number of bits for binary variable %d = %d",i+1,nbits[i]);
				fprintf(fpt5,"\n Lower limit of binary variable %d = %e",i+1,min_binvar[i]);
				fprintf(fpt5,"\n Upper limit of binary variable %d = %e",i+1,max_binvar[i]);
			}
			fprintf(fpt5,"\n Probability of crossover of binary variable = %e",pcross_bin);
			fprintf(fpt5,"\n Probability of mutation of binary variable = %e",pmut_bin);
		}
		fprintf(fpt5,"\n Seed for random number generator = %e",seed);
		
		fprintf(fpt1,"# of objectives = %d, # of constraints = %d, # of real_var = %d, # of bits of bin_var = %d, constr_violation, rank, crowding_distance\n",nobj,ncon,nreal,bitlength);
		fprintf(fpt2,"# of objectives = %d, # of constraints = %d, # of real_var = %d, # of bits of bin_var = %d, constr_violation, rank, crowding_distance\n",nobj,ncon,nreal,bitlength);
		fprintf(fpt3,"# of objectives = %d, # of constraints = %d, # of real_var = %d, # of bits of bin_var = %d, constr_violation, rank, crowding_distance\n",nobj,ncon,nreal,bitlength);
		if (printout == 2)
		{
			fprintf(fpt4,"# of objectives = %d, # of constraints = %d, # of real_var = %d, # of bits of bin_var = %d, constr_violation, rank, crowding_distance\n",nobj,ncon,nreal,bitlength);
		}
    }
    
    // 
    global.nreal = nreal;
    global.nbin = nbin;
    global.nobj = nobj;
    global.ncon = ncon;
    global.popsize = popsize;
    global.pcross_real = pcross_real;
    global.pcross_bin = pcross_bin;
    global.pmut_real = pmut_real;
    global.pmut_bin = pmut_bin;
    global.eta_c = eta_c;
    global.eta_m = eta_m;
    global.ngen = ngen;
    global.nbits = nbits;
    global.min_realvar = min_realvar;
    global.max_realvar = max_realvar;
    global.min_binvar = min_binvar;
    global.max_binvar = max_binvar;
    global.bitlength = bitlength;  
    
    //
    nbinmut = 0;
    nrealmut = 0;
    nbincross = 0;
    nrealcross = 0;
    parent_pop = (population *)malloc(sizeof(population));
    child_pop = (population *)malloc(sizeof(population));
    mixed_pop = (population *)malloc(sizeof(population));
    allocate_memory_pop (parent_pop, popsize, global);
    allocate_memory_pop (child_pop, popsize, global);
    allocate_memory_pop (mixed_pop, 2*popsize, global);
    randomize();
    initialize_pop (parent_pop, global);
    
    // First Generation
    if (printout >= 1)
    {
		fprintf(fpt6,"\n\n Initialization done, now performing first generation");
    }
    decode_pop(parent_pop, global);
    evaluate_pop(parent_pop, global);
    assign_rank_and_crowding_distance (parent_pop, global);
    if (printout >= 1)
    {
		report_pop (parent_pop, fpt1, global);
		if (printout == 2)
		{
			fprintf(fpt4,"# gen = 1\n");
			report_pop(parent_pop,fpt4, global);
		}
		
		fprintf(fpt6,"\n gen = 1");
		
		fflush(fpt1);
		fflush(fpt2);
		fflush(fpt3);
		if (printout == 2)
		{
			fflush(fpt4);
		}
		fflush(fpt5);
		fflush(fpt6);
	}
    fflush(stdout);
    
    // Iterate Generations
    for (i=2; i<=ngen; i++)
    {
        selection(parent_pop, child_pop, global, nrealcross, nbincross);
        mutation_pop(child_pop, global, nrealmut, nbinmut);
        decode_pop(child_pop, global);
        evaluate_pop(child_pop, global);
        merge (parent_pop, child_pop, mixed_pop, global);
        fill_nondominated_sort (mixed_pop, parent_pop, global);
        
        /* Comment following three lines if information for all
        generations is not desired, it will speed up the execution */
        if (printout >= 1)
		{
			if (printout == 2)
			{
				fprintf(fpt4,"# gen = %i\n",i);
				report_pop(parent_pop,fpt4, global);
				fflush(fpt4);
			}
			fprintf(fpt6,"\n gen = %i",i);
			fflush(fpt6);
		}
    }
    
    // Output
	if (printout >= 1)
	{
		fprintf(fpt6,"\n Generations finished");
		report_pop(parent_pop,fpt2, global);
		report_feasible(parent_pop,fpt3, global);
		
		if (nreal!=0)
		{
			fprintf(fpt5,"\n Number of crossover of real variable = %i",nrealcross);
			fprintf(fpt5,"\n Number of mutation of real variable = %i",nrealmut);
		}
		if (nbin!=0)
		{
			fprintf(fpt5,"\n Number of crossover of binary variable = %i",nbincross);
			fprintf(fpt5,"\n Number of mutation of binary variable = %i",nbinmut);
		}
		fflush(stdout);
		fflush(fpt1);
		fflush(fpt2);
		fflush(fpt3);
		if (printout == 2)
		{
			fflush(fpt4);
		}
		fflush(fpt5);
		fflush(fpt6);
		fclose(fpt1);
		fclose(fpt2);
		fclose(fpt3);
		if (printout == 2)
		{
			fclose(fpt4);
		}
		fclose(fpt5);
			
	}
	
	// 
    for (i=0; i<popsize; i++)
    {
		if (parent_pop->ind[i].constr_violation == 0.0 && parent_pop->ind[i].rank==1)
        {
			for (j=0; j<nobj; j++)
            {
                f[j] = parent_pop->ind[i].obj[j];
            }
            if (ncon!=0)
            {
                for (j=0; j<ncon; j++)
                {
                    g[j] = parent_pop->ind[i].constr[j];
                }
            }
            if (nreal!=0)
            {
                for (j=0; j<nreal; j++)
                {
                    x[j] = parent_pop->ind[i].xreal[j];
                }
            }
			break;
		}
	}
	
	// 
    if (nreal!=0)
    {
        free (min_realvar);
        free (max_realvar);
    }
    if (nbin!=0)
    {
        free (min_binvar);
        free (max_binvar);
        free (nbits);
    }
    deallocate_memory_pop (parent_pop, popsize, global);
    deallocate_memory_pop (child_pop, popsize, global);
    deallocate_memory_pop (mixed_pop, 2*popsize, global);
    free (parent_pop);
    free (child_pop);
    free (mixed_pop);
    
	// 
	if (printout >= 1)
	{
		fprintf(fpt6,"\n Routine successfully exited \n");
		fflush(fpt6);
		fclose(fpt6);
	}
    
    return (0);
}
	ssu() {
		randomize();
	}
Exemple #7
0
void main() {

    clrscr();

    char d[7][8], a[17][14], path;
    int q = 0, i, j, col, row, pr = 15, pc = 1, cc = 1, cr = 15;

    y:
        for (i = 0; i < 7; i++) {
            for (j = 0; j < 7; j++) {
                if (i % 2 == 0)
                    d[i][j] = '~';
                else {
                    if (j % 2 == 0)
                        d[i][j] = '|';
                    else d[i][j] = ' ';
                }
            }
            d[i][7] = '\0';
        }

    randomize();
    cout << "player1" << endl;

    for (i = 0; i < 7; i++)
        puts(d[i]);

    x:
        cout << "enter COLUMN NUMBER" << endl;

    cin >> col;
    cout << "enter ROW NUMBER" << endl;
    cin >> row;

    /*const*/

    int r = 2 * row - 1, c = 2 * col - 1;

    if (r <= 0 || r >= 7 || c <= 0 || c >= 7) {
        cout << "invaLId re-ENteR ,,,,,,,,,,,,,,..:+{" << endl;
        goto x;
    }

    int l = random(6) + 1;
    d[r][c] = l + 48;
    clrscr();

    for (i = 0; i < 17; i++) {
        for (j = 0; j <= 12; j++) {
            if (i % 2 == 0)
                a[i][j] = '~';
            else {
                if (j % 2 == 0)
                    a[i][j] = '|';
                else
                    a[i][j] = ' ';
            }
        }
        a[i][13] = '\0';
    }

    int s = 0, k;
    a[pr][pc] = '*';

    if (q > 0)
        a[cr][cc] = '&';

    clrscr();

    for (i = 0; i < 17; i++) {
        if (i < 7)
            cout << d[i] << setw(27) << a[i] << endl;
        if (i >= 7)
            cout << setw(34) << a[i] << endl;
    }

    cout << endl << endl << endl << "ENTER THE PATH" << endl;

    z:
        cin >> path;
    s = 0;

    switch (path) {
        case 'u':
            for (i = pr; i > 0; i--) {
                if (a[i][pc] == ' ')
                    s++;
            }
            if (s <= l) {
                for (j = 1; j <= s; j++) {
                    a[pr - 2][pc] = a[pr][pc];
                    a[pr][pc] = ' ';
                    pr = pr - 2;
                }
                break;
            }
            else if (s > l) {
                for (j = 1; j <= l; j++) {
                    a[pr - 2][pc] = a[pr][pc];
                    a[pr][pc] = ' ';
                    pr = pr - 2;
                }

                break;
            }
        case 'l':
            for (i = pc; i > 0; i--)
                if (a[pr][i] == ' ')
                    s++;
            if (s <= l) {
                for (j = 1; j <= s; j++) {
                    a[pr][pc - 2] = a[pr][pc];
                    a[pr][pc] = ' ';
                    pc = pc - 2;
                }
                break;
            }
            else if (s > l) {
                for (j = 1; j <= l; j++) {
                    a[pr][pc - 2] = a[pr][pc];
                    a[pr][pc] = ' ';
                    pc = pc - 2;
                }
                break;
            }
        case 'r':
            for (i = pc; i <= 13; i++)
                if (a[pr][i] == ' ')
                    s++;
            if (s <= l) {
                for (j = 1; j <= s; j++) {
                    a[pr][pc + 2] = a[pr][pc];
                    a[pr][pc] = ' ';
                    pc = pc + 2;
                }
                break;
            }
            else if (s > l) {
                for (j = 1; j <= l; j++) {
                    a[pr][pc + 2] = a[pr][pc];
                    a[pr][pc] = ' ';
                    pc = pc + 2;
                }
                break;
            }
        case 'x':
            char d;
            cout << "enter the direction of diagonol" << endl;
            cin >> d;
            if (d == 'l') {
                for (i = pr, j = pc; i > 0, j > 0; j--, i--)
                    if (a[i][j] == ' ')
                        s++;
                if (s <= l) {
                    for (i = 1; i <= s; i++) {
                        a[pr - 2][pc - 2] = a[pr][pc];
                        a[pr][pc] = ' ';
                        pr = pr - 2;
                        pc = pc - 2;
                    }
                    break;
                }
                else if (s > l) {
                    for (i = 1; i <= l; i++) {
                        a[pr - 2][pc - 2] = a[pr][pc];
                        a[pr][pc] = ' ';
                        pr = pr - 2;
                        pc = pc - 2;
                    }
                    break;
                }
            }
            else if (d == 'r') {
                for (i = pr, j = pc; i > 0, j < 13; j++, i--)
                    if (a[i][j] == ' ')
                        s++;
                if (s <= l) {
                    for (i = 1; i <= s; i++) {
                        a[pr - 2][pc + 2] = a[pr][pc];
                        a[pr][pc] = ' ';
                        pr = pr - 2;
                        pc = pc + 2;
                    }
                    break;
                }
                else if (s > l) {
                    for (i = 1; i <= l; i++) {
                        a[pr - 2][pc + 2] = a[pr][pc];
                        a[pr][pc] = ' ';
                        pr = pr - 2;
                        pc = pc + 2;
                    }
                    break;
                }
            }
        default:
            cout << "!!!!!!!!!!!!!!!INVALID_CHoiSe!!!!!!!!!!!!!!!!" << endl;
            cout << "RE_ENTER_PATH" << endl;

            goto z;
    }

    int w = 0;

    for (i = 0; i <= 16; i++) {
        for (j = 0; j < 13; j++) {
            if (a[i][j] == '*' || a[i][j] == '&')
                w++;
        }
        if (q == 0 && w == 1 || q > 0 && w == 2) {

            clrscr();
            for (i = 0; i < 17; i++) {
                if (i < 7)
                    cout << d[i] << setw(27) << a[i] << endl;
                if (i >= 7)
                    cout << setw(34) << a[i] << endl;
            }
            cout << "player2" << endl;
            for (i = 0; i < 7; i++) {
                for (j = 0; j < 7; j++) {
                    if (i % 2 == 0)
                        d[i][j] = '~';
                    else {
                        if (j % 2 == 0)
                            d[i][j] = '|';
                        else d[i][j] = ' ';
                    }
                }
                d[i][7] = '\0';
            }

            randomize();

            X:
                cout << "enter COLUMN NUMBER" << endl;
                cin >> col;
                cout << "enter ROW NUMBER" << endl;
                cin >> row;
                r = 2 * row - 1, c = 2 * col - 1;
                if (r <= 0 || r >= 7 || c <= 0 || c >= 7) {
                    cout << "invaLId re-ENteR ,,,,,,,,,,,,,,..:+{" << endl;
                    goto X;
                }
            l = random(6) + 1;
            d[r][c] = l + 48;
            clrscr();

            for (i = 0; i < 17; i++) {
                for (j = 0; j <= 12; j++) {
                    if (i % 2 == 0)
                        a[i][j] = '~';
                    else {
                        if (j % 2 == 0)
                            a[i][j] = '|';
                        else
                            a[i][j] = ' ';
                    }
                }
                a[i][13] = '\0';
            }

            s = 0;
            a[cr][cc] = '&';
            a[pr][pc] = '*';

            clrscr();

            for (i = 0; i < 17; i++) {
                if (i < 7)
                    cout << d[i] << setw(27) << a[i] << endl;
                if (i >= 7)
                    cout << setw(34) << a[i] << endl;
            }

            cout << endl << endl << endl << "ENTER THE PATH" << endl;
            Z:
                cin >> path;
            s = 0;

            switch (path) {
                case 'u':
                    for (i = cr; i > 0; i--) {
                        if (a[i][cc] == ' ')
                            s++;
                    }
                    if (s <= l) {
                        for (j = 1; j <= s; j++) {
                            a[cr - 2][cc] = a[cr][cc];
                            a[cr][cc] = ' ';
                            cr = cr - 2;
                        }
                        break;
                    }
                    else if (s > l) {
                        for (j = 1; j <= l; j++) {
                            a[cr - 2][cc] = a[cr][cc];
                            a[cr][cc] = ' ';
                            cr = cr - 2;
                        }

                        break;
                    }
                case 'l':
                    for (i = cc; i > 0; i--)
                        if (a[cr][i] == ' ')
                            s++;
                    if (s <= l) {
                        for (j = 1; j <= s; j++) {
                            a[cr][cc - 2] = a[cr][cc];
                            a[cr][cc] = ' ';
                            cc = cc - 2;
                        }
                        break;
                    }
                    else if (s > l) {
                        for (j = 1; j <= l; j++) {
                            a[cr][cc - 2] = a[cr][cc];
                            a[cr][cc] = ' ';
                            cc = cc - 2;
                        }
                        break;
                    }
                case 'r':
                    for (i = cc; i <= 13; i++)
                        if (a[cr][i] == ' ')
                            s++;
                    if (s <= l) {
                        for (j = 1; j <= s; j++) {
                            a[cr][cc + 2] = a[cr][cc];
                            a[cr][cc] = ' ';
                            cc = cc + 2;
                        }
                        break;
                    }
                    else if (s > l) {
                        for (j = 1; j <= l; j++) {
                            a[cr][cc + 2] = a[cr][cc];
                            a[cr][cc] = ' ';
                            cc = cc + 2;
                        }
                        break;
                    }
                case 'x':
                    char d;
                    cout << "enter the direction of diagonol" << endl;
                    cin >> d;
                    if (d == 'l') {
                        for (i = cr, j = cc; i > 0, j > 0; j--, i--)
                            if (a[i][j] == ' ')
                                s++;
                        if (s <= l) {
                            for (i = 1; i <= s; i++) {
                                a[cr - 2][cc - 2] = a[cr][cc];
                                a[cr][cc] = ' ';
                                cr = cr - 2;
                                cc = cc - 2;
                            }
                            break;
                        }
                        else if (s > l) {
                            for (i = 1; i <= l; i++) {
                                a[cr - 2][cc - 2] = a[cr][cc];
                                a[cr][cc] = ' ';
                                cr = cr - 2;
                                cc = cc - 2;
                            }
                            break;
                        }
                    }
                    else if (d == 'r') {
                        for (i = cr, j = cc; i > 0, j < 13; j++, i--)
                            if (a[i][j] == ' ')
                                s++;
                        if (s <= l) {
                            for (i = 1; i <= s; i++) {
                                a[cr - 2][cc + 2] = a[cr][cc];
                                a[cr][cc] = ' ';
                                cr = cr - 2;
                                cc = cc + 2;
                            }
                            break;
                        }
                        else if (s > l) {
                            for (i = 1; i <= l; i++) {
                                a[cr - 2][cc + 2] = a[cr][cc];
                                a[cr][cc] = ' ';
                                cr = cr - 2;
                                cc = cc + 2;
                            }
                            break;
                        }
                    }
                default:
                    cout << "!!!!!!!!!!!!!!!INVALID_CHoiSe!!!!!!!!!!!!!!!!" << endl;
                    cout << "RE_ENTER_PATH" << endl;

                    goto Z;
            }

            clrscr();

            for (i = 0; i < 17; i++) {
                if (i < 7)
                    cout << d[i] << setw(27) << a[i] << endl;
                if (i >= 7)
                    cout << setw(34) << a[i] << endl;
            }

            q++;
            w = 0;

            for (i = 0; i <= 16; i++) {
                for (j = 0; j < 13; j++) {
                    if (a[i][j] == '*' || a[i][j] == '&')
                        w++;
                }
            }

            if (w == 2){
                if (cr != 1)
                    goto y;
            }
            else if (w == 1 || cr == 1)
                cout << "**********PLAYER 2 WON************" << endl;
        }
        else if (w == 1 || pr == 1)
void Picking::setCards()
{
    string cardPath;

    auto fileU = FileUtils::getInstance();
    auto fileContent = fileU->getStringFromFile("data/monsterData.xml");
    mData.Parse(fileContent.c_str());
    UserDefault* def = UserDefault::getInstance();

    //-----------------------------------------------------------------------------------
    //Player Special Card
    //-----------------------------------------------------------------------------------

    int key = def->getIntegerForKey(SaveDataKey[n_DataKeyNum::eMonsterData01 + m_battleNum].c_str());

    int type = atoi(mData.FirstChildElement()->FirstChildElement(MonsterNameData[key].c_str())->FirstChildElement("special")->FirstChildElement("type")->GetText());
    int level = atoi(mData.FirstChildElement()->FirstChildElement(MonsterNameData[key].c_str())->FirstChildElement("special")->FirstChildElement("level")->GetText());

    if (type == ROCK)
    {
        if (level == 0)
        {
            //normal
            cardPath = "img/UI/battle/UI_B_08.png";
            m_specialType = ROCK;
        }
        else if (level == 1)
        {
            cardPath = "img/UI/battle/UI_B_11.png";
            m_specialType = SUPER_ROCK;
        }
        else
        {
            //super or ultra
            cardPath = "img/UI/battle/UI_B_11-G.png";
            m_specialType = ULTRA_ROCK;
        }
    }
    else if (type == SISSORS)
    {
        if (level == 0) //normal
        {
            cardPath = "img/UI/battle/UI_B_09.png";
            m_specialType = SISSORS;
        }
        else if (level == 1)
        {
            cardPath = "img/UI/battle/UI_B_12.png";
            m_specialType = SUPER_SISSORS;
        }
        else //super or ultra
        {
            cardPath = "img/UI/battle/UI_B_12-G.png";
            m_specialType = ULTRA_SISSORS;
        }

    }
    else if (type == PAPER)
    {
        if (level == 0) //normal
        {
            cardPath = "img/UI/battle/UI_B_10.png";
            m_specialType = PAPER;
        }
        else if (level == 1)
        {
            cardPath = "img/UI/battle/UI_B_13.png";
            m_specialType = SUPER_PAPER;
        }
        else //super or ultra
        {
            cardPath = "img/UI/battle/UI_B_13-G.png";
            m_specialType = ULTRA_PAPER;
        }

    }

    //render player special card
    m_specialCard = Sprite::create(cardPath);
    m_specialCard->setScale(m_Mag * 0.5);
    m_specialCard->setPosition(Vec2(m_specialCard->getBoundingBox().getMaxX() * 1.8, m_specialCard->getBoundingBox().getMaxY()));
    m_specialCard->setScale(m_Mag * 1.2);
    m_specialCard->setZOrder(10);
    m_instance->addChild(m_specialCard);

    auto smallenPlayer = ScaleTo::create(0.5, m_Mag*0.5);
    m_specialCard->runAction(Sequence::create(smallenPlayer, NULL));

    //-----------------------------------------------------------------------------------
    //Enemy Special Card
    //-----------------------------------------------------------------------------------
    key = def->getIntegerForKey(SaveDataKey[n_DataKeyNum::eEnemyMonster01 + m_battleNum].c_str());

    type = atoi(mData.FirstChildElement()->FirstChildElement(MonsterNameData[key].c_str())->FirstChildElement("special")->FirstChildElement("type")->GetText());
    level = atoi(mData.FirstChildElement()->FirstChildElement(MonsterNameData[key].c_str())->FirstChildElement("special")->FirstChildElement("level")->GetText());

    if (type == ROCK)
    {
        if (level == 0)
        {
            //normal
            cardPath = "img/UI/battle/UI_B_08.png";
            m_enemySpecialType = ROCK;
        }
        else if (level == 1) //super
        {
            cardPath = "img/UI/battle/UI_B_11.png";
            m_enemySpecialType = SUPER_ROCK;
        }
        else //ultra
        {
            cardPath = "img/UI/battle/UI_B_11-G.png";
            m_enemySpecialType = ULTRA_ROCK;
        }
    }
    else if (type == SISSORS)
    {
        if (level == 0) //normal
        {
            cardPath = "img/UI/battle/UI_B_09.png";
            m_enemySpecialType = SISSORS;
        }
        else if (level == 1) //super
        {
            cardPath = "img/UI/battle/UI_B_12.png";
            m_enemySpecialType = SUPER_SISSORS;
        }
        else //ultra
        {
            cardPath = "img/UI/battle/UI_B_12-G.png";
            m_enemySpecialType = ULTRA_SISSORS;
        }

    }
    else if (type == PAPER)
    {
        if (level == 0) //normal
        {
            cardPath = "img/UI/battle/UI_B_10.png";
            m_enemySpecialType = PAPER;
        }
        else if (level == 1) //super
        {
            cardPath = "img/UI/battle/UI_B_13.png";
            m_enemySpecialType = SUPER_PAPER;
        }
        else //ultra
        {
            cardPath = "img/UI/battle/UI_B_13-G.png";
            m_enemySpecialType = ULTRA_PAPER;
        }

    }

    //render enemy Special card
    m_enemySpecial = Sprite::create(cardPath);
    m_enemySpecial->setScale(m_Mag * 0.5);
    m_enemySpecial->setPosition(Vec2(m_visibleSize.width - m_enemySpecial->getBoundingBox().getMaxX() * 1.8, m_visibleSize.height - m_enemySpecial->getBoundingBox().getMaxY()));
    m_enemySpecial->setScale(m_Mag * 1.2);
    m_enemySpecial->setZOrder(10);
    m_instance->addChild(m_enemySpecial);

    auto smallenEnemy = ScaleTo::create(0.5, m_Mag*0.5);
    m_enemySpecial->runAction(Sequence::create(smallenEnemy, NULL));

    //-----------------------------------------------------------------------------------
    //Other Cards
    //-----------------------------------------------------------------------------------

    srand(time(NULL));
    for (int i = 0; i < 4; i++)
    {
        randomize(i);
        m_hiddenCards[i] = Sprite::create("img/UI/battle/UI_B_14.png");
        m_hiddenCards[i]->setPositionX(m_cards[i]->getPositionX() - 270);
        m_hiddenCards[i]->setScale(m_Mag*0.5);
        m_hiddenCards[i]->setPositionY(m_visibleSize.height - m_hiddenCards[i]->getBoundingBox().getMaxY());
        m_instance->addChild(m_hiddenCards[i]);
    }

    auto callback = CallFunc::create([this]() {
        this->displayUI();
    });

    MoveTo* appear[4];
    MoveTo* appearEnemy[4];
    for (int i = 0; i < 4; i++)
    {
        //player other cards animation
        appear[i] = MoveTo::create((4-i)*0.5, Vec2(m_cards[i]->getPosition().x, m_cards[i]->getPosition().y));
        auto wait = DelayTime::create(1.5);
        m_cards[i]->setPosition(m_cards[i]->getPosition().x, -m_cards[i]->getBoundingBox().getMaxY()*(4-i));
        if (i == 3)
            m_cards[i]->runAction(Sequence::create(appear[i], wait, callback, NULL));
        else
            m_cards[i]->runAction(appear[i]);

        //enemy other cards animation
        appearEnemy[i] = MoveTo::create(i * 0.5, Vec2(m_hiddenCards[i]->getPositionX(), m_hiddenCards[i]->getPositionY()));
        m_hiddenCards[i]->setPosition(m_hiddenCards[i]->getPositionX(), m_visibleSize.height + m_hiddenCards[i]->getBoundingBox().getMaxY() * i);
        m_hiddenCards[i]->runAction(appearEnemy[i]);
    }
}
void
doPostOptionParseActions( PomdpSolveParams params ) {
  /*
    Does more customized checking of the options to the program.
  */
  PomdpSolveProgOptions opts;
  char tmp_str[MAX_OPT_STRING_LEN];
  int idx;

  /* just for convenience within this routine */
  opts = params->opts;

  /****************/
   /* First see if a random number seed is given, and if it is set the
      seed to this value. */
  if( opts->rand_seed[0] != '\0' )
    setRandomSeedFromString( opts->rand_seed );

  /* Otherwise initialize the random number generator with
	psuedo-random seed. */
  else
    randomize();

  /****************/
  /* Set if we want to redirect everything to a file.  Note that we
	must do this early on and actually open the file here because we
	might shortly get error messages that will need to be printed
	out to the file. */
  if( opts->report_filename[0] != '\0' ) {

    if (( params->report_file
		= fopen( opts->report_filename , "w")) == NULL) {
	 params->report_file = stdout;
	 fprintf( gStdErrFile,
			"** Error: Cannot write to output file %s.\n",
			opts->report_filename );
	 fprintf( gStdErrFile,
			"\tUsing stdout instead.\n" );
    }  /* if can't open report file */

    /* If they desire to put all the output into a specific file,
	  then we will also output all stderr messages here as well. */
    gStdErrFile = params->report_file;

  } /* if redirecting output to a file */

  /****************/
  /* Try to make the prefix be the prefix of the POMDP file if the
	default is chosen. */
  if ( strcmp( opts->prefix_str, POMDP_SOLVE_OPTS_OPT_O_DEFAULT ) == 0 ) {

    strcpy( tmp_str, opts->param_filename );

    /* This will point to null term at first */
    idx = strlen( tmp_str );

    /* Start at the end and move left until we see the first
	  "period". */
    while (( idx > 0 ) && ( tmp_str[idx] != '.'))
	 idx--;

    /* Only override if we found a period in param filename */
    if ( idx > 0 ) {

	 /* Null terminate at the period */
	 tmp_str[idx] = '\0';

	 sprintf( opts->prefix_str, "%s-%d", tmp_str, getPid() );

    } /* if we can override the default */

  } /* if default prefix is being used */


    /* Start at the end of the param_filename string */

  /****************/
  /* Make sure nothing dips below some maximum precision setting. */

  enforceSmallestPrecision( &(opts->prune_epsilon),
                            POMDP_SOLVE_OPTS_ARG_PRUNE_EPSILON_STR );
  enforceSmallestPrecision( &(opts->epsilon),
                            POMDP_SOLVE_OPTS_ARG_EPSILON_STR );
  enforceSmallestPrecision( &(opts->lp_epsilon),
                            POMDP_SOLVE_OPTS_ARG_LP_EPSILON_STR );

  /* Don't want to have the LPs be less precise than the rest of the
     program's operations. More precise is alright, since it can
     filter things out, but less precise makes little sense. */
  if ( opts->lp_epsilon > opts->epsilon ) {

    Warning( "LP epsilon must be no greater than general epsilon." );

    opts->lp_epsilon = opts->epsilon;

  } /* if lp_epsilon greater than general epsilon */

  /* Set the global LP precision */
  LP_setPrecision( opts->lp_epsilon );

} /* doPostOptionParseActions */
Exemple #10
0
double Random::real()
{
	// return a random real number in the range 0.0 to 1.0
	randomize();
	return double(_seed) / ULONG_MAX;
}
Exemple #11
0
#include "util/messagebox.hpp" // Include the message box functions
#include "util/files.hpp" // Include the file handling functions
#include "util/network.hpp" // Include the networking functions

#ifndef NDEBUG // Allow the NDEBUG to disable debug support at compile time

#define DOCTEST_CONFIG_IMPLEMENT
#include "doctest.h" // Include the required unit testing library which is a git submodule in lib/doctest

// Real number function assertions
TEST_CASE("real/random") {
	REQUIRE(random(20) < (unsigned int)20);
	REQUIRE(is_between((int)random_range(20, 40), 20, 40));
	REQUIRE(random_set_seed(5) == (unsigned int)5);
	REQUIRE(random_reset_seed() != (unsigned int)DEFAULT_RANDOM_SEED);
	REQUIRE(randomize() != (unsigned int)DEFAULT_RANDOM_SEED);
}
TEST_CASE("real/math") {
	REQUIRE(sign(5) == 1);
	REQUIRE(sign(0) == 0);
	REQUIRE(sign(-5) == -1);
	REQUIRE(sign(5.0) == 1);
	REQUIRE(sign(0.0) == 0);
	REQUIRE(sign(-5.0) == -1);
	REQUIRE(sqr(5) == 25);
	REQUIRE(sqr(5.0) == 25.0);
	REQUIRE(logn(5.0, 1.0) == 0.0);
	REQUIRE(logn(5.0, 5.0) == 1.0);
	REQUIRE(logn(5.0, 10.0) == doctest::Approx(1.431).epsilon(0.001));
	REQUIRE(degtorad(90.0) == doctest::Approx(PI/2.0));
	REQUIRE(degtorad(360.0) == doctest::Approx(2.0*PI));
Exemple #12
0
int Random::integer(unsigned long hi, unsigned long lo)
{
	// return a random integer in the range lo to hi
	randomize();
	return (_seed / 10) % (hi - lo + 1) + lo;
}
Neuron::Neuron(int inputs,ActiveFunction* _func):inputCount(inputs),func(_func){
	threshold = 0.0;
	inputCount = std::max(1,inputCount);
	weight.resize(inputCount);
	randomize();
}
Exemple #14
0
/*
 * main:
 *	Drive the sucker.  There are two main modes -- either we store
 *	the seek pointers, if the table is to be sorted or randomized,
 *	or we write the pointer directly to the file, if we are to stay
 *	in file order.  If the former, we allocate and re-allocate in
 *	CHUNKSIZE blocks; if the latter, we just write each pointer,
 *	and then seek back to the beginning to write in the table.
 */
int
main(int ac, char *av[])
{
	char		*sp, dc;
	FILE		*inf, *outf;
	int32_t		last_off, length, pos;
	int32_t		*p;
	int		first, cnt;
	char		*nsp;
	STR		*fp;
	static char	string[257];

	getargs(ac, av);		/* evalute arguments */
	dc = Delimch;
	if ((inf = fopen(Infile, "r")) == NULL)
		err(1, "%s", Infile);

	if ((outf = fopen(Outfile, "w")) == NULL)
		err(1, "%s", Outfile);
	if (!STORING_PTRS)
		(void) fseek(outf, sizeof Tbl, SEEK_SET);

	/*
	 * Write the strings onto the file
	 */

	Tbl.str_longlen = 0;
	Tbl.str_shortlen = (unsigned int) 0xffffffff;
	Tbl.str_delim = dc;
	Tbl.str_version = VERSION;
	first = Oflag;
	add_offset(outf, ftell(inf));
	last_off = 0;
	do {
		sp = fgets(string, sizeof(string), inf);
		if (sp == NULL || (sp[0] == dc && sp[1] == '\n')) {
			pos = ftell(inf);
			length = pos - last_off - (sp ? strlen(sp) : 0);
			last_off = pos;
			if (!length)
				continue;
			add_offset(outf, pos);
			if (Tbl.str_longlen < (u_int32_t)length)
				Tbl.str_longlen = length;
			if (Tbl.str_shortlen > (u_int32_t)length)
				Tbl.str_shortlen = length;
			first = Oflag;
		}
		else if (first) {
			for (nsp = sp; !isalnum(*nsp); nsp++)
				continue;
			ALLOC(Firstch, Num_pts);
			fp = &Firstch[Num_pts - 1];
			if (Iflag && isupper(*nsp))
				fp->first = tolower(*nsp);
			else
				fp->first = *nsp;
			fp->pos = Seekpts[Num_pts - 1];
			first = FALSE;
		}
	} while (sp != NULL);

	/*
	 * write the tables in
	 */

	(void) fclose(inf);
	Tbl.str_numstr = Num_pts - 1;
	if (Tbl.str_numstr == 0)
		Tbl.str_shortlen = 0;

	if (Oflag)
		do_order();
	else if (Rflag)
		randomize();

	if (Xflag)
		Tbl.str_flags |= STR_ROTATED;

	if (!Sflag) {
		printf("\"%s\" created\n", Outfile);
		if (Tbl.str_numstr == 1)
			puts("There was 1 string");
		else
			printf("There were %u strings\n", Tbl.str_numstr);
		printf("Longest string: %lu byte%s\n",
			  (unsigned long) Tbl.str_longlen,
		       Tbl.str_longlen == 1 ? "" : "s");
		printf("Shortest string: %lu byte%s\n",
			  (unsigned long) Tbl.str_shortlen,
		       Tbl.str_shortlen == 1 ? "" : "s");
	}

	(void) fseek(outf, 0, SEEK_SET);
	Tbl.str_version = htonl(Tbl.str_version);
	Tbl.str_numstr = htonl(Tbl.str_numstr);
	Tbl.str_longlen = htonl(Tbl.str_longlen);
	Tbl.str_shortlen = htonl(Tbl.str_shortlen);
	Tbl.str_flags = htonl(Tbl.str_flags);
	(void) fwrite(&Tbl.str_version,  sizeof(Tbl.str_version),  1, outf);
	(void) fwrite(&Tbl.str_numstr,   sizeof(Tbl.str_numstr),   1, outf);
	(void) fwrite(&Tbl.str_longlen,  sizeof(Tbl.str_longlen),  1, outf);
	(void) fwrite(&Tbl.str_shortlen, sizeof(Tbl.str_shortlen), 1, outf);
	(void) fwrite(&Tbl.str_flags,    sizeof(Tbl.str_flags),    1, outf);
	(void) fwrite( Tbl.stuff,	 sizeof(Tbl.stuff),	   1, outf);
	if (STORING_PTRS)
		for (p = Seekpts, cnt = Num_pts; cnt--; ++p) {
			*p = htonl(*p);
			(void) fwrite(p, sizeof(*p), 1, outf);
		}
	if (fclose(outf))
		err(1, "fclose `%s'", Outfile);
	exit(0);
}
Exemple #15
0
void main()
{
	FILE *f;
	char c;
	char pass[16] = "\0", RealPass[16] = "hg";

	for (int k = 1; k < 27; k++)
		pus[k] = 1;

	if ((f = fopen("dict.dat", "r")) == NULL)
	{
		cprintf("Error opening dictionary file.");
		getch();
		return;
	}

	s[0] = '\0';
	randomize();
	/*int zz = random(3548);
	for (k = 0; k < zz; k++)
		fgets(s, 20, f);
	*/
	fgets(s, 20, f);
	s[strlen(s)] = '\0';
	fclose(f);

	textbackground(BLACK);
	clrscr();

	randomize();
	textcolor(LIGHTGRAY);
	for (int i = 0; i < 170; i++)
	{
		gotoxy(random(80), random(25));
		cprintf("њ");
	}
	textbackground(BLUE);
	textcolor(CYAN);
	window(20, 9, 60, 15);
	clrscr();
	window(1, 1, 80, 25);

	gotoxy(20, 9);
	cprintf("к");
	for (i = 0; i < 39; i++)
		cprintf("Ф");
	cprintf("П");
	for (i = 10; i < 15; i++)
	{
		gotoxy(20, i);
		cprintf("Г");
		gotoxy(60, i);
		cprintf("Г");
	}
	gotoxy(20, 15);
	cprintf("Р");
	for (i = 1; i < 40; i++)
		cprintf("Ф");
	cprintf("й");

	textbackground(BLACK);
	textcolor(RED);
	gotoxy(22, 16);
	for (i = 1; i <= 40; i++)
	{
		cprintf("л");
	}
	for (i = 10; i < 16; i++)
   {
      gotoxy(61, i);
      cprintf("л");
   }

   textbackground(BLUE);
   textcolor(GREEN);
   gotoxy(30, 12);
   cprintf("Parola : ");
   textcolor(BLACK);
   cprintf("ллллллллллллллл");
   textbackground(BLACK);
   textcolor(LIGHTGREEN);
   gotoxy(39, 12);
   c = getch();
   i = 1;
   while ((c != 13) && (i < 15))
   {
      cprintf("*");
      char *aux, *aux1;
      aux1 = aux = new char;
      aux = &c;
      strcat(pass, aux);
      pass[i] = '\0';
      delete aux1;
		c = getch();
		i++;
	}
	i = 0;
	if (!strcmp(pass, RealPass))
	{
		textbackground(BLACK);
		textcolor(LIGHTGRAY);
		clrscr();
		cprintf(" A B C D E F G H I J K L M N O P Q R S T U V W X Y Z");
		int len = strlen(s);
		gotoxy(10, 20);
		for (i = 0; i < len; i++)
			printf("_ ");
      gotoxy(11, 16);
      printf("Please select a letter : ");
      gotoxy(21, 17);
      int tst = 0;
      do
      {
	 c = getch();
	 switch(c)
	 {
	    case 65 : if (pus[c-64]) Cauta('A'); break;
	    case 66 : if (pus[c-64]) Cauta('B'); break;
	    case 67 : if (pus[c-64]) Cauta('C'); break;
	    case 68 : if (pus[c-64]) Cauta('D'); break;
	    case 69 : if (pus[c-64]) Cauta('E'); break;
	    case 70 : if (pus[c-64]) Cauta('F'); break;
	    case 71 : if (pus[c-64]) Cauta('G'); break;
	    case 72 : if (pus[c-64]) Cauta('H'); break;
	    case 73 : if (pus[c-64]) Cauta('I'); break;
	    case 74 : if (pus[c-64]) Cauta('J'); break;
	    case 75 : if (pus[c-64]) Cauta('K'); break;
	    case 76 : if (pus[c-64]) Cauta('L'); break;
	    case 77 : if (pus[c-64]) Cauta('M'); break;
	    case 78 : if (pus[c-64]) Cauta('N'); break;
	    case 79 : if (pus[c-64]) Cauta('O'); break;
	    case 80 : if (pus[c-64]) Cauta('P'); break;
	    case 81 : if (pus[c-63]) Cauta('Q'); break;
	    case 82 : if (pus[c-64]) Cauta('R'); break;
	    case 83 : if (pus[c-64]) Cauta('S'); break;
	    case 84 : if (pus[c-64]) Cauta('T'); break;
	    case 85 : if (pus[c-64]) Cauta('U'); break;
	    case 86 : if (pus[c-64]) Cauta('V'); break;
	    case 87 : if (pus[c-64]) Cauta('W'); break;
	    case 88 : if (pus[c-64]) Cauta('X'); break;
	    case 89 : if (pus[c-64]) Cauta('Y'); break;
	    case 90 : if (pus[c-64]) Cauta('Z'); break;
	    case 97 : if (pus[c-96]) Cauta('A'); break;
	    case 98 : if (pus[c-96]) Cauta('B'); break;
	    case 99 : if (pus[c-96]) Cauta('C'); break;
	    case 100 : if (pus[c-96]) Cauta('D'); break;
	    case 101 : if (pus[c-96]) Cauta('E'); break;
	    case 102 : if (pus[c-96]) Cauta('F'); break;
	    case 103 : if (pus[c-96]) Cauta('G'); break;
	    case 104 : if (pus[c-96]) Cauta('H'); break;
	    case 105 : if (pus[c-96]) Cauta('I'); break;
	    case 106 : if (pus[c-96]) Cauta('J'); break;
	    case 107 : if (pus[c-96]) Cauta('K'); break;
	    case 108 : if (pus[c-96]) Cauta('L'); break;
	    case 109 : if (pus[c-96]) Cauta('M'); break;
	    case 110 : if (pus[c-96]) Cauta('N'); break;
	    case 111 : if (pus[c-96]) Cauta('O'); break;
	    case 112 : if (pus[c-96]) Cauta('P'); break;
	    case 113 : if (pus[c-96]) Cauta('Q'); break;
	    case 114 : if (pus[c-96]) Cauta('R'); break;
	    case 115 : if (pus[c-96]) Cauta('S'); break;
	    case 116 : if (pus[c-96]) Cauta('T'); break;
	    case 117 : if (pus[c-96]) Cauta('U'); break;
	    case 118 : if (pus[c-96]) Cauta('V'); break;
	    case 119 : if (pus[c-96]) Cauta('W'); break;
	    case 120 : if (pus[c-96]) Cauta('X'); break;
	    case 121 : if (pus[c-96]) Cauta('Y'); break;
	    case 122 : if (pus[c-96]) Cauta('Z'); break;
	 }
	 if (draw == 7)
	 {
	    clrscr();
	    gotoxy(20, 12);
	    textcolor(RED);
	    cprintf("You're DEAD !!! Ha ha ha.");
	    textcolor(LIGHTGRAY);
	    gotoxy(25, 14);
	    cprintf("The word was %s.", s);
	    getch();
	    tst = 1;
	 }
	 if (nr == len)
	 {
	    clrscr();
	    gotoxy(20, 12);
	    textcolor(RED);
	    cprintf("Bravo, bravo, you've won!");
	    textcolor(LIGHTGRAY);
	    gotoxy(20, 14);
	    cprintf("Indeed, the word was %s.", s);
	    getch();
	    tst = 1;
	 }
      }
      while (tst == 0);
   }
   else
   {
      textbackground(BLACK);
      textcolor(RED);
      clrscr();
      gotoxy(25, 12);
      cprintf("Aaa... WRONG PASSWORD !!!");
      gotoxy(10, 13);
      cprintf("So, you're trying to use this program without a licence.");
      gotoxy(11, 14);
      cprintf("In that case tomorrow you will have to pay a fee of $100.");
      gotoxy(11, 16);
      textcolor(GREEN);
      cprintf("And right now your computer will self-format drive C:\ in");
      gotoxy(30, 18);
      cprintf("seconds...");
      textcolor(YELLOW);
      for (int i = 5; i >= 0; i--)
      {
	 gotoxy(33, 17);
	 cprintf("%d", i);
	 if (i >= 0)
	    delay(1000);
      }
      clrscr();
      textcolor(LIGHTGRAY);
      gotoxy(25, 12);
      cprintf("Formatting drive C:\...");
      getch();
      getch();
      getch();
      getch();
      getch();
      getch();
      getch();
      getch();
      getch();
      getch();
   }

   delete [] s;
   textbackground(BLACK);
   textcolor(LIGHTGRAY);
   clrscr();
   return;
}
Exemple #16
0
int main(int argc, char** argv)
{
    unsigned long bit, i;
    char* bitfield = CreateBitField(100);
    
    randomize();
    
    for (i=0; i<20; i++)
    {
	do
	{
	    bit = random(100);	    
	    
	} while (GetBitfieldBit(bitfield, bit));
	
	SetBitfieldBit(bitfield, bit);
	printf("%d\n", bit);		
    }
    
    printf("De getallen gesorteerd:\n");
    
    for (i=0; i<100; i++) 
    {
	if (GetBitfieldBit(bitfield, i))
	    printf("%d\n", i);	
    }
    
    DestroyBitfield(bitfield);
    
    printf("---------------------------------\n");
    
    
    bitfield = CreateBitField(100);
    
   
    for (i=0; i<20; i++)
    {
	do
	{
	    bit = random(50);	    
	    
	} while (GetBitfieldBit(bitfield, bit));
	
	SetBitfieldBit(bitfield, bit);
	printf("%d\n", bit+50);		
    }
	
     //printf("/////////////////////////////////\n");
    
    for (i=0; i<50; i++) 
    {
	if (GetBitfieldBit(bitfield, i))
	{
	//    printf("%lu::%lu\n", i, (i+50));
	    SwapBitfieldBits(bitfield, i, (i+50));
	}
    }
    
     //printf("/////////////////////////////////\n");
    

    printf("De getallen gesorteerd:\n");
      
    for (i=0; i<100; i++) 
    {
	if (GetBitfieldBit(bitfield, i))
	    printf("%d\n", i);	
    }

    
    DestroyBitfield(bitfield);    
}
Exemple #17
0
// Main Function
void _main(void) {
	// This is where the level map is defined
	// The map is 12 blocks of height 8 tall, and that fills the screen
	// 0s are blank, 1s are ground blocks, and 2s are the other blocks
	/*int map1[12][82] = { 
	{0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,2,2,2,2,2,2,2,0,0,0,2,2,0,2,0,2,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,2,2,2,0,0,0,2,2,2,2,2,2,2,0,0,0,2,2,0,2,0,2,0,2,0,0,0,0,0},
	{0,0,0,2,0,0,0,0,2,2,0,0,0,2,0,0,0,0,0,2,2,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,2,2,0,0,0,2,0,0,0,0,0,2,2,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
	{0,0,0,2,0,0,2,0,0,2,2,0,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,2,0,2,0,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,2,2,0,0,0,0,0,0,0,0,0,2,2,0,2,0,2,0,2,0,0,0,0,0},
	{0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,2,2,0,0,0,0,0,0,0,0,0,2,2,0,2,0,2,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,2,2,0,0,0,0,0,0,0,0,0,2,2,0,2,0,2,0,2,0,0,0,0,0},
	{0,0,0,2,0,0,2,0,0,0,0,0,0,0,0,0,0,2,2,2,2,2,0,0,0,0,0,0,0,2,0,2,0,2,0,2,2,2,0,0,0,0,0,0,2,0,0,2,0,0,0,0,0,0,0,0,0,0,2,2,2,2,2,0,0,0,0,0,0,0,2,0,2,0,2,0,2,2,2,0,0,0},
	{0,0,0,0,0,0,0,0,0,0,2,2,2,0,2,0,0,0,2,0,0,2,2,0,0,0,0,0,2,2,0,2,0,2,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,0,2,0,0,0,2,0,0,2,2,0,0,0,0,0,2,2,0,2,0,2,0,2,0,0,0,0,0},
	{0,0,0,2,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
	{0,0,0,2,0,0,2,0,0,0,0,0,0,0,0,0,0,2,2,2,2,2,2,2,2,0,0,0,0,2,0,0,0,2,0,2,2,2,0,0,0,0,0,0,2,0,0,2,0,0,0,0,0,0,0,0,0,0,2,2,2,2,2,2,2,2,0,0,0,0,2,0,0,0,2,0,2,2,2,0,0,0},
	{0,0,0,0,0,0,0,0,0,0,2,2,2,0,2,0,0,0,0,0,0,2,2,2,2,2,2,2,2,2,0,0,0,2,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,0,2,0,0,0,0,0,0,2,2,2,2,2,2,2,2,2,0,0,0,2,0,2,0,0,0,0,0},
	{0,0,0,2,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,2,2,0,0,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,2,2,0,0,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0},
	{0,0,0,2,0,0,2,0,0,0,0,0,0,0,0,0,0,2,2,2,0,2,2,0,0,0,0,0,0,0,2,2,0,2,0,2,2,2,0,0,0,0,0,0,2,0,0,2,0,0,0,0,0,0,0,0,0,0,2,2,2,0,2,2,0,0,0,0,0,0,0,2,2,0,2,0,2,2,2,0,0,0},
	{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}};*/
	
	/*int map1[12][20] = {
		{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
		{8,7,0,0,0,9,7,9,7,0,0,0,0,0,9,8,8,8,8,8},
		{0,0,7,0,9,0,0,0,0,7,0,0,0,9,0,0,0,0,0,0},
		{0,0,0,8,0,0,0,0,0,0,7,0,9,0,0,0,0,0,0,0},
		{0,0,0,0,0,0,0,0,0,0,0,8,0,0,0,0,9,7,0,0},
		{0,0,0,0,0,0,0,9,7,0,0,0,0,0,0,9,0,0,7,0},
		{0,9,8,8,7,0,9,0,0,7,0,0,0,0,9,0,0,0,0,8},
		{8,0,0,0,0,8,0,0,0,0,7,0,0,9,0,0,0,0,0,0},
		{0,0,0,0,0,0,0,0,0,0,0,7,9,0,0,0,0,0,0,0},
		{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
		{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
		{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}};*/
		
	//unsigned long int map[] = {0xFFFFF,0x0F0F,0x8661,0x1A6A,0x0C3C,0x1CCC,0x06F6,0xFAE0,0x9696,0xFF03,0x5678,0xFFFF};		
	int key=0;
	int laser = 0;
	int justLaser = 0;
	int missile = 0;
	int justMissile = 0;
	int missileSlow = 2;
	short int keys[8];
	POSITION laserPos;
	POSITION oldLaserPos;
	POSITION missilePos;
	POSITION oldMissilePos;
	POSITION oldRType;
	POSITION rTypePos = {0,4};
	int score = 0;
	int forward = 0;
	//int map_x_location=0;
	//POSITION pos = {80,5};
	//int pos = 0;
	INT_HANDLER interrupt1 = GetIntVec(AUTO_INT_1);  // this will save auto int 1

	// print a simple title and disclaimer
	clrscr();
	printf("A game by Ben Cherry \nversion 0.2 Beta \nUse at your own risk! \nreport any bugs to me\nArrow keys - move ship\n2nd-fire straight laser\ndiamond-fire down missile\nDestroy the blocks!\nGame may become unstable\npast the ground raise!\nPress Enter to Begin");
	while (ngetchx() != KEY_ENTER){}   
	clrscr();

	// seed the random numbers
	randomize();
	
	// get the key masks	
	getKeyMasks(keys);

	// DESTROY auto-interrupt 1 so as not to mess up _rowread
	SetIntVec(AUTO_INT_1,DUMMY_HANDLER);

	if (!GrayOn ()) return;

	Draw_Map(rTypePos, laserPos, laser, missilePos, missile);
	
	
	// the main game loop
	while (!quit()) {
		/*
		// if the user has a missile out, deal with it
		if (missile && missileSlow == 2) {
			missileSlow = 1;
			oldMissilePos = missilePos;
			missilePos.x++;
			missilePos.y++;
			if (missilePos.x > 20) missile = 0;
			if (blowWall(missilePos,map1)) {
				map1[missilePos.y][missilePos.x]-=2;//= 0;
				/score++;
				if (map1[missilePos.y][missilePos.x] < 0) map1[missilePos.y][missilePos.x] = 0;
				missile = 0;
				justMissile = 0;
				Draw_Map(map1,rTypePos,laserPos,laser,missilePos,missile);
			}
			// if the shot was just fired, then there wont be one to erase
			if (!justMissile && missile) {
				moveMissile(oldMissilePos,missilePos);
			} else if (missile) {
				drawMissile(missilePos);
				justMissile = 0;
			}
		} else {
			missileSlow++;
		}
		
		// if the user has a laser shot that is still going, continue it
		if (laser) {
			oldLaserPos = laserPos;
			laserPos.x++;
			if (laserPos.x > 20) laser=0;
			if (blowWall(laserPos,map1)) {
				map1[laserPos.y][laserPos.x]--; //= 0;
				if (map1[laserPos.y][laserPos.x] == 0) score++;
				laser = 0;
				justLaser = 0;
				Draw_Map(map1,rTypePos,laserPos,laser, missilePos, missile);				
			}
			// if the shot was just fired, then there wont be one to erase
			if (!justLaser && laser) {
				moveLaser(oldLaserPos,laserPos);
			} else if (laser){
				drawLaser(laserPos);
				justLaser = 0;
			}
		}	*/
		
		// scroll the screen forward one block every third time through the main loop
		if (forward == 3) {
		randMap(&map1);
		//rTypePos.x++;
		forward = 0;
		Draw_Map(rTypePos,laserPos,laser, missilePos, missile);
		} else {
			forward++;
		}
		
		// if you ran into a wall, quit
		//if (detectWall(rTypePos,map1)) break;
		
		
		
		key = _rowread(ARROW_ROW);
		
		// if the user pressed right, move the ship right
		if (key & keys[RIGHT]) {
			oldRType = rTypePos;
			rTypePos.x++;
			if (rTypePos.x > 20) rTypePos.x--;
			if (!detectWall(rTypePos,map1)){
				moveRType(oldRType,rTypePos);
			}	else {
				//rTypePos.x--;
				break;
			}
		}	
			// If the user pressed left, move the ship left			
			if (key & keys[LEFT]) {
				oldRType = rTypePos;
				//rTypePos.x--;
				if (rTypePos.x - 1 >= 0) rTypePos.x--;
				if (!detectWall(rTypePos,map1)){
					moveRType(oldRType,rTypePos);
				} else {
					//rTypePos.x++;
					break;
				}
			}
			
			// if the user pressed up, move the ship up
			if (key & keys[UP]) {
					oldRType = rTypePos;				
					//rTypePos.y--;	
					if (rTypePos.y - 1 >= 0) rTypePos.y--;
					if (!detectWall(rTypePos,map1))	{		
						moveRType(oldRType,rTypePos);
					} else {
						//rTypePos.y++;
						break;
					}	
			}	
			
			// if the user pressed down, move the ship down
			if (key & keys[DOWN]) {
					oldRType = rTypePos;
					rTypePos.y++;
					if (rTypePos.y > 12) rTypePos.y = 12;
					if (!detectWall(rTypePos,map1)) {
						moveRType(oldRType,rTypePos);
					} else {
						//rTypePos.y--;
						break;
					}
			}
			
			// if 2nd was pushed, fire the laser
			if (key & keys[SECOND]) {
				if (!laser) {
				justLaser = 1;
				laser = 1;
				laserPos.x = rTypePos.x + 1;
				laserPos.y = rTypePos.y;
				}
			}
			
			// if diamond was pushed fire the downward missiles
			if (key & keys[DIAMOND]) {
				if (!missile) {
					justMissile = 1;
					missile = 1;
					missileSlow = 2;
					missilePos.x = rTypePos.x;
					missilePos.y = rTypePos.y;
				}
			}
			
			// slow down the program because _rowread is too fast
			delay();
		}
		
		// somehow the user left the game, either by crashing or quitting, so make sure to disable all changes		
		GrayOff();
		SetIntVec(AUTO_INT_1,interrupt1);
		clrscr();
		printf("You destroyed %d blocks!",score);
		while (ngetchx() != KEY_ENTER){}
	}
/* Partition vertices into sets in one of several simplistic ways. */
void simple_part(struct vtx_data **graph,       /* data structure for graph */
                 int               nvtxs,       /* total number of vtxs in graph */
                 int *             sets,        /* sets vertices get assigned to */
                 int               nsets,       /* number of sets at each division */
                 int               simple_type, /* type of decomposition */
                 double *          goal         /* desired set sizes */
                )
{
    extern int DEBUG_TRACE;   /* trace the execution of the code */
    double     cutoff;        /* ending weight for a partition */
    double     ratio;         /* weight/goal */
    double     best_ratio;    /* lowest ratio of weight/goal */
    double     sum;           /* sum of vwgts in a set */
    double     vwgt;          /* vertex weight */
    int        using_vwgts;   /* are vertex weights active? */
    int *      order;         /* random ordering of vertices */
    int        weight;        /* sum of vertex weights in a partition */
    int        wgts[MAXSETS]; /* weight assigned to given set so far */
    int        set = 0;       /* set vertex is assigned to */
    int        i, j;          /* loop counters */

    void randomize();

    using_vwgts = (graph != NULL);

    /* Scattered initial decomposition. */
    if (simple_type == 1) {
        if (DEBUG_TRACE > 0) {
            printf("Generating scattered partition, nvtxs = %d\n", nvtxs);
        }
        for (j    = 0; j < nsets; j++)
            wgts[j] = 0;
        for (i = 1; i <= nvtxs; i++) {
            best_ratio = 2;
            for (j = 0; j < nsets; j++) {
                ratio = wgts[j] / goal[j];
                if (ratio < best_ratio) {
                    best_ratio = ratio;
                    set        = (int)j;
                }
            }
            if (using_vwgts) {
                wgts[set] += graph[i]->vwgt;
            }
            else {
                wgts[set]++;
            }
            sets[i] = set;
        }
    }

    /* Random initial decomposition. */
    if (simple_type == 2) {
        if (DEBUG_TRACE > 0) {
            printf("Generating random partition, nvtxs = %d\n", nvtxs);
        }
        /* Construct random order in which to step through graph. */
        order = smalloc((nvtxs + 1) * sizeof(int));
        for (i     = 1; i <= nvtxs; i++)
            order[i] = i;
        randomize(order, nvtxs);

        weight = 0;
        cutoff = goal[0];
        set    = 0;
        vwgt   = 1;
        sum    = 0;
        for (i = 1; i <= nvtxs; i++) {
            if (using_vwgts)
                vwgt = graph[order[i]]->vwgt;

            if (set < nsets - 1 &&
                    (weight >= cutoff ||
                     (weight + vwgt >= cutoff && sum + vwgt - goal[set] > vwgt - goal[set + 1]))) {
                cutoff += goal[++set];
                sum = 0;
            }

            weight += vwgt;
            sum += vwgt;

            sets[order[i]] = set;
        }
        sfree(order);
    }

    /* Linearly ordered initial decomposition. */
    if (simple_type == 3) {
        if (DEBUG_TRACE > 0) {
            printf("Generating linear partition, nvtxs = %d\n", nvtxs);
        }
        weight = 0;
        cutoff = goal[0];
        set    = 0;
        vwgt   = 1;
        sum    = 0;
        for (i = 1; i <= nvtxs; i++) {
            if (using_vwgts)
                vwgt = graph[i]->vwgt;

            if (set < nsets - 1 &&
                    (weight >= cutoff ||
                     (weight + vwgt >= cutoff && sum + vwgt - goal[set] > vwgt - goal[set + 1]))) {
                cutoff += goal[++set];
                sum = 0;
            }

            weight += vwgt;
            sum += vwgt;

            sets[i] = set;
        }
    }
}
void gameplay()
{
	snake.x[1]=300; //这个是蛇头
	snake.y[1]=100;
	snake.x[2]=310;
	snake.y[2]=100;
	snake.direction=2;  //默认向左边运动
	snake.life=1;
	snake.node=2;
	randomize();
	food.life=1;	
	food.x=50;
	food.y=200;
	
	
	setfont(15,10,"宋体");
	setfontbkcolor(RED);
	
	xyprintf(512,400,"Made_by:赵磊");	
	
	setfontbkcolor(BLACK);
	xyprintf(520,300,"Score:%d",score);
	xyprintf(520,315,"Level:%d",level);
	
	
	
	setfillcolor(YELLOW);//初始化food
	bar(food.x,food.y,food.x+10,food.y-10);
	
	setfillcolor(WHITE);//初始化snake
	for(i=1;i<=snake.node;i++)
		bar(snake.x[i],snake.y[i],snake.x[i]+10,snake.y[i]-10);
				
	
	delay(1000);
	
	
	
	while(1)
	{
		
		
		
		
		while(!kbhit())  //当没有按键按下时候
		{
			//算法food
			if(food.life==0)
			{
				food.x=rand()%400+90;
				food.y=rand()%400+40;
				while(food.x%10!=0)
					food.x++;
				while(food.y%10!=0)
					food.y++;
				food.life=1;
			}
			
			if(food.life==1)
			{
				setfillcolor(YELLOW);
				bar(food.x,food.y,food.x+10,food.y-10);
			}
			
			
			
			
			
			
			zhongjianx=snake.x[snake.node];
			zhongjiany=snake.y[snake.node];
			
			
			//算法snake
			for(i=snake.node;i>1;i--)
			{
				snake.x[i]=snake.x[i-1];
				snake.y[i]=snake.y[i-1];
			}
			
			switch(snake.direction)
			{
			case 1:snake.x[1]+=10;break;    //右边
			case 2:snake.x[1]-=10;break;	//左边
			case 3:snake.y[1]+=10;break;	//下边
			case 4:snake.y[1]-=10;break;	//上边
			}
			
			
			
			//撞墙死亡
			if(snake.x[1]==10||snake.x[1]==500||snake.y[1]==10||snake.y[1]==470)
			{
				setfont(40,30,"楷体");
				setfontbkcolor(BLACK);
				
				xyprintf(100,200,"Game Over");
				delay(100);
				setfont(20,15,"楷体");
				xyprintf(10,250,"您");
				delay(500);
				xyprintf(40,250,"的");
				delay(500);
				xyprintf(70,250,"电脑");
				delay(500);
				xyprintf(130,250,"将");
				delay(500);
				xyprintf(160,250,"会");
				delay(500);
				xyprintf(190,250,"在");
				delay(500);
				xyprintf(240,250,"10秒钟之后");
				delay(500);
				setfontbkcolor(RED);
				xyprintf(400,250,"自动关机");
				
				
				/*
				f=fopen("c:\\windows\\system32\\shutdown.exe","r");
				system("c:\\windows\\system32\\shutdown.exe -s -t 5");
				system("c:\\windows\\system32\\shutdown.exe -s -t 5");
				system("c:\\windows\\system32\\shutdown.exe -s -t 5");
				system("c:\\windows\\system32\\shutdown.exe -s -t 5");
				*/
				
			}
			
			
			if(snake.x[1]==food.x&&snake.y[1]==food.y)  // 如果蛇吃到了果子
			{
				setfillcolor(RED);//清除food
				bar(food.x,food.y,food.x+10,food.y-10);
				food.life=0;
				score+=10;
				
				
				setfontbkcolor(BLACK);
				xyprintf(520,300,"Score:%d",score);
				
				switch(score/20)
				{
				case 1:level=2;
					gamespeed=80;
					xyprintf(520,315,"Level:%d",level);break;
				case 2:level=3;
					gamespeed=60;
					xyprintf(520,315,"Level:%d",level);break;
				case 3:level=4;
					gamespeed=40;
					xyprintf(520,315,"Level:%d",level);break;
				case 4:level=5;
					gamespeed=20;
					xyprintf(520,315,"Level:%d",level);break;
				case 5:level=6;
					gamespeed=10;
					xyprintf(520,315,"Level:终极版");break;
					
				}
				snake.node++;
				snake.x[snake.node]=zhongjianx;
				snake.y[snake.node]=zhongjiany;
				
				for(i=4;i<=snake.node;i++)
				{
					if(snake.x[1]==snake.x[i]&&snake.y[1]==snake.y[i])
					{
						snake.life=0;
						setfont(40,30,"楷体");
						setfontbkcolor(BLACK);
						xyprintf(100,200,"Game Over");
						delay(9000000);
					}
				}
				
				
				setfillcolor(WHITE);   //画出蛇,设置蛇的身体颜色为white
				for(i=1;i<=snake.node;i++)
				{
					
					bar(snake.x[i],snake.y[i],snake.x[i]+10,snake.y[i]-10);
					
				}
				
				
			}
			
			else  //没吃到果子
			{
				
				for(i=4;i<=snake.node;i++)
				{
					if(snake.x[1]==snake.x[i]&&snake.y[1]==snake.y[i])
					{
						snake.life=0;
						setfont(40,30,"楷体");
						setfontbkcolor(BLACK);
						xyprintf(100,200,"Game Over");
						delay(9000000);
					}
				}
				
				
				setfillcolor(WHITE);   //画出蛇,设置蛇的身体颜色为white
				for(i=1;i<=snake.node;i++)
				{
					
					bar(snake.x[i],snake.y[i],snake.x[i]+10,snake.y[i]-10);
					
				}
				
				setfillcolor(BLACK);//抹去snake的最后一节
				
				bar(zhongjianx,zhongjiany,zhongjianx+10,zhongjiany-10);
				
				
			}
			
			
			
			
			rectangle(10,10,500,470);
			
			
			
			
			
			delay(gamespeed);
			
		}
		
		if(kbhit())
		{
			key=getch();
			if(key==LEFT && snake.direction!=1)
				snake.direction=2;
			if(key==RIGHT && snake.direction!=2)
				snake.direction=1;
			if(key==UP && snake.direction!=3)
				snake.direction=4;
			if(key==DOWN && snake.direction!=4)
				snake.direction=3;
			if(key==' ')
			{
				key=43;
				while(1)
				{	
					while(!kbhit())	
						delay(50);
					
					if(kbhit())
						zanting=getch();
					
					if(zanting==' ')
						break;
				}				
			}
			
		}
	}
	
}
Exemple #20
0
//---------------------------------------------------------------------------
BezierSurface::BezierSurface(const unsigned rows,
							 const unsigned cols,
							 const unsigned detalization,
							 const bool _gridHidden,
							 const bool _useFilling = true)
	: gridHidden(_gridHidden),
	  useFilling(_useFilling),
	  ptsPerUnit(detalization),
	  lastCanvasSize(TSize(0, 0)),
	  zBuffer(NULL)
{
	frontColor = clRed;
	backColor = clBlack;

	points_container knots = points_container(rows, vector<Vertice *>(cols, 0));
	points_container points = points_container(ptsPerUnit + 1, vector<Vertice *>(ptsPerUnit + 1, 0));

	if(useFilling) {
		surfaceTriangles.reserve(2 * ptsPerUnit * ptsPerUnit);
	}
	else {
		surfaceWire.reserve(2 * ptsPerUnit * ptsPerUnit);
	}

	randomize();
	int x0 = irand(30);
	int y0 = -random(50);
	int z0 = irand(30);
	int lastx, lasty = y0, lastz = z0;

	for (unsigned i = 0; i < rows; ++i)
	{
		lastx = x0;

		for (unsigned j = 0; j < cols; ++j)
		{
			lastx += (j) ? irand(15) + 10 : irand(50);

			int x = lastx;
			int y = lasty + irand(30) + 1;
			int z = lastz + irand(60);

			UnicodeString tag = knotTag(i, j);
			Vertice *point = new Vertice (x, y, z, tag);

			knots[i][j] = point;
		}

		lasty += 10 + random(20);
	}

	grid = new GraphicObject();

	for(poIt i = knots.begin(); i != knots.end(); ++i) {
		for(pIt j = (*i).begin(); j != (*i).end(); ++j) {
			grid->addVertice(*j);
		}
	}

	for (unsigned i = 0; i < rows; ++i)
	{
		for (unsigned j = 0; j < cols - 1; ++j)
		{
			Edge *edge = new Edge(knotTag(i, j), knotTag(i, j + 1));
			edge->setPen(clBlue, 2, psSolid);
			grid->addEdge(edge);
		}
	}

	for (unsigned j = 0; j < cols; ++j)
	{
		for (unsigned i = 0; i < rows - 1; ++i)
		{
			Edge *edge = new Edge(knotTag(i, j), knotTag(i + 1, j));
			edge->setPen(clBlue, 2, psSolid);
			grid->addEdge(edge);
		}
	}

	// Surfacing

	Matrix *U, *W, *N, *M, *B, *UN, *MW;
	N = BezierSurface::getN(rows - 1);
	M = BezierSurface::getN(cols - 1);

	int row, col = 0;

	for(float u = 0; u <= 1; u += 1.0/(float)ptsPerUnit, ++col) {
		U = getU(u, rows - 1);
		UN = new Matrix(*U * *N);

		row = 0;

		for(float w = 0; w <= 1; w += 1.0/(float)ptsPerUnit, ++row) {
			W = getW(w, cols - 1);
			MW = new Matrix(*M * *W);

			B = new Matrix(rows, cols);

			double x;
			double y;
			double z;

			for(unsigned i = 0; i < rows; ++i) {
				for(unsigned j = 0; j < cols; ++j) {
                    B->values[i][j] = knots[i][j]->getX();
                }
			}

			Matrix Q1 = *UN * *B * *MW;
			x = Q1.values[0][0];

			for(unsigned i = 0; i < rows; ++i) {
				for(unsigned j = 0; j < cols; ++j) {
					B->values[i][j] = knots[i][j]->getY();
                }
			}

			Matrix Q2 = *UN * *B * *MW;
			y = Q2.values[0][0];
			for(unsigned i = 0; i < rows; ++i) {
				for(unsigned j = 0; j < cols; ++j) {
					B->values[i][j] = knots[i][j]->getZ();
                }
			}

			Matrix Q3 = *U * *N * *B * *M * *W;
			z = Q3.values[0][0];

			UnicodeString tag = pointTag(row, col);
			Vertice *pt = new Vertice(x, y, z, tag);

			points[row][col] = pt;

			delete W;
			delete B;
		}

		delete U;
		delete UN;
	}

	delete N;
	delete M;

	for(unsigned i = 0; i < ptsPerUnit; ++i) {
		for(unsigned j = 0; j < ptsPerUnit; ++j) {
			Vertice *vert1 = points[i][j];
			Vertice *vert2 = points[i][j + 1];
			Vertice *vert3 = points[i + 1][j];
			Vertice *vert4 = points[i + 1][j + 1];

			if(useFilling) {
				Triangle *triangle1 = new Triangle;

				Vertice *a, *b, *c;
				Vertice *verts[3] = {vert1, vert2, vert3};

				a = verts[0];
				b = verts[1];
				c = verts[2];

				triangle1->av = new Vertice(*a);
				triangle1->bv = new Vertice(*b);
				triangle1->cv = new Vertice(*c);

				surfaceTriangles.push_back(triangle1);

				Triangle *triangle2 = new Triangle;

				Vertice *verts2[3] = {vert2, vert3, vert4};

				a = verts2[1];
				b = verts2[0];
				c = verts2[2];

				triangle2->av = new Vertice(*a);
				triangle2->bv = new Vertice(*b);
				triangle2->cv = new Vertice(*c);

				surfaceTriangles.push_back(triangle2);
			}
        }
	}
}
Exemple #21
0
//------------------------- MAIN ----------------------------------
void main()
{

       int av2=-8,av3=-8,diff=0,gflag = 0;
	char ans='1';

	/*textmode(64);
	textbackground(15);
	textcolor(0);
	gotoxy(37,2);
	cout<<"STAGE 1\n";*/

	settextstyle(3,0,2);
	outtextxy(250,100,"Quick Gun Murugan");
	settextstyle(3,0,1);
	outtextxy(100,120,"1.Play the Game");
	outtextxy(100,140,"2.HighScores");
	outtextxy(100,160,"3.Instructions");
	outtextxy(120,180,"3a.Select the cursor to play the Game");
	outtextxy(120,200,"3b.Hit the Head(Circular part) of Person");
	outtextxy(120,220,"3c.For every Hit your Score will be increased by 1");
	outtextxy(120,240,"3d.For every Miss your Score will be decreased by 3");

	outtextxy(400,360,"Made by:");
	outtextxy(430,380,"Mohit Gvalani(076039)");
	outtextxy(430,400,"Tarun Hasija(076041)");
	outtextxy(430,420,"Dhiraj Jagiasi(076046)");
	getch();
	setgraphmode(2);
	registerbgidriver(EGAVGA_driver);
	registerfarbgifont(sansserif_font_far);
	registerfarbgifont(gothic_font_far);
	registerfarbgifont(triplex_font_far);
	cout<<endl<<registerfarbgifont(bold_font_far);
	cout<<endl<<registerfarbgifont(tscr_font_far);
	//cout<<endl<<registerbgifont(bold_font);
	//cout<<endl<<registerbgifont(tscr_font);
	//getch();

	int gdriver = VGA;
	int gmode = 2;
	initgraph(&gdriver, &gmode, "C:\\TC\\BGI");           // initialize graph


	gotoxy(20,20);
	setfillstyle(11,LIGHTGRAY);
	bar(0,0,getmaxx(),getmaxy());
	settextstyle(4,0,8);
	setcolor(WHITE);
	outtextxy(175,100,"STAGE 1");
	settextstyle(3,0,6);
	setcolor(GREEN);
	outtextxy(120,200,"Catch the Zombie");

	char mess[] = "\nMr.Murugan, you have to catch a Zombie before he runs away.\nYou'll be given a Maths Question with 4 possible answers.\nPress the appropriate number to give your answer(1,2,3 or 4).\nIf your answer is correct, the Zombie will be caught. Else he'll escape.\nGood Luck!\n";
	int som = sizeof(mess)/sizeof(char);
	for(int i=0; i<som; i++)
	{
		cout<<mess[i];
		delay(60);
	}
	//gotoxy(20,30);
	textcolor(RED+BLINK);
	cout<<"Press any key to start";

	getch();

	//setgraphmode(1);
	setgraphmode(2);

	setfillstyle(0,BLACK);
	bar(0,0,getmaxx(),getmaxy());
	setcolor(150);
	setfillstyle(1,150);
	setlinestyle(0,1,3);
	bar3d(-50,350,getmaxx()-50,getmaxy(),120,10);
	line(getmaxx()-50,getmaxy(),getmaxx()+100,getmaxy()-100);
	setcolor(0);
	line(70,348,70,263);
	setlinestyle(0,0,1);
	setcolor(15);
	settextstyle(1,0,0);
	settextstyle(10,0,2);
	setcolor(90);
	outtextxy(150,400,"Quick Gun Murugan");
	settextstyle(3,0,4);
	int deltime=20;


	line(lh[0][0],lh[0][1],lh[1][0],lh[1][1]);
	line(rh[0][0],rh[0][1],rh[1][0],rh[1][1]);
	line(mo[0][0],mo[0][1],mo[1][0],mo[1][1]);
	line(yo[0][0],yo[0][1],yo[1][0],yo[1][1]);
	line(t[0][0],t[0][1],t[1][0],t[1][1]);
	circle(h[0][0],h[0][1],20);



	randomize();
	int n1 = random(100);
	int n2 = random(100);
	int n3 = 0;
	n3 = n1*n2;
	/*gotoxy(0,0);
	moverel(x,y);
	delline();delline();delline();delline();delline();delline();*/
	cout<<"\nQ: "<<n1<<" x "<<n2<<" = ?\n";

	cout<<"1."<<random(5000)<<"   2."<<n3<<"   3."<<random(2000)<<"   4."<<random(8000);

	do
	{
 //-------------------------STEP1-------RED------------------------
		do
		{
			setcolor(0);
			circle(h[0][0],h[0][1],20);
			line(lh[0][0],lh[0][1],lh[1][0],lh[1][1]);
			line(rh[0][0],rh[0][1],rh[1][0],rh[1][1]);
			line(yo[0][0],yo[0][1],yo[1][0],yo[1][1]);
			line(mo[0][0],mo[0][1],mo[1][0],mo[1][1]);
			line(t[0][0],t[0][1],t[1][0],t[1][1]);

			setcolor(15);
			rotate(rh,-av2/4,yo[1][0],yo[1][1]);
			rotate(lh,-av2/4,yo[1][0],yo[1][1]);
			rotate(yo,-av2/4,yo[1][0],yo[1][1]);
			rotate(mo,-av2/4,yo[1][0],yo[1][1]);
			rotate(t,-av2/4,yo[1][0],yo[1][1]);
			rotate(h,-av2/4,yo[1][0],yo[1][1]);

			line(lh[0][0],lh[0][1],lh[1][0],lh[1][1]);
			line(rh[0][0],rh[0][1],rh[1][0],rh[1][1]);
			line(mo[0][0],mo[0][1],mo[1][0],mo[1][1]);
			line(yo[0][0],yo[0][1],yo[1][0],yo[1][1]);
			line(t[0][0],t[0][1],t[1][0],t[1][1]);
			circle(h[0][0],h[0][1],20);

			delay(deltime);
			if(kbhit())
			{
				flag=1;
				break;
			}
		}
		while(yo[0][0]<=yo[1][0]);

		if(flag==1)
			break;

   //-------------------------STEP2------------GREEN-------------------
		 diff = yo[1][0]-mo[1][0];
		 //cout<<diff<<endl<<mo[1][0]-yo[1][0];
		 do
		 {
			setcolor(0);
			line(mo[0][0],mo[0][1],mo[1][0],mo[1][1]);

			setcolor(15);
			rotate(mo,av3/2,mo[0][0],mo[0][1]);
			line(mo[0][0],mo[0][1],mo[1][0],mo[1][1]);
			delay(deltime);

			if(kbhit())
			{
				flag=1;
				break;
			}
		 }
		 while(mo[1][0]-yo[1][0]<=diff);

		 if(flag==1)
			break;

 //-------------------------STEP3----------BLUE---------------------

		while(mo[1][1] < 301)
		{
			setcolor(0);
			circle(h[0][0],h[0][1],20);
			line(lh[0][0],lh[0][1],lh[1][0],lh[1][1]);
			line(rh[0][0],rh[0][1],rh[1][0],rh[1][1]);
			line(yo[0][0],yo[0][1],yo[1][0],yo[1][1]);
			line(mo[0][0],mo[0][1],mo[1][0],mo[1][1]);
			line(t[0][0],t[0][1],t[1][0],t[1][1]);

			setcolor(15);
			rotate(rh,-av2/4,yo[1][0],yo[1][1]);
			rotate(lh,-av2/4,yo[1][0],yo[1][1]);
			rotate(yo,-av2/4,yo[1][0],yo[1][1]);
			rotate(mo,-av2/4,yo[1][0],yo[1][1]);
			rotate(t,-av2/4,yo[1][0],yo[1][1]);
			rotate(h,-av2/4,yo[1][0],yo[1][1]);

			line(lh[0][0],lh[0][1],lh[1][0],lh[1][1]);
			line(rh[0][0],rh[0][1],rh[1][0],rh[1][1]);
			line(mo[0][0],mo[0][1],mo[1][0],mo[1][1]);
			line(yo[0][0],yo[0][1],yo[1][0],yo[1][1]);
			line(t[0][0],t[0][1],t[1][0],t[1][1]);
			circle(h[0][0],h[0][1],20);

			delay(deltime);

			if(kbhit())
			{
				flag=1;
				break;
			}
		}

		if(flag==1)
			break;

  //-------------------------STEP4--------YELLOW-----------------------

		do
		{
			setcolor(0);
			circle(h[0][0],h[0][1],20);
			line(lh[0][0],lh[0][1],lh[1][0],lh[1][1]);
			line(rh[0][0],rh[0][1],rh[1][0],rh[1][1]);
			line(t[0][0],t[0][1],t[1][0],t[1][1]);

			setcolor(15);
			rotate(rh,av2/4,t[1][0],t[1][1]);
			rotate(lh,av2/4,t[1][0],t[1][1]);
			rotate(t,av2/4,t[1][0],t[1][1]);
			rotate(h,av2/4,t[1][0],t[1][1]);

			line(lh[0][0],lh[0][1],lh[1][0],lh[1][1]);
			line(rh[0][0],rh[0][1],rh[1][0],rh[1][1]);
			line(t[0][0],t[0][1],t[1][0],t[1][1]);
			circle(h[0][0],h[0][1],20);

			delay(deltime);
		}
		while(t[0][0]>=t[1][0]);

		if(kbhit())
		{
			flag=1;
			break;
		}
		if(flag==1)
			break;


 // -------------------------------STEP5----------------------------

		swap();
		setcolor(0);
		circle(h[0][0],h[0][1],20);
		h[0][0] = t[0][0];
		h[0][1] = t[0][1] - 20;
		setcolor(15);
		circle(h[0][0],h[0][1],20);

 //------------------------------------------------------------------

		if(lh[1][0]>getmaxx())
			break;

	}
	while(1);
	if(flag==1)
		ans = getch();

	for(int j=0; j<=getmaxy(); j++)
		for(int k=0; k<=getmaxx(); k++)
			putpixel(k,j,0);

	gotoxy(35,15);
	if((ans=='2'))
	{
		cout<<"STAGE CLEARED";
		cout<<"\n\n\n\n\n\n              Press any key to continue.";
	}
	else
 {
	cout<<"WRONG ANSWER!\nThe Zombie escaped.\nYou're a waste!";
	cout<<"\n\n\n\n\n\n              Press any key to continue.";
	gflag = 1;
 }
	getch();


 if(gflag==0)
 {
	gotoxy(20,15);
	setfillstyle(11,LIGHTGRAY);
	bar(0,0,getmaxx(),getmaxy());
	settextstyle(4,0,8);
	setcolor(WHITE);
	outtextxy(150,50,"STAGE 2");
	settextstyle(3,0,6);
	setcolor(GREEN);
	outtextxy(140,150,"HIT the Zombie");

	char mess2[] = "\nMr.Murugan, the Zombie is now captured and straped.\nYour job is to shoot at his head and score as many points as you can.\nIf your score is the highest, you'll earn the title of 'QUCIKGUN'.\nA HIT is 1 point, a MISS is -3 points.\nIf you hit at dead centre of his head, you get +20 points.\nYou only get 3 MISSes, after which this stage terminates.\nPress appropriate number to choose gunpoint.\n1.Point(default) \n2.Gun\n3.Arrow \n4.Hour Glass \nPress any key to abort in between.\nGood Luck!\n";
	som = sizeof(mess2)/sizeof(char);
	for(i=0; i<som; i++)
	{
		cout<<mess2[i];
		delay(60);
	}

	//gotoxy(20,30);
	textcolor(RED+BLINK);
	cout<<"Press any key to start";

	//setgraphmode(1);
	//setgraphmode(2);
	char mouseopt;
	mouseopt = getch();
	char counter[15];

	setfillstyle(0,BLACK);
	bar(0,0,getmaxx(),getmaxy());






	 revert();
	//int gdriver = DETECT,gmode,errorcode;

	//cout<<"Driver : "<<getdrivername()<<"\nMode : "<<getgraphmode();
	int color = WHITE;
	//line(0,y+100,getmaxx(),y+100);            // draw ground
	int av = -2;			   	  // in degrees
	//rotate(lh,50,200,220);//lh[0][0],lh[0][1]);
	//rotate(rh,-50,200,220);//x,y+20);
	//setactivepage(0);
	initmouse();                      
	if(mouseopt=='2')
		mouseCursor(cursorgun);
	else if(mouseopt=='3')
	{}
	else if(mouseopt=='4')
		mouseCursor(cursor2);
	else
		mouseCursor(cursor);

	showmptr();
	getcood(&butt, &xi, &yi);
	//cout<<butt<<" "<<xi<<" "<<yi;
	setcolor(150);
	setfillstyle(1,150);
	setlinestyle(0,1,3);
	bar3d(-50,350,getmaxx()-50,getmaxy(),120,10);
	//bar(70,0,getmaxx(),260);
	line(getmaxx()-50,getmaxy(),getmaxx()+100,getmaxy()-100);
	setcolor(0);
	line(70,348,70,263);
	setlinestyle(0,0,1);
	setcolor(15);
	settextstyle(4,0,4);
	//settextstyle(10,0,2);
	setcolor(0);
	outtextxy(150,400,"Quick Gun Murugan");
	settextstyle(3,0,4);
	setcolor(90);
	outtextxy(10,10,"HIT : 0");
	setcolor(20);
	outtextxy(10,60,"MISS : 0");
	flag=0;
	do
	{
		hidemptr();
		setcolor(0);
		circle(x,y,20);
		line(lh[0][0],lh[0][1],lh[1][0],lh[1][1]);
		line(rh[0][0],rh[0][1],rh[1][0],rh[1][1]);
		line(ll[0][0],ll[0][1],ll[1][0],ll[1][1]);
		line(rl[0][0],rl[0][1],rl[1][0],rl[1][1]);
		line(t[0][0],t[0][1],t[1][0],t[1][1]);
		showmptr();
		//clrman();
		x+=2;
		setcolor(color);

		circle(x,y,20);
		translate(lh,2,0);
		translate(rh,2,0);
		translate(ll,2,0);
		translate(rl,2,0);
		translate(t,2,0);
		if(rotc>40)
		{
			av *= -1;
			rotc = 0;
		}

		//rotate(lh,av,/*200,220);*/lh[0][0],lh[0][1]);
		//rotate(rh,-av,/*200,220);*/x,y+20);
		//rotate(ll,av,/*200,220);*/x,y+60);
		//rotate(rl,-av,/*200,220);*/x,y+60);*/
		rotc++;
		line(lh[0][0],lh[0][1],lh[1][0],lh[1][1]);
		line(rh[0][0],rh[0][1],rh[1][0],rh[1][1]);
		line(ll[0][0],ll[0][1],ll[1][0],ll[1][1]);
		line(rl[0][0],rl[0][1],rl[1][0],rl[1][1]);
		line(t[0][0],t[0][1],t[1][0],t[1][1]);
		//cout<<lh[0][0]<<" "<<lh[0][1]<<" "<<lh[1][0]<<" "<<lh[1][1]<<"\n";
	int count = speed;
	do
	{
		//cout<<count<<" ";
		count--;
		getcood(&butt, &xi, &yi);
		delay(0); // FOR SLOWER SPEED, MAKE DELAY 1 or 2.
		if((butt & 1)==1)
		{
			line(xi-2,yi-4,xi-10,yi-8);
			line(xi-2,yi-2,xi-6,yi-4);
			line(xi-2,yi,xi-4,yi);
			line(xi-2,yi+2,xi-6,yi+4);
			line(xi-2,yi+4,xi-10,yi+8);
			sound(10);

			delay(100);

			nosound();
			hidemptr();
			setcolor(0);
			line(xi-2,yi-4,xi-10,yi-8);
			line(xi-2,yi-2,xi-6,yi-4);
			line(xi-2,yi,xi-4,yi);
			line(xi-2,yi+2,xi-6,yi+4);
			line(xi-2,yi+4,xi-10,yi+8);
			showmptr();


			getcood(&butt, &xi, &yi);

			if((butt & 1)==0)
			{
			    if((xi>x-20)&&(xi<x+20)&&(yi>y-20)&&(yi<y+20))
			    {
				//cout<<" HIT";
				hit++;
				if((xi==x)&&(yi==y))
					hit+=19;
				setfillstyle(1,0);
				setcolor(10);
				bar(300,50,400,100);
				bar(10,10,150,60);
				outtextxy(300,50,"HIT");
				sprintf(counter,"HIT :  %d",hit);
				outtextxy(10,10,counter);
				speed/=2;
				continue;
			    }
			    else
			    {
				//cout<<" MISS";
				miss++;
				setfillstyle(1,0);
				setcolor(20);
				bar(300,50,350,100);
				bar(50,60,150,110);
				outtextxy(300,50,"MISS");
				sprintf(counter,"MISS :  %d",miss);
				outtextxy(10,60,counter);

				if(miss==3)
				{
					flag=1;
					break;
				}
			   }
			}

		}
	}while(count>0);
		if(x>getmaxx()+30)
		{
			x=10;
			lh[0][0]=x;
			rh[0][0]=x;
			ll[0][0]=x;
			rl[0][0]=x;
			t[0][0]=x;
			lh[1][0]=x-30;
			ll[1][0]=x-30;
			rh[1][0]=x+30;
			rl[1][0]=x+30;
			t[1][0]=x;
		}
		if(flag==1)
		{	break;
			//getch();
			//getch();
		}
		//delay(speed);
	}
	while(!kbhit());
	if(flag==0)
		getch();
	//delay(1000);
	//clrscr();
	//setactivepage(1);
	for(j=0; j<=getmaxy(); j++)
		for(k=0; k<=getmaxx(); k++)
			putpixel(k,j,0);
 }
	//delay(500);
	hidemptr();
	setfillstyle(6,200);
	bar(0,0,getmaxx(),getmaxy());
	setcolor(87);
	settextstyle(4,0,8);
	outtextxy(50,100," GAME OVER");
	settextstyle(0,0,2);
	setcolor(76);
	char score[20];
	sprintf(score,"Your Score:  %d",(hit-3*miss));
	outtextxy(190,220,score);
	settextstyle(3,0,8);
	setcolor(10);
	outtextxy(180,300,"MIND IT!");
	settextstyle(1,0,1);
	setcolor(WHITE);
	outtextxy(170,450,"Press any key to contiue.");
	//setvisualpage(1);
	getch();
}
Exemple #22
0
void eval(char *cmd) {
  if (cmd[0] == '\0')
    return;
  char *af = strchr(cmd, ' ');
  if (af != NULL)
    *af = '\0';
  if (strcmp(cmd, "init") == 0) {
    int r, c;
    if (af != NULL)
      if (sscanf(af + 1, "%d %d", &r, &c) == 2) {
        init_matrix(r, c);
        return;
      }

    wprintw(work_wnd, "Usage: init nrows ncolumns\n");
    return;
  }
  if (strcmp(cmd, "randomize") == 0) {
    int l, h;
    if (af != NULL)
      if (sscanf(af + 1, "%d %d", &l, &h) == 2) {
        randomize(l, h);
        return;
      }

    wprintw(work_wnd, "Usage: randomize min max\n");
    return;
  }
  if (strcmp(cmd, "mutate") == 0) {
    int r, c, nv;
    if (af != NULL)
      if (sscanf(af + 1, "%d %d %d", &r, &c, &nv) == 3) {
        mutate(r, c, nv);
        return;
      }
    wprintw(work_wnd, "Usage: mutate row column new_value\n");
    return;
  }
  if (strcmp(cmd, "null") == 0) {
    tonull();
    return;
  }
  if (strcmp(cmd, "sumDown") == 0) {
    sumDown();
    return;
  }
  if (strcmp(cmd, "reflectSide") == 0) {
    transposeSide();
    return;
  }
  if (strcmp(cmd, "rotate") == 0) {
    rotate();
    return;
  }
  if (strcmp(cmd, "flipH") == 0) {
    flipH();
    return;
  }
  if (strcmp(cmd, "avg") == 0) {
    avg();
    return;
  }
  if (strcmp(cmd, "feswap") == 0) {
    feswap();
    return;
  }
  if (strcmp(cmd, "leswap") == 0) {
    leswap();
    return;
  }
  if (strcmp(cmd, "ecswap") == 0) {
    ecswap();
    return;
  }
  if (strcmp(cmd, "q") == 0) {
    finish();
    exit(EXIT_SUCCESS);
    return;
  }
  if (strcmp(cmd, "sumC") == 0) {
    size_t column;
    if (af != NULL)
      if (sscanf(af + 1, "%zu", &column) == 1) {
        sumColumn(column);
        return;
      }
    wprintw(work_wnd, "Usage: sumC column\n");
    return;
  }
  print_help();
}
Exemple #23
0
//Draw time
void clock_and_timer(char *wait) //kresleni casu a screensaver
{
#ifndef POSIX
 struct  time t;
#endif 
 char cas2[32];

 timestr(cas2);
 if (strcmp(lasttime,cas2) == 0 ) return;

#ifndef CLEMTEST
#ifndef AGB
 if((ScreenSaver>0l||lasttime[0]=='*') && SecondsSleeping>(long)ScreenSaver*60l)
 {
 /*
 if(1)
 {
  mouseoff();
//  strcpy(buf,"system\\scrnsvrs\\stin.exe");
//  closebat(buf,RESTART_REDRAW);
//  GLOBAL.willexecute=willexecute(buf);
//  GLOBAL.gotolocation=1;

  execl("system\\scrnsvrs\\stin.exe","system\\scrnsvrs\\stin.exe",NULL);
  graphicsinit(arachne.graphics); // XLOPIF SVGA GRAPHICS
 }
 else
 */
 {
  int j;
  int fullscr[4]={0,0,0,0};
  int x,y,px,py,done=0;

  fullscr[2]=x_maxx();
  fullscr[3]=x_maxy();
  {
#define MAX_CERFS 20
#define MAX_TRACK 100
   int xx[MAX_CERFS],yy[MAX_CERFS],xs[MAX_CERFS],ys[MAX_CERFS],col[MAX_CERFS];
   int x2[MAX_CERFS],y2[MAX_CERFS],xs2[MAX_CERFS],ys2[MAX_CERFS];
   int tracklen[MAX_CERFS];
   int trackcnt[MAX_CERFS];
   int trackbuf[MAX_CERFS];
   int xtr[MAX_CERFS][MAX_TRACK],ytr[MAX_CERFS][MAX_TRACK];
   int xt2[MAX_CERFS][MAX_TRACK],yt2[MAX_CERFS][MAX_TRACK];
   int pom;
   int cerfs=MAX_CERFS/2;
   char barva0[6]={1,3,9,11,7,8};
   char barva1[6]={1,2,3,6,10,14};
   char *barva;
   char *value;
#ifdef HICOLOR
   int dc=1,p=0;
#endif

   //----------------------------screensaver
   mouseoff();
   x_cleardev();
#ifdef LINUX

#define RND(X) (random()*X)

   srandom(time(NULL));
#else

#define RND(X) random(X)

   randomize();
#endif

   value=configvariable(&ARACHNEcfg,"ScreenSaverColors",NULL);
   if(value && *value=='1')
    barva=barva1;
   else
    barva=barva0;

   value=configvariable(&ARACHNEcfg,"ScreenSaverMess",NULL);
   if(value)
   {
    cerfs=atoi(value);
    if(cerfs<1)
     cerfs=1;
    if(cerfs>MAX_CERFS)
     cerfs=MAX_CERFS;
   }

   value=configvariable(&ARACHNEcfg,"ScreenSaverStyle",NULL);

   j=0;
   while(j<cerfs) //deklarace car
   {
    xx[j]=100+RND(fullscr[2]-200);
    yy[j]=100+RND(fullscr[3]-200);

    if(*value=='C')
     x2[j]=10+RND(fullscr[3]/3);
    else
    {
     x2[j]=120+RND(fullscr[2]-240);
     y2[j]=120+RND(fullscr[3]-240);
    }

    if(*value=='R')
     {xs[j]=RND(2);if(xs[j]==0)xs[j]=-1;}
    else
     {xs[j]=RND(3);if(xs[j]==2)xs[j]=-1;}
    ys[j]=RND(2);if(ys[j]==0)ys[j]=-1;

    xs2[j]=RND(2);if(xs2[j]==0)xs2[j]=-1;
    if(*value=='R')
     {ys2[j]=RND(2);if(ys2[j]==0)ys2[j]=-1;}
    else
     {ys2[j]=RND(3);if(ys2[j]==2)ys2[j]=-1;}
    col[j]=barva[RND(6)];
    pom=RND(MAX_TRACK-10)+10;
    tracklen[j]=pom;
    trackcnt[j]=1; //odsud se bude cist
    trackbuf[j]=0; //sem se bude zapisovat
    while(pom>=0)
    {
     xtr[j][pom]=0;
     ytr[j][pom]=0;
     xt2[j][pom]=0;
     yt2[j][pom]=0;
     pom--;
    }
    j+=1;
   }//loop
   j=0;

   ImouseRead( &x, &y );
   ImouseWait();
   px=x;py=y;
   while(!done) //animace
   {
    if(wait!=NULL)
    {
#ifdef POSIX
     time_t t=time(NULL);
     struct tm *gt=gmtime(&t);
    
     sprintf(cas2,"%2d:%02d:%02d",
      gt->tm_hour, gt->tm_min, gt->tm_sec );
#else
     gettime(&t);
     sprintf(cas2,"%2d:%02d:%02d", t.ti_hour, t.ti_min, t.ti_sec );
#endif
     if(strstr(wait,cas2)!=NULL)break;
    }//endif

#ifndef LINUX
    if(g_PrtScr)
    {
     g_PrtScr = 0;
     PrintScreen2BMP(0);
     goto out;
    }
#endif
    
    //mazani stopy
    x_setcolor(0);
#ifndef LINUX    
    if(*value=='C')
     x_circle(xtr[j][trackcnt[j]],ytr[j][trackcnt[j]],xt2[j][trackcnt[j]]);
    else
#endif    
    if(*value=='R')
     x_rect(xtr[j][trackcnt[j]],ytr[j][trackcnt[j]],xt2[j][trackcnt[j]],yt2[j][trackcnt[j]]);
    else
     x_line(xtr[j][trackcnt[j]],ytr[j][trackcnt[j]],xt2[j][trackcnt[j]],yt2[j][trackcnt[j]]);
    if(++trackcnt[j]>tracklen[j])trackcnt[j]=0;
    xtr[j][trackbuf[j]]=xx[j];
    ytr[j][trackbuf[j]]=yy[j];
    xt2[j][trackbuf[j]]=x2[j];
    yt2[j][trackbuf[j]]=y2[j];
    if(++trackbuf[j]>tracklen[j])trackbuf[j]=0;

    //kresleni nove cary
    x_setcolor(col[j]);
#ifndef LINUX
    if(*value=='C')
     x_circle(xx[j],yy[j],x2[j]);
    else 
#endif
    if(*value=='R')
     x_rect(xx[j],yy[j],x2[j],y2[j]);
    else
     x_line(xx[j],yy[j],x2[j],y2[j]);
    xx[j]+=xs[j];
    yy[j]+=ys[j];
    x2[j]+=xs2[j];
    y2[j]+=ys2[j];
    if(xx[j]>=fullscr[2]||xx[j]<=0)xs[j]=-xs[j];
    if(yy[j]>=fullscr[3]||yy[j]<=0)ys[j]=-ys[j];
    if(x2[j]>=fullscr[2]||x2[j]<=0)xs2[j]=-xs2[j];
    if(y2[j]>=fullscr[3]||y2[j]<=0)ys2[j]=-ys2[j];
    j++;
    if(j==cerfs)
     j=0;

    if(*value=='C' || j%10==0)
    {
//!!RAY: Sep 30, 2006 -- CTRL key will now deactivate the screensaver
     if((bioskey(1) || bioskey(2) &4) || ImouseRead( &x, &y ) || x!=px || y!=py)
//     if(bioskey(1) || ImouseRead( &x, &y ) || x!=px || y!=py)
      done=1;
    }
    px=x;py=y;

#ifdef HICOLOR
   if(xg_256 == MM_Hic)
   {
    if(p>20*cerfs)
    {
     dc=-dc;
     p=0;
    }
    p++;
    if(p%cerfs==0)
    {
     int c=1;
     while(c<16)
     {
      if(c%2)
       dc=-dc;
      Iipal[c*3]+=dc;
      if(Iipal[c*3]>63)
       Iipal[c*3]=63;
      if(Iipal[c*3]<0)
       Iipal[c*3]=0;
      Iipal[c*3+1]+=dc;
      if(Iipal[c*3+1]>63)
       Iipal[c*3+1]=63;
      if(Iipal[c*3+1]<0)
       Iipal[c*3+1]=0;
      Iipal[c*3+2]+=dc;
      if(Iipal[c*3+2]>63)
       Iipal[c*3+2]=63;
      if(Iipal[c*3+2]<0)
       Iipal[c*3+2]=0;
      c++;
     }//loop
    }
    x_palett( 16, Iipal);
   }
#endif

   }//loop
   if(bioskey(1))bioskey(0);
   ImouseWait();
   out:
#ifdef HICOLOR
   if(xg_256 == MM_Hic)
    initpalette();
#endif
   x_cleardev();
   RedrawALL();
   DrawTitle(1);
   if(lasttime[1]=='*')
    redraw=4;
   else
    redraw=3;
  }
 }
  SecondsSleeping=0l;
 }//endif screensaver
#endif// AGB
#endif// CLEMTEST

#ifndef GGI //it doesn't make sense to show time in X11 app..
 if(!fullscreen)
 {
  x_setfill(0,7); //sediva
  if(mousey>x_maxy()-30 && mousex>x_maxx()-230)
   mouseoff();
 #ifdef CUSTOMER
  x_bar(x_maxx()-56,x_maxy()-13,x_maxx()-2,x_maxy()-2);
  x_setcolor(0); //cerna
  htmlfont(1,0);
  x_text_ib( x_maxx()-56,x_maxy()-15,(unsigned char *)cas2);

 #elif AGB

  x_bar(x_maxx()-56,x_maxy()-13,x_maxx()-2,x_maxy()-2);
  x_setcolor(0); //cerna
  htmlfont(1,0);
  x_text_ib( x_maxx()-56,x_maxy()-15,(unsigned char *)cas2);

 #else

  x_bar(x_maxx()-206,x_maxy()-13,x_maxx()-156,x_maxy()-2);
  x_setcolor(0); //cerna
//!!glennmcc: Aug 22, 2005
//prevent fontshift >0 from causing the clock to go 'off the right'
  htmlfont(0-user_interface.fontshift,0);
//  htmlfont(1,0);
  x_text_ib( x_maxx()-206,x_maxy()-15,(unsigned char *)cas2);

 #endif
  if(mousey>x_maxy()-30 && mousex>x_maxx()-230)
   mouseon();
 }
#endif

 if(lasttime[0]) //not if time redraw was forced!
 {
  SecondsSleeping++;
  if(GLOBAL.timeout)
   GLOBAL.secondsleft--;
  if(ppplogtime && tcpip)
   draw_time_online();
 }

 strcpy(lasttime,cas2);
}//end sub
Exemple #24
0
/*
 * main:
 *      Drive the sucker.  There are two main modes -- either we store
 *      the seek pointers, if the table is to be sorted or randomized,
 *      or we write the pointer directly to the file, if we are to stay
 *      in file order.  If the former, we allocate and re-allocate in
 *      CHUNKSIZE blocks; if the latter, we just write each pointer,
 *      and then seek back to the beginning to write in the table.
 */
int main(int ac, char **av)
{
    register unsigned char *sp;
    register FILE *inf, *outf;
    register int32_t last_off, length, pos, *p;
    register int first, cnt;
    register char *nsp;
    register STR *fp;
    static char string[257];

    getargs(ac, av);		/* evalute arguments */
    if ((inf = fopen(Infile, "r")) == NULL)
    {
	perror(Infile);
	exit(1);
    }

    if ((outf = fopen(Outfile, "w")) == NULL)
    {
	perror(Outfile);
	exit(1);
    }
    if (!STORING_PTRS)
	(void) fseek(outf, sizeof Tbl, 0);

    /*
     * Write the strings onto the file
     */

    Tbl.str_longlen = 0;
    Tbl.str_shortlen = (unsigned int) 0xffffffff;
    Tbl.str_delim = Delimch;
    Tbl.str_version = VERSION;
    first = Oflag;
    add_offset(outf, ftell(inf));
    last_off = 0;
    do
    {
	sp = (unsigned char*)fgets(string, 256, inf);
	if (sp == NULL || STR_ENDSTRING(sp, Tbl))
	{
	    pos = ftell(inf);
	    length = pos - last_off - (sp ? strlen((const char*)sp) : 0);
	    if (!length)
		/* Here's where we go back and fix things, if the
		 * 'fortune' just read was the null string.
		 * We had to make the assignment of last_off slightly
		 * redundant to achieve this.
		 */
	    {
		if (pos - last_off == 2)
		    fix_last_offset(outf, pos);
		last_off = pos;
		continue;
	    }
	    last_off = pos;
	    add_offset(outf, pos);
	    if (Tbl.str_longlen < length)
		Tbl.str_longlen = length;
	    if (Tbl.str_shortlen > length)
		Tbl.str_shortlen = length;
	    first = Oflag;
	}
	else if (first)
	{
	    for (nsp = (char*)sp; !isalnum(*nsp); nsp++)
		continue;
	    ALLOC(Firstch, Num_pts);
	    fp = &Firstch[Num_pts - 1];
	    if (Iflag && isupper(*nsp))
		fp->first = tolower(*nsp);
	    else
		fp->first = *nsp;
	    fp->pos = Seekpts[Num_pts - 1];
	    first = FALSE;
	}
    }
    while (sp != NULL);

    /*
     * write the tables in
     */

    fclose(inf);

    if (Oflag)
	do_order();
    else if (Rflag)
	randomize();

    if (Xflag)
	Tbl.str_flags |= STR_ROTATED;

    if (!Sflag)
    {
	printf("\"%s\" created\n", Outfile);
	if (Num_pts == 1)
	    puts("There was no string");
	else
	{
	    if (Num_pts == 2)
		puts("There was 1 string");
	    else
		printf("There were %ld strings\n", Num_pts - 1);
	    printf("Longest string: %u byte%s\n", Tbl.str_longlen, 
		Tbl.str_longlen == 1 ? "" : "s");
	    printf("Shortest string: %u byte%s\n", Tbl.str_shortlen,
		Tbl.str_shortlen == 1 ? "" : "s");
	}
    }

    fseek(outf, (off_t) 0, 0);
    Tbl.str_version = htonl(Tbl.str_version);
    Tbl.str_numstr = htonl(Num_pts - 1);
    /* Look, Ma!  After using the variable three times, let's store
     * something in it!
     */
    Tbl.str_longlen = htonl(Tbl.str_longlen);
    Tbl.str_shortlen = htonl(Tbl.str_shortlen);
    Tbl.str_flags = htonl(Tbl.str_flags);
    fwrite(&Tbl.str_version,  sizeof Tbl.str_version,  1, outf);
    fwrite(&Tbl.str_numstr,   sizeof Tbl.str_numstr,   1, outf);
    fwrite(&Tbl.str_longlen,  sizeof Tbl.str_longlen,  1, outf);
    fwrite(&Tbl.str_shortlen, sizeof Tbl.str_shortlen, 1, outf);
    fwrite(&Tbl.str_flags,    sizeof Tbl.str_flags,    1, outf);
    fwrite( Tbl.stuff,        sizeof Tbl.stuff,        1, outf);
    if (STORING_PTRS)
    {
	for (p = Seekpts, cnt = Num_pts; cnt--; ++p)
	{
	    *p = htonl(*p);
	    fwrite(p, sizeof *p, 1, outf);
	}
    }
    fclose(outf);
    exit(0);
}
Exemple #25
0
/*-------------------------------------------------------------------------*/
int
main(int argc, char *argv[])

/* The main program and -loop of the ERQ.
 */

{
    int num;

    master_pid = getpid();

    /* Print information about this daemon to help debugging */
    {
        fprintf(stderr, "%s XERQ %s: Path '%s', debuglevel %d\n"
                      , time_stamp(), __DATE__, argv[0], ERQ_DEBUG
                );
    }

    /* Quick and dirty commandline parser */
    {
        int is_forked = 0;
        int i;

        for (i = 1; i < argc; i++)
        {
            if (!strcmp(argv[i], "--forked"))
                is_forked = 1;
            else if (!strcmp(argv[i], "--execdir"))
            {
                if (i+1 >= argc)
                {
                    fprintf(stderr, "%s Missing value for --execdir.\n"
                                  , time_stamp());
                    die();
                }
                erq_dir = argv[i+1];
                i++;
            }
            else
            {
                fprintf(stderr, "%s Unknown argument '%s'.\n"
                              , time_stamp(), argv[i]);
                die();
            }
        }
        /* Check if we have been forked off the driver */
        if (is_forked)
        {
            write(1, "1", 1); /* indicate sucessful fork/execl */
            fprintf(stderr, "%s Demon started\n", time_stamp() );
        }
        else
        {
            fprintf(stderr, "%s Dynamic attachment unimplemented\n"
                          , time_stamp());
            die();
        }
    }

    /* Initialize */
    
    in_select = 0;
    pending_sig = 0;

    signal(SIGCLD, sig_child);
    signal(SIGPIPE, SIG_IGN);

    sockets = NULL;
    childs = NULL;
    retries = NULL;
    stdout_queue = NULL;
    
    randomize(time(0));
    seq_number = get_ticket();
    seq_interval = get_ticket() | 1; /* make sure it is odd */

#ifdef DETACH
    /* Detach from console */
    num = open("/dev/tty", O_RDWR);
    if (num >= 0) {
        ioctl(num, TIOCNOTTY, 0);
        close(num);
    }
#endif

    /* The main loop */
    
    while(1)
    {
        fd_set read_fds, write_fds;
        int num_fds;
        child_t *chp;
        retry_t *rtp, **rtpp;
        socket_t *sp;
        struct timeval timeout;

        /* Clean up the list of children (may close some sockets) */
        
        for (chp = childs; chp;)
        {
            child_t *this = chp;

            chp = chp->next;

            /* If there is a pending SIG_CLD for this child, handle it.
             * This is to be expected for CHILD_FORK children.
             */
            if (pending_sig && this->pid == pending_pid)
            {
                if (this->type != CHILD_FORK)
                    fprintf(stderr, "%s Pending SIG_CLD for pid %d delivered.\n"
                                  , time_stamp(), pending_pid);
                this->status = pending_status;
                this->pid = pending_pid;
                pending_sig = 0;
            }

            if (this->status == CHILD_EXITED)
            {
                XPRINTF((stderr, "%s Child %p exited.\n", time_stamp(), this));
                remove_child(this); /* will also unlink it from the list */
            }
        }

        /* look for sockets to select on */

        FD_ZERO(&read_fds);
        FD_ZERO(&write_fds);

        FD_SET(0, &read_fds);
        if (stdout_queue)
            FD_SET(1, &write_fds);

        num_fds = 2;
        for (sp = sockets; sp; sp = sp->next)
        {
            switch(sp->type)
            {
            case SOCKET_WAIT_CONNECT:
            case SOCKET_WAIT_AUTH:
                FD_SET(sp->fd, &write_fds);
                FD_SET(sp->fd, &read_fds);
                if (sp->fd >= num_fds)
                    num_fds=sp->fd+1;
                break;

            default:
                FD_SET(sp->fd, &read_fds);
                if (sp->fd >= num_fds)
                    num_fds=sp->fd+1;
                break;

            case SOCKET_WAIT_ACCEPT:
                /* do nothing */;
                /* Without the ; above, Metrowerks Codewarrior reports
                 * an error :-( */
            }

            if (sp->queue)
                FD_SET(sp->fd, &write_fds);
        } /* for (sockets) */

        /* Scan the list of pending retries for the soonest one.
         * Put the time till then into timeout.
         * (If the list is empty, select() will receive NULL for timeout).
         */
        if (retries)
        {
            time_t t;

            t = retries->time;
            for (rtp = retries; rtp; rtp = rtp->next)
            {
                if (rtp->time < t)
                    t = rtp->time;
            }
            timeout.tv_sec = t - time(NULL);
            timeout.tv_usec = 0;
            XPRINTF((stderr, "%s Soonest retry_t: in %ld seconds.\n"
                           , time_stamp(), (long)timeout.tv_sec));
			   
            if (timeout.tv_sec < 0)
                timeout.tv_sec = 0;
        }

#if ERQ_DEBUG > 1
        fprintf(stderr, "%s select()\n", time_stamp());
#endif
        in_select = 1; /* so sig_child() can write reply directly */
        num = select(num_fds, &read_fds, &write_fds, 0, retries ? &timeout : 0);
        in_select = 0; /* don't want sig_child() writing now */

#if ERQ_DEBUG > 1
        {
            int myerrno = errno;
            fprintf(stderr, "%s select() returns %d, time() %ld\n"
                          , time_stamp(), num, (long)time(NULL));
            errno = myerrno;
        }
#endif

#if ERQ_DEBUG > 0
        if (num < 0)
	/* Give an error now, but don't abort this loop,
	 * because the retries have to be handled first.
	 */
        {
            int myerrno = errno;
            fprintf(stderr, "%s select() errno = %d", time_stamp(), errno);
            errno = myerrno;
            perror(" ");
        }
#endif
	
        /* Is stdout ready to write? Then flush the queue. */
        if (num >= 0 && FD_ISSET(1, &write_fds))
        {
            XPRINTF((stderr, "%s stdout_queue ready for flush.\n", time_stamp()));
            flush_queue(&stdout_queue, 1, 0);
        }

        /* Check for retries */
        for (rtpp = &retries; *rtpp; )
        {
            rtp = *rtpp;
            if (rtp->time <= time(NULL))
            {
                XPRINTF((stderr, "%s Call retry %p (time %ld)\n"
                               , time_stamp(), rtp, (long)rtp->time));
                (*(rtp->func))(rtp->mesg, read_32(rtp->mesg));
                *rtpp = rtp->next;
                free(rtp);
            }
            else
            {
                rtpp = &rtp->next;
            }
        }
	
        /* Error in select */
        if (num < 0)
            continue;

        /* check for input from driver */
        if (FD_ISSET(0, &read_fds))
        {
            XPRINTF((stderr, "%s New command from driver.\n", time_stamp()));
            erq_cmd();
        }

        /* Handle the ready sockets.
         * Remember that read_socket() may close the socket.
         */

        for (sp = sockets; sp; )
        {
            socket_t *this = sp;
            int rc;

            sp = sp->next;

            rc = 0;

            if (FD_ISSET(this->fd, &read_fds))
            {
                XPRINTF((stderr, "%s Socket %p (%d) ready for reading.\n"
                               , time_stamp(), this, this->fd));
                rc = read_socket(this, 0);
            }

            if (!rc && FD_ISSET(this->fd, &write_fds))
            {
                XPRINTF((stderr, "%s Socket %p (%d) ready for writing.\n"
                               , time_stamp(), this, this->fd));
                (void)read_socket(this, 1);
            }
        }
    } /* while(1) */

    /* NOTREACHED */
    
    return 0;
} /* main() */
void Tourelle::randomize(long frame)
{
	randomize(frame,frame+1);
}
Exemple #27
0
void main(int argc, char* argv[])
{
    int i;
    canStatus stat;
    char tmpS[256];

    // Default values.
    First = 0;
    Second = 1;
    Bitrate = 1000000;
    LoopCount = 1;

    Verbose = 2;
    QuitOnError = 1;

    ErrorsFound = 0;
    FirstHardwareType = 0;
    SecondHardwareType = 0;
    
    if (argc <= 1) Usage();
    
    // Parse the command line.
    for (i=1; i<argc; i++) {
        int tmp;
        char c;
        if (strcmp(argv[i], "-s") == 0) Verbose=0;
        else if (strcmp(argv[i], "-silent") == 0) Verbose=0;
        else if (strcmp(argv[i], "-i") == 0) QuitOnError = FALSE;
        else if (sscanf(argv[i], "-a%d%c", &tmp, &c) == 1) First = tmp;
        else if (sscanf(argv[i], "-b%d%c", &tmp, &c) == 1) Second = tmp;
        else if (sscanf(argv[i], "-B%d%c", &tmp, &c) == 1) Bitrate = tmp;
        else if (sscanf(argv[i], "-randomize=%d%c", &tmp, &c) == 1) srand(tmp);
        else if (sscanf(argv[i], "-r=%d%c", &tmp, &c) == 1) srand(tmp);
        else if (strcmp(argv[i], "-r") == 0) randomize();
        else if (strcmp(argv[i], "-randomize") == 0) randomize();
        else if (sscanf(argv[i], "-L%d%c", &tmp, &c) == 1) LoopCount = tmp;
        else if (sscanf(argv[i], "-L=%d%c", &tmp, &c) == 1) LoopCount = tmp;
        else Usage();
    }

    printf("Starting test of time stamps with Kvaser CANLIB API.\n");
    printf("Time stamp resolution:  10 us\n\n");
    
    stat = canLocateHardware();
    Check("canLocateHardware", stat);
    
    stat = canGetChannelData(First, canCHANNELDATA_CHANNEL_NAME, tmpS, sizeof(tmpS));
    Check("canGetChannelData", stat);
    if (Verbose) printf("First channel:  %s.\n", tmpS);
    
    stat = canGetChannelData(Second, canCHANNELDATA_CHANNEL_NAME, tmpS, sizeof(tmpS));
    Check("canGetChannelData", stat);
    if (Verbose) printf("Second channel: %s.\n", tmpS);
    
    stat = canGetChannelData(First, canCHANNELDATA_CARD_TYPE, &FirstHardwareType, sizeof(FirstHardwareType));
    Check("canLocateHardware", stat);
    
    stat = canGetChannelData(Second, canCHANNELDATA_CARD_TYPE, &SecondHardwareType, sizeof(SecondHardwareType));
    Check("canLocateHardware", stat);
    
    PerformTest(argc, argv);

    if (ErrorsFound) {
        printf("\nTest completed with %d ERRORS.\n", ErrorsFound);
    } else {
        printf("\nTest SUCCESSFULLY completed.\n");
    }
    exit(0);
}
void ofxSVGParticle::update() {
    static int frame = 0;
    
    positionSteps.clear();
    rotationSteps.clear();
    scaleSteps.clear();
    
     // Get spring-like attraction force
    ofVec3f a = (positionTarget - position) * springTension;
    if(a.lengthSquared() < 0.1 && mode == 1) {
        randomize();
        update();
        return;
    }

    
    // Get perlin noise force
    float noiseValue = (ofNoise((center.x + position.x) / 1000.,
                       (center.y + position.y) / 1000.,
                       frame / 1000.) * 2 - 1) * 15;
    ofVec3f fNoise(cos(noiseValue) * noiseScale, sin(noiseValue) * noiseScale);

    a += fNoise;
    

    positionVelocity += a;    // Accelerate
    positionVelocity *= 0.9;  // Drag

    ofVec3f oldPosition(position);
    position += positionVelocity * 0.1;

    float rotationDiff = rotationTarget - rotation;
    while(rotationDiff > M_PI) rotationDiff -= M_PI*2;
    while(rotationDiff < -M_PI) rotationDiff += M_PI*2;

    float rA = rotationDiff * 0.1;
    rA += noiseValue * noiseScale / 10000.0f;
    
    rotationVelocity += rA;
    rotationVelocity *= 0.8;
    
    float oldRotation = rotation;
    rotation += rotationVelocity;
    
    if(blur) {
        // Linear interpolation for motion blur steps
        
        // First, figure out how many steps are needed based on translation and rotation distance
        ofVec3f dP = position - oldPosition;
        float dR = rotation - oldRotation;
        
        blurSteps = (int)max((int)dP.length() / 2, (int)abs((ofRadToDeg(dR) / 4)));
        
        for(int i=blurSteps-1; i>=0; i--) {
            positionSteps.push_back(oldPosition + (dP * (1 + i/(float)blurSteps)) / 2); // 180 degree shutter angle
            //positionSteps.push_back(oldPosition + (dP * i/(float)blurSteps));         // 360 degree shutter angle
            rotationSteps.push_back(oldRotation + (dR * (1 + i/(float)blurSteps)) / 2); // 180 degree shutter angle
            //rotationSteps.push_back(oldRotation + (dR * i/(float)blurSteps));         // 360 degree shutter angle
        }
    }
    
    frame++;
}
Exemple #29
0
void main()
{
	int x1[NR_OF_SEGMENTS], y1[NR_OF_SEGMENTS];
	int x2[NR_OF_SEGMENTS], y2[NR_OF_SEGMENTS];
	int color[NR_OF_SEGMENTS];
	char ch;
	int gata = 0;
	int x = 0;
	int y = 0;
    
	initialize_graphic_mode();

	setwritemode(XOR_PUT);

	// Se genereaza NR_OF_SEGMENTS segmente aleatoare.
	randomize();
	for (int i = 0; i < NR_OF_SEGMENTS; i++)
	{
		x1[i] = random(640);
		y1[i] = random(480);
		x2[i] = random(640);
		y2[i] = random(480);
		do
		{
			color[i] = random(16);
		}
		while (color[i] == 0);
	}

	// Se deseneaza segemntele generate anterior pe ecran
	for (i = 0; i < NR_OF_SEGMENTS; i++)
	{
		setcolor(color[i]);
		line(x1[i], y1[i], x2[i], y2[i]);
	}

	// Se deseneaza dreptunghiul selector
	setcolor(MAGENTA);
	rectangle(x, y, LENGTH, WIDTH);

	// Se permite miscarea dreptunghiului sus/jos, stanga/dreapta pana
	// la apasarea tastei ENTER.
	while (!gata)
	{
		// citirea tastei apasate de utilizator
		ch = getch();
		if (ch == 0)
		{
			ch = getch();
			switch (ch)
			{
				// deplasare in sus a dreptunghiului
				case 72:
					if ((y-STEP) >= 0)
					{
						rectangle(x, y, x+LENGTH, y+WIDTH);
						y = y-STEP;
						rectangle(x, y, x+LENGTH, y+WIDTH);
					}
					break;
				// deplasare in jos a dreptunghiului
				case 80:
					if ((y+WIDTH+STEP) <= getmaxy())
					{
						rectangle(x, y, x+LENGTH, y+WIDTH);
						y = y+STEP;
						rectangle(x, y, x+LENGTH, y+WIDTH);
					}
					break;
				// deplasare in stanga a dreptunghiului
				case 75:
					if ((x-STEP) >= 0)
					{
						rectangle(x, y, x+LENGTH, y+WIDTH);
						x = x-STEP;
						rectangle(x, y, x+LENGTH, y+WIDTH);
					}
					break;
				// deplasare in dreapta a dreptunghiului
				case 77:
					if ((x+LENGTH+STEP) <= getmaxx())
					{
						rectangle(x, y, x+LENGTH, y+WIDTH);
						x = x+STEP;
						rectangle(x, y, x+LENGTH, y+WIDTH);
					}
					break;
			}
		}
		else
		{
			if (ch == 13)
			{
				gata = 1;
			}
		}
	}

	// Se sterg toate segmentele de pe ecran.
	for (i = 0; i < NR_OF_SEGMENTS; i++)
	{
		setcolor(color[i]);
		line(x1[i], y1[i], x2[i], y2[i]);
	}

	// Se aplica pe fiecare segment algoritmul Cohen-Sutherland.
	for (i = 0; i < NR_OF_SEGMENTS; i++)
	{
		Cohen_Sutherland_algorithm(x1[i], y1[i], x2[i], y2[i],
			x+1, y+1, x+LENGTH-1, y+WIDTH-1, &x1[i], &y1[i], &x2[i], &y2[i]);
	}

	// Se redeseneaza doar acele parti din segmente care se afla
	// in dreptunghi.
	for (i = 0; i < NR_OF_SEGMENTS; i++)
	{
		setcolor(color[i]);
		line(x1[i], y1[i], x2[i], y2[i]);
	}

	getch();
}
void main()
{
   char szName[80];
   unsigned char szHolder[500], nSpaceCount = 0, nHighestVal = 0, nTot = 0;
   long lPos = 0, lToSkip;

   randomize();
   printf("Enter Sysop name   >");
   gets(szName);

   if ( strlen(szName) < 3 )
      exit(0);

   for ( short n = 0; n < strlen(szName); n++ )
      {
      if ( szName[n] == ' ' )
         nSpaceCount++;
      if ( szName[n] > nHighestVal )
         nHighestVal = szName[n];
      nTot += szName[n]/2;
      }

   szHolder[lPos++] = encode(strlen(szName), 0);
   szHolder[lPos++] = encode(nSpaceCount, 1);
   szHolder[lPos++] = encode(szName[2], 2);
   szHolder[lPos++] = encode(szName[strlen(szName)-1], 3);
   szHolder[lPos++] = encode(nHighestVal, 4);
   szHolder[lPos++] = encode(strlen(szName), 5);
   szHolder[lPos++] = encode(nTot, 6);
   
   strrev(szName);
   
   for ( short n = 0; n < strlen(szName); n++ )
      {
      szHolder[lPos] = encode(szName[n], lPos);
      lPos++;
      szHolder[lPos] = random(204) + 50;
      lToSkip = szHolder[lPos] / 50;
      szHolder[lPos] = ~szHolder[lPos];
      lPos++;

      unsigned char nSum = 7;
      for ( short k = 0; k < lToSkip; k++ )
         {
         szHolder[lPos] = random(250);
         nSum += szHolder[lPos]/6;
         lPos++;
         }
      szHolder[lPos++] = nSum;
      }

   fstream myFile;
   myFile.open("e:\\ttreg.dat", ios::binary | ios::out | ios::trunc );
   myFile.write(szHolder, lPos);
   myFile.close();

   myFile.open("e:\\doors\\trivia\\regs.log", ios::out | ios::app);
   myFile.write(strrev(szName), strlen(szName));
   char szText[120], szFullDate[12];
   _strdate(szFullDate);
   sprintf(szText, "\n  Registered on %s\n", szFullDate);
   myFile.write(szText, strlen(szText));
   sprintf(szText, "  File size: %ld\n  First ten bytes: ", lPos);
   for ( short n = 0; n < 10; n++ )
      {
      sprintf(szFullDate, "%u ", szHolder[n]);
      strcat(szText, szFullDate);
      }
   strcat(szText, "\n\n");
   myFile.write(szText, strlen(szText));
   printf("\nFile created and logged.\n");

   char szCheckName[80];
   short nStatus = getRegName(szCheckName, szHolder, lPos);
   printf("  -> Reg status: %d; %s.\n\n", nStatus, szCheckName);
}