Exemple #1
0
int direc()
{
 d= rand() % (HIGH - LOW + 1) + LOW;
 
 if(d!=b)
   { 
    b=d;
    return d;
   }
 else
 { int e;
   e = direc();
   return e;
   }
}
Exemple #2
0
// Constructor
BoundaryObject::BoundaryObject(MatrixXd scl, MatrixXd rot, Vector3d pos, Vector3d rgb, 
                               float a, float ee, float nn, boundary_t b, float d) : 
                               Object(scl, rot, pos, rgb, a, ee, nn)
{
    bot = b;
    if (d <= 1 && d >= 0)
        dampening = d;
    else
        dampening = 0.9;
        
    int ind = 0;
    int sign = 1;
    Vector3d direc(0, 0, 0);
    switch (bot) {
        case GROUND:
            direc(1) = 1;
            ind = 1;
            break;
        case CEILING:
            direc(1) = -1;
            ind = 1;
            break;
        case WALL_LEFT:
            direc(0) = 1;
            ind = 0;
            break;
        case WALL_RIGHT:
            direc(0) = -1;
            ind = 0;
            break;
        case WALL_FRONT:
            direc(2) = 1;
            ind = 2;
            break;
        case WALL_BACK:
            direc(2) = -1;
            ind = 2;
            break;
        default:
            direc(0) = 0;
            break;
    }
    Vector3d point = this->getFarthestPointInDirection(direc);
    boundary = point(ind);
}
/** If m_fullTest=true if checks that the files exists, otherwise just that path syntax looks valid
 *  @param value :: file name
 *  @returns An error message to display to users or an empty string on no error
 */
std::string FileValidator::checkValidity(const std::string &value) const
{
  // Check if the path is syntactically valid
  if( !Poco::Path().tryParse(value) )
  {
    return "Error in path syntax: \"" + value + "\".";
  }
  
  //Check the extension but just issue a warning if it is not one of the suggested values
  if (!(value.empty()))
  {
    if (!(this->endswith(value)))
    {
      //Dropped from warning to debug level as it was printing out on every search of the archive, even when successful. re #5998
      g_log.debug() << "Unrecognised extension in file \"" << value << "\"";
      if (!this->m_extensions.empty()) {
        g_log.debug() << " [ ";
        for (std::set<std::string>::const_iterator it = this->m_extensions.begin(); it != this->m_extensions.end(); ++it)
          g_log.debug() << *it << " ";
        g_log.debug() << "]";
      }
      g_log.debug() << "\"."  << std::endl;
    }
  }

  // create a variable for the absolute path to be used in error messages
  std::string abspath(value);
  if (!value.empty())
  {
    Poco::Path path(value);
    if (path.isAbsolute())
      abspath = path.toString();
  }

  //If the file is required to exist check it is there
  if ( m_testExist && ( value.empty() || !Poco::File(value).exists() ) )
  {
    return "File \"" + abspath + "\" not found";
  }

  //If the file is required to be writable...
  if (m_testCanWrite)
  {
    if (value.empty())
      return "Cannot write to empty filename";

    Poco::File file(value);
    // the check for writable is different for whether or not a version exists
    // this is taken from ConfigService near line 443
    if (file.exists())
    {
      try
      {
        if (!file.canWrite())
          return "File \"" + abspath + "\" cannot be written";
      }
      catch (std::exception &e)
      {
        g_log.information() << "Encountered exception while checking for writable: " << e.what();
      }
    }
    else // if the file doesn't exist try to temporarily create one
    {
      try
      {
        Poco::Path direc(value);
        if (direc.isAbsolute())
        {
          // see if file is writable
          if (Poco::File(direc).canWrite())
            return "";
          else
            return "Cannot write to file \"" + direc.toString() + "\"";
        }

        g_log.debug() << "Do not have enough information to validate \""
                      << abspath << "\"\n";
      }
      catch (std::exception &e)
      {
        g_log.information() << "Encountered exception while checking for writable: " << e.what();
      }
      catch (...) {
    	g_log.information() << "Unknown exception while checking for writable";
      }
    }
  }

  //Otherwise we are okay, file extensions are just a suggestion so no validation on them is necessary
  return "";
}
// Callback which draws the label of the grid
void viewportEdgeIntersectCallback(const Vec3d& screenPos, const Vec3d& direction, void* userData)
{
	ViewportEdgeIntersectCallbackData* d = static_cast<ViewportEdgeIntersectCallbackData*>(userData);
	Vec3d direc(direction);
	direc.normalize();
	const Vec4f tmpColor = d->sPainter->getColor();
	d->sPainter->setColor(d->textColor[0], d->textColor[1], d->textColor[2], d->textColor[3]);
	bool withDecimalDegree = dynamic_cast<StelGui*>(StelApp::getInstance().getGui())->getFlagShowDecimalDegrees();

	QString text;
	if (d->text.isEmpty())
	{
		// We are in the case of meridians, we need to determine which of the 2 labels (3h or 15h to use)
		Vec3d tmpV;
		d->sPainter->getProjector()->unProject(screenPos, tmpV);
		double lon, lat, textAngle;
		StelUtils::rectToSphe(&lon, &lat, tmpV);
		switch (d->frameType)
		{
			case StelCore::FrameAltAz:
			{
				double raAngle = ::fmod(M_PI-d->raAngle,2.*M_PI);
				lon = ::fmod(M_PI-lon,2.*M_PI);

				if (std::fabs(2.*M_PI-lon)<0.001) // We are at meridian 0
					lon = 0.;

				const double delta = raAngle<M_PI ? M_PI : -M_PI;				
				if (std::fabs(lon-raAngle) < 0.01 || (lon==0. && raAngle!=M_PI))					
					textAngle = raAngle;
				else
					textAngle = raAngle+delta;

				if (raAngle==2*M_PI && delta==-M_PI)
					textAngle = 0;

				if (withDecimalDegree)
					text = StelUtils::radToDecDegStr(textAngle);
				else
					text = StelUtils::radToDmsStrAdapt(textAngle);

				break;			
			}
			case StelCore::FrameObservercentricEcliptic:						
			{
				double raAngle = d->raAngle;
				if (raAngle<0.)
					raAngle += 2.*M_PI;

				if (lon<0.)
					lon += 2*M_PI;

				if (std::fabs(2.*M_PI-lon)<0.001) // We are at meridian 0
					lon = 0.;

				const double delta = raAngle<M_PI ? M_PI : -M_PI;
				if (std::fabs(lon-raAngle) < 1. || lon==0.)
					textAngle = raAngle;
				else
					textAngle = raAngle+delta;

				if (raAngle==2*M_PI && delta==-M_PI)
					textAngle = 0;

				if (withDecimalDegree)
					text = StelUtils::radToDecDegStr(textAngle);
				else
					text = StelUtils::radToDmsStrAdapt(textAngle);

				break;			
			}
			case StelCore::FrameGalactic:
			{
				double raAngle = M_PI-d->raAngle;
				lon = M_PI-lon;

				if (raAngle<0)
					raAngle=+2.*M_PI;

				if (lon<0)
					lon=+2.*M_PI;

				if (std::fabs(2.*M_PI-lon)<0.01) // We are at meridian 0
					lon = 0.;

				if (std::fabs(lon-raAngle) < 0.01)
					textAngle = -raAngle+M_PI;
				else
				{
					const double delta = raAngle<M_PI ? M_PI : -M_PI;
					textAngle = -raAngle-delta+M_PI;
				}

				if (withDecimalDegree)
					text = StelUtils::radToDecDegStr(textAngle);
				else
					text = StelUtils::radToDmsStrAdapt(textAngle);
				break;
			}
			default:			
			{
				if (std::fabs(2.*M_PI-lon)<0.001)
				{
					// We are at meridian 0
					lon = 0.;
				}
				const double delta = d->raAngle<M_PI ? M_PI : -M_PI;
				if (std::fabs(lon-d->raAngle) < 1. || lon==0. || d->raAngle==M_PI)
					textAngle = d->raAngle;
				else
					textAngle = d->raAngle+delta;

				if (d->raAngle+delta==0.)
					textAngle = M_PI;

				if (withDecimalDegree)
					text = StelUtils::radToDecDegStr(textAngle,false,true);
				else
					text = StelUtils::radToHmsStrAdapt(textAngle);
			}
		}
	}
	else
		text = d->text;

	double angleDeg = std::atan2(-direc[1], -direc[0])*180./M_PI;
	float xshift=6.f;
	if (angleDeg>90. || angleDeg<-90.)
	{
		angleDeg+=180.;
		xshift=-d->sPainter->getFontMetrics().width(text)-6.f;
	}

	d->sPainter->drawText(screenPos[0], screenPos[1], text, angleDeg, xshift, 3);
	d->sPainter->setColor(tmpColor[0], tmpColor[1], tmpColor[2], tmpColor[3]);
	glDisable(GL_TEXTURE_2D);
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
Exemple #5
0
main()
{    
      
time_t seconds;          //Declare variable to hold seconds on clock.

time(&seconds);          //Get value from system clock andplace in seconds variable.

srand((unsigned int) seconds);               //Convert seconds to a unsignedinteger.
 
  initwindow(1350, 700, "MAZE TRIAL");    
 floodfill(0,0,WHITE);
 
  int r=c=0; // Stores the values of rows and coloumns;
  int R,C; //No. of boxes
  
 /*setbkcolor(BLACK);
settextstyle(TRIPLEX_FONT,HORIZ_DIR,1);
outtextxy(500,5,"enter the ROWS ");
  
  char num[3];
 int i,k=1;
 
 while((i=getch())!=13)
    {
     r+=(i-48)*pow(10,k);
     k--;
    }
    cout<<r;
    
  num[0]=((r-(r%10))/10)+48;
  num[1]=(r%10)+48;
  num[2]='\0';
  
  outtextxy(500,5,"NUMBER OF ROWS ARE : ");
  outtextxy(500,20,num);
   
   getch();
   
   floodfill(0,0,BLUE);

 setbkcolor(BLACK);
settextstyle(TRIPLEX_FONT,HORIZ_DIR,1);
outtextxy(500,5,"enter the COLUMNS ");


 k=1;
 
 while((i=getch())!=13)
    {
     c+=(i-48)*pow(10,k);
     k--;
    }

  num[0]=((c-(c%10))/10)+48;
  num[1]=(c%10)+48;
  num[2]='\0';
  
  outtextxy(500,5,"NUMBER OF COLUMNS ARE : ");
  outtextxy(500,20,num);

getch();

 setbkcolor(WHITE);
settextstyle(TRIPLEX_FONT,HORIZ_DIR,1);


floodfill(0,0,BLUE);*/


  /*cout<<" Columns: ";
  cin>> c;*/
  R=r=10;
  C=c=10;
  
   
   
  while(1)
  {
     for(int i=0;i<r;i++)
     for(int j=0; j<c; j++)
        a[i][j]=0;
      
  stack adrs[1000];   //////////////////////////////////////////////////////////////////
             
      
  adrs[top].x=0;
  adrs[top].y=0;              // initially the address is 0,0   
   
  
  
  
     
     StartMenu();
     int ch;
     ch=getch();
     ch-=48;
     
     setfillstyle(SOLID_FILL,WHITE);
     floodfill(0,0,MAGENTA);
   
   setfillstyle(SOLID_FILL,WHITE);
  floodfill(0,0,BLACK);
  
  settextstyle(3,0,6);
  setbkcolor(WHITE);
  setcolor(BLACK);
  outtextxy(100,100,"Choose Level");
  setbkcolor(RED);
  setcolor(WHITE);
  outtextxy(500,100," 1 EASY ");
  setbkcolor(GREEN);
  setcolor(WHITE);
  outtextxy(750,100," 2 MEDIUM");
  setbkcolor(BLUE);
  setcolor(WHITE);
  outtextxy(1050,100," 3 HARD");
   
   int Level=getch();
   setfillstyle(SOLID_FILL,WHITE);
   floodfill(0,0,MAGENTA);
     
   switch(Level)
   {
    case 49: R=r=10;
             C=c=10;
             break;
             
    case 50: R=r=13;
             C=c=24;
             break;
             
    case 51: R=r=18;
             C=c=35;
             break;
   }
   
  r=(2*r)-1;
  c=(2*c)-1;
   
   basic_design(r,c,ch);
   //out_boundary(r,c);
   int H=1, L=3;
  
   out_boundary(r,c,ch);
      
 getch();
 
     a[0][0]=1;      //int k=0;
     
   while(1)
    { int ender=0;
     
     D=direc(); 
     //cout<<"Receiving "<<D<<"\n\n";
     //getch();
        
     //cout<<"Direction ? ";
     //cin>>D;
     
     switch(D)
     {  
        int nx,ny,ox,oy;
           
        case 1:
                                  
             cout<<"\n\nPresent TOP: "<<top;            //UP
             cout<<"\nPresent TOP x: "<<adrs[top].x;   
             cout<<"\nPresent TOP y: "<<adrs[top].y;
               
                if(adrs[top].x > 0) //if 1
                 {
                  nx = adrs[top].x-2;
                  ny = adrs[top].y;
                  ox = adrs[top].x;
                  oy = adrs[top].y;
                  
                 cout<<"\nFuture New: "<<nx<<ny<<"\n\n";
                  
                  if(nx==adrs[top-1].x && ny==adrs[top-1].y)// if 2
                    continue;
                  else// else 2
                    {
                     if( a[nx][ny] !=1 )//if 3
                       {
                        cout<<"\nOld: "<<ox<<oy;
                        cout<<"\nNew: "<<nx<<ny;
                        cout<<"\nMoved";
                        cout<<"\n\n";
                        
                        top++;
                        adrs[top].x = nx;
                        adrs[top].y = ny;
                        a[nx][ny]=1;
                        a[nx+1][ny]=1;
                        bx=nx+1;
                        by=ny;
                       // setcolor(WHITE);
                        //line(25+25*ny,50+25*nx,50+25*ny,50+25*nx);  
                        coord_cal(bx,by);  // panting the red brick -> white
                       }  // Pointer moved. Next iteration
                     else     //else 3
                      {
                       count++;
                       if(count==5)
                          {
                            count=0;
                           --top; 
                          }//if
                      }//else
                              //Pointer backtracked. Next iteration
                    }  
            
            }   
         break;

         
 
case 2:      
                    //right
       cout<<"\n\nPresent TOP: "<<top;
       cout<<"\nPresent TOP x: "<<adrs[top].x;   
             cout<<"\nPresent TOP y: "<<adrs[top].y;
         
           
                   
       if(adrs[top].y <c-1)
         {
          nx = adrs[top].x;
          ny = adrs[top].y+2;
          ox = adrs[top].x; 
          oy = adrs[top].y;
           
        
          cout<<"\nFuture New: "<<nx<<ny;
          cout<<"\n\n";     
           
                  
          if(top!=0)
            {
             if(nx==adrs[top-1].x && ny==adrs[top-1].y)   
               continue;                   
             else
               {
                if( a[nx][ny] !=1)
                  {
                    cout<<"\nOld: "<<ox<<oy;
                    cout<<"\nNew: "<<nx<<ny;
                    cout<<"Moved";
                    cout<<"\n\n";
               
                    top++;
                    adrs[top].x = nx;
                    adrs[top].y = ny;
                    a[nx][ny]=1;
                    a[nx][ny-1]=1;
                    bx=nx;
                    by=ny-1;
                    //setcolor(BLACK);
                    //line( 50+25*oy,25+25*ox,50+25*oy,50+25*ox );   
                     coord_cal(bx,by);   // panting the red brick -> white
                    // return; // return back to direction specifier.
                  }
                else
                 {count++;
                      if(count==5)
                      {
                        count=0;  --top;} }   //return; // return back to direction specifier
               }
            }
          else
          {
           top++;
           adrs[top].x = nx;
           adrs[top].y = ny;
           a[nx][ny]=1;
           a[nx][ny-1]=1;
                               bx=nx;
                    by=ny-1;
                            coord_cal(bx,by);
           //setcolor(BLACK);
           //line( 50+25*oy,25+25*ox,50+25*oy,50+25*ox );
          }
}         

     break;
  
  case 3:
                                 //DOWN
           cout<<"\n\nPresent TOP: "<<top;
           cout<<"\nPresent TOP x: "<<adrs[top].x;   
             cout<<"\nPresent TOP y: "<<adrs[top].y;
             
             
              
            if(adrs[top].x <r-1)
              {
               nx = adrs[top].x+2;
               ny = adrs[top].y;
               ox = adrs[top].x; 
               oy = adrs[top].y; 
               
        
               cout<<"\nFuture New: "<<nx<<ny;
               cout<<"\n\n";
                              
               if(top!=0)
            {
             if(nx==adrs[top-1].x && ny==adrs[top-1].y)   
               continue;                   
             else
               {
                if( a[nx][ny] !=1)
                  {
                    cout<<"\nOld: "<<ox<<oy;
                    cout<<"\nNew: "<<nx<<ny;
                    cout<<"Moved";
                    cout<<"\n\n";
               
                    top++;
                    adrs[top].x = nx;
                    adrs[top].y = ny;
                    a[nx][ny]=1;
                     a[nx-1][ny]=1;
                     bx=nx-1;
                     by=ny;
                    //setcolor(BLACK);
                   // line( 25+25*oy,50+25*ox,50+25*oy,50+25*ox ); 
                    coord_cal(bx,by);     // panting the red brick -> white
                    // return; // return back to direction specifier.
                  }
                else
                  {count++;
                      if(count==5)
                          { count=0;--top; } }   //return; // return back to direction specifier
               }
            }
          else
          {
           top++;
           adrs[top].x = nx;
           adrs[top].y = ny;
           a[nx][ny]=1;
           a[nx-1][ny]=1;
           bx=nx-1;
                     by=ny;
                    coord_cal(bx,by); 
       
       //    setcolor(BLACK);
         //  line( 25+25*oy,50+25*ox,50+25*oy,50+25*ox );
          }
          
}
     break;
     
case 4:            //left
           
            cout<<"\n\nPresent TOP: "<<top;
            cout<<"\nPresent TOP x: "<<adrs[top].x;   
            cout<<"\nPresent TOP y: "<<adrs[top].y;
            
            if(adrs[top].y >0)
              {
               nx = adrs[top].x;
               ny = adrs[top].y-2;
               ox = adrs[top].x; 
               oy = adrs[top].y; 
               
               cout<<"\nFuture New: "<<nx<<ny<<endl;
                     
               if(nx==adrs[top-1].x && ny==adrs[top-1].y) 
                 continue;
               else 
               {
                if( a[nx][ny] !=1)
                    {
                     cout<<"\nOld: "<<ox<<oy;
                     cout<<"\nNew: "<<nx<<ny;
                     cout<<"Moved";
                     cout<<"\n\n";
                     
                     top++;
                     adrs[top].x = nx;
                     adrs[top].y = ny;
                     a[nx][ny]=1;
                     a[nx][ny+1]=1;
                     bx=nx;
                     by=ny+1;
                     //setcolor(BLACK);
                    // line( 50+25*ny,25+25*nx,50+25*ny,50+25*nx );      
                     coord_cal(bx,by);// panting the red brick -> white
                     //return; // return back to direction specifier.
                    }
                  else
                     {count++;
                      if(count==5)
                       {count=0; --top;} } 
               }
                     //return; // return back to direction specifier.
                  
}
          
          break;
           
}//END OF switch()
           
    for(int i=0;i<r;i+=2)
     for(int j=0; j<c; j+=2)
        {  if(a[i][j]==1)
              ender++;
         }
             
    if(ender==(R*C))
         break;
    
    
      
                   
     
     
     
}// while loop ends
   
   lining_sqb(r, c,a,ch);
 
 
  out_boundary(r,c,ch);
    play(a,r,c,ch);
    // while (!kbhit( ))
       // delay(750);   //getch();
        
  setfillstyle(SOLID_FILL,WHITE);
  floodfill(0,0,MAGENTA);
    }
}  // END OF main()
Exemple #6
0
int   tomonster ()
{   register int i, dist, rr, cc, mdir = NONE, mbad = NONE;
    int   closest, which, danger = 0, adj = 0;
    char  monc = ':', monchar = ':', *monster;

    /* If no monsters, fail */
    if (mlistlen==0)
        return (0);

    /*
     * Loop through the monsters, 'which' and 'closest' record the index
     * and distance of the closest monster worth fighting.
     */

    for (i = 0, which = NONE, closest = 999; i < mlistlen; i++)
    {   dist = max (abs (mlist[i].mrow - atrow), abs (mlist[i].mcol - atcol));
        monchar = mlist[i].chr;

        /*
         * IF   we are not using a magic arrow OR
         *      we want to wake this monster up AND we can beat him OR
         *      he is standing near something we want and we will have to
         *        fight him anywhay
         * THEN consider fighting the monster.
         *
         * Don't pick fights with sleepers if cosmic.  DR UTexas 25 Jan 84
         */

        if (usingarrow || mlist[i].q == AWAKE ||
                (!cosmic && wanttowake (monchar) &&
                 (avghit (i) <= 50 || (maxhit (i) + 50 - k_wake) < Hp)) ||
                (mlist[i].q == HELD && Hp >= Hpmax))
        {   danger += maxhit(i);		/* track total danger */
            adj++;				/* count number of monsters */

            /* If he is the closest monster, save his index and distance */
            if (dist < closest)
            {
                closest = dist;
                which = i;
                monc = mlist[i].chr;
                mbad = avghit(i);
            }

            /* Or if he is meaner than another equally close monster, save him */
            else if (dist == closest && avghit(i) > avghit(which))
            {   dwait (D_BATTLE, "Chasing %c(%d) rather than %c(%d) at distance %d.",
                       mlist[i].chr, avghit(i), mlist[which].chr,
                       avghit(which), dist);

                closest = dist;
                which = i;
                monc = mlist[i].chr;
                mbad = avghit(i);
            }
        }
    }

    /* No monsters worth bothering, return failure */
    if (which < 0) return (0);

    /* Save the monsters location in registers */
    rr = mlist[which].mrow - atrow;
    cc = mlist[which].mcol - atcol;

    /* If the monster is on an exact diagonal, record direction */
    mdir = (rr==0 || cc==0 || abs(rr)==abs(cc)) ? direc (rr, cc) : -1;

    /* Get a string which names the monster */
    monster = monname (monc);

    /* If 'battlestations' has an action, use that action */
    if (battlestations (which, monster, mbad, danger, mdir, closest, 1, adj))
        return (1);

    /* If he is an odd number of squares away, lie in wait for him */
    if ((closest&1) == 0 && !lyinginwait)
    {   command (T_FIGHTING, "s");
        dwait (D_BATTLE, "Waiting for monster an odd number of squares away...");
        lyinginwait = 1;
        return (1);
    }

    /* "We have him! Move toward him!" */
    if (gotowards (mlist[which].mrow, mlist[which].mcol, 0))
    {   goalr = mlist[which].mrow;
        goalc = mlist[which].mcol;
        lyinginwait = 0;
        return (1);
    }

    /* Could not find a path to the monster, record failure */
    return (0);
}
Exemple #7
0
int   fightmonster ()
{   register int i, rr, cc, mdir = NONE, mbad  = NONE, danger = 0;
    int  melee = 0, adjacent = 0, alertmonster = 0;
    int  wanddir = NONE, m = NONE, howmean;
    char mon, monc = ':', *monster;

    /* Check for adjacent monsters */
    for (i = 0; i < mlistlen; i++)
    {   rr = mlist[i].mrow;
        cc = mlist[i].mcol;
        if (max (abs (atrow-rr), abs (atcol-cc)) == 1)
        {   if (mlist[i].q != ASLEEP)
            {   if (mlist[i].q != HELD || Hp >= Hpmax || !havefood (1))
                {   melee = 1;
                    if (mlist[i].q == AWAKE) alertmonster = 1;
                }
            }
        }
    }

    if (!melee) return (0);               /* No one to fight */

    /* Loop to find worst monster and tally danger & number adjacent */
    for (i = 0; i < mlistlen; i++)
    {   rr = mlist[i].mrow;
        cc = mlist[i].mcol;	/* Monster position */

        /*
         * If the monster is adjacent and is either awake or
         * we dont know yet whether he is asleep, but we havent
         * see any alert monsters yet.
         */

        if (max (abs (atrow-rr), abs (atcol-cc)) == 1 &&
                (alertmonster ? mlist[i].q == AWAKE :
                 mlist[i].q != ASLEEP)) /* DR Utexas 26 Jan 84 */
        {   mon = mlist[i].chr;		/* Record the monster type */
            monster = monname (mon);		/* Record the monster name */
            danger += maxhitchar(mon);	/* Add to the danger */

            /* If he is adjacent, add to the adj count */
            if (onrc (CANGO, rr, atcol) && onrc (CANGO, atrow, cc))
            {   adjacent++;
                howmean = isholder (monster) ? 10000 : avghit(i);

                /* If he is adjacent and the worst monster yet, save him */
                if ((howmean > mbad) || (mdir < 0))
                {   wanddir = mdir = direc (rr-atrow, cc-atcol);
                    monc = mon;
                    m = i;
                    mbad = howmean;
                }
            }

            /* If we havent yet a line of sight, check this guy out */
            else if (wanddir == NONE)
            {
                wanddir = direc (rr-atrow, cc-atcol);
            }

            /* Debugging breakpoint */
            dwait (D_BATTLE, "%c <%d,%d>, danger %d, worst %c(%d,%d), total %d",
                   screen[rr][cc], rr-atrow, cc-atcol,
                   danger, monc, mdir, mbad, adjacent);
        }
    }

    /*
     * The following variables have now been set:
     *
     * monc:      The letter of the worst monster we can hit
     * mbad:      Relative scale 0 to 26, how bad is (s)he
     * mdir:      Which direction to him/her
     * danger:    How many hit points can (s)he/they do this round?
     * wanddir:   Direction of worst monster, even if we cant move to it.
     */

    /*
     * Check whether the battlestations expert has a suggested action.
     */

    monster = monname (monc);
    if (battlestations (m, monster, mbad, danger, adjacent ? mdir : wanddir,
                        adjacent ? 1 : 2, alertmonster, max (1, adjacent)))
    {
        foughtmonster = DIDFIGHT;
        return (1);
    }

    /*
     * If we did not wait for him last turn, and he is not adjacent,
     * let him move to us (otherwise, he gets to hits us first).
     */

    if (!lyinginwait && !adjacent)
    {   command (T_FIGHTING, "s");
        dwait (D_BATTLE, "Lying in wait...");
        lyinginwait = 1;
        foughtmonster = DIDFIGHT;
        return (1);
    }

    /* If we are here but have no direction, there was a bug somewhere */
    if (mdir < 0)
    {   dwait (D_BATTLE, "Adjacent, but no direction known!");
        return (0);
    }

    /* If we could die this round, tell the user about it */
    if (danger >= Hp) display ("In trouble...");

    /* Well, nothing better than to hit the beast! Tell dwait about it */
    dwait (D_BATTLE, "Attacking %s(%d) direction %d (total danger %d)...",
           monster, mbad, mdir, danger);

    /* Record the monster type */
    lastmonster = monc-'A'+1;

    /* Move towards the monster (this causes us to hit him) */
    rmove (1, mdir, T_FIGHTING);
    lyinginwait = 0;
    foughtmonster = DIDFIGHT;
    return (1);
}
Exemple #8
0
void grgitn ( )
{

    /*	  CONTROLS MAIN ITERATIVE LOOP;  CALLS consbs TO COMPUTE    */
    /*	  INITIAL BASIS INVERSE ;  CALLS direc TO COMPUTE SEARCH    */
    /*	  DIRECTION;  CALLS ONE DIMENTIONAL SEARCH SUBROUTINE	    */
    /*	  search;  TEST FOR OPTIMALITY				    */

    /*	  Local Declarations	*/

    double  ts, tst, cons2, phhold, objtst, trubst;
    int   i, j, k, ii, jr, kk, iii, istop, msgcg, nfail, idegct;
    int   linect, iparm;

    /*	  INITIALIZE PERFORMANCE COUNTERS    */

    ncalls = 0;  /*  ncalls = NUMBER OF NEWTON CALLS  */
    nit = 0;     /*  nit    = CUMULATIVE NO. OF NEWTON ITERATIONS    */
    nftn = 1;    /*  nftn   = TOTAL NO. OF gcomp CALLS  */
    ngrad = 0;   /*  ngrad  = NO. OF GRADIENT CALLS  */
    nsear = 0;   /*  nsear  = NO. OF ONE DIMENTIONAL SEARCHES  */
    nsear0 = 0;  /*  nsear0 = VALUE OF NSEAR AT START FOR THIS NEWTON VALUE*/
    istop = 0;   /*  istop  = NO. OF CONSECUTIVE TIMES RELATIVE CHANGE  */
			  /*          IN FUNCTION IS LESS THAN epstop  */
    nbs = 0;     /*  nbs    = NO. OF TIMES BASIC VARIABLE VIOLATES BOUND  */
    nnfail = 0;  /*  nnfail = NO. TIMES NEWTON FAILD TO CONVERGE  */
    nstepc = 0;  /*  nstepc = NO. TIMES STEP SIZE CUT BACK WHEN NEWTON FAILS  */
/*08/1991 thru 11/1991*/
    scaled = 0;
    havescale = 0;
/*08/1991 thru 11/1991*/

    /*	  ADJUSTMENTS FOR USING TWO CONSTRAINT TOLERANCES    */

    epnewt = epinit;
    if ( eplast < epinit )  epstop = 10.0e0 * epstop;
    phhold = ph1eps;
    ipr = ipr3 + 1;
    linect = 60;
    iprhld = ipr;
    iprhd3 = ipr3;

    /*	  THIS IS RETURN POINT FOR epnewt LOOP	  */

w10 :
    drop = 0;		   /* COMMON LOGBLK, SRCHLG, SUPBLK */
    move = 1;
    restrt = 0;
    unbd = 0;
    jstfes = 0;
    degen = 0;
    uncon = 0;
    chngsb = 1;
    sbchng = 0;

    idegct = 0;
    nsuper = 0; 	   /* COMMOM NINTBK */
    trubst = 0.0e0;
    nsupp = 0;		   /* COMMON DIRGRG */
    ierr = 0;
    nfail = 0;
    msgcg = 1;
    stpbst = 1.0e0;
    lv = 0;
    istop = 0;
    objtst = plinfy;
    step = 0.0e0;
    cond = 1.0e0;
    ninf= 0;
    nb = 0;
    if ( iper != 0 )  {  ipr = 1;  ipr3 = 0; }
    for ( i = 1; i <= mp1; i++ )    x[n+i] = g[i];
    for ( i=1; i<=nbmax; i++ )
		for ( j=1; j<=nnbmax; j++ )  binv[i][j] = 0.0e0;

    /*	  THIS IS RETURN POINT FOR MAIN LOOP	*/

w40 : ;

    /*	  COMPUTE BASIS INVERSE, EXCEPT WHEN DEGENERATE    */

    consbs ( );

    if ( ninf == 0 || ph1eps == 0.0e0 )  goto w50;
    initph = 1;
    ph1obj();
    initph = 0;
w50 :
    if ( nsear != nsear0 )  goto w100;

    /*	INITIALIZATIONS THAT MUST BE DONE AFTER 1ST consbs CALLS  */
    /*	FOR EACH VALUE OF epnewt  */

    initph = 2;
    ph1obj();
    initph = 0;
    if ( nb == 0 )  goto w70;
    for ( i=1; i<=nb; i++ )  {
	k = ibv[i];
	xbest[i] = x[k];
    }
w70 :
    if ( nnbc == 0 )  goto w100;
    for ( i=1; i<=nnbc; i++ ) {
	k = inbc[i];
	xbest[nb+i] = g[k];
    }
    for ( i=1; i<=mp1; i++ )   gbest[i] = g[i];
w100 :
    /*	COMPUTE REDUCED GRADIENT  */

    redgra(gradf);

    if ( ipr < 4 ) goto w140;
    for ( i=1; i<=n; i++ )   xstat[i] = gradf[i];
    if ( maxim == 0 || ninf!= 0 )  goto w130;
    for ( i=1; i<=n; i++ )  xstat[i] = -xstat[i];
w130 :
    if ( ipr < 0 )  goto w140;
    fprintf ( ioout, "REDUCED GRADIENT IS\n");
    for ( i=1; i<=n; i++ )  fprintf ( ioout, "   %e\n", xstat[i] );
w140 :
    /*	===CHECK IF ANY OF THE STOP CRITERIA ARE SATISFIED===  */

    /*	UNCONDITIONAL STOP IF NUMBER OF LINEAR SEARCH > LIMSER	*/

    if ( nsear < limser )  goto w155;
    /*	DID REACH LIMIT SO QUIT  */

    if ( ipr < 0 )  goto w151;
    fprintf ( ioout, "NUMBER OF COMPLETED ONE-DIMENSIONAL SEARCHES = LIMSER");
    fprintf ( ioout, " =  %d.\nOPTIMIZATION TERMINATED.\n", nsear);
    linect++;
w151 :
    info = 3;
    ierr = 11;
    goto w520;

    /*	TEST IF KUHN-TUCKER CONDITIONS SATISFIED  */

w155 :
    for ( i=1; i<=n; i++ )  {
	ii = inbv[i];
	tst = gradf[i];
	if ( ii <= n )	goto w160;
	if ( istat[ii-n] == 1 )  goto w190;
w160 :
	if ( iub[i] == 0 )  goto w180;
	if ( iub[i] == 1 )  goto w170;
	if ( tst < -epstop )  goto w200;
	goto w190;
w170 :
	if ( tst > epstop ) goto w200;
	goto w190;
w180 :
	if ( fabs(tst) > epstop )  goto w200;
w190 :	;
    }

    /*	K-T CONDITIONS ARE SATISFIED.  GO CHECK IF epnewt AT FINAL VALUE  */

    if ( ipr < 0 )  goto w191;
    fprintf ( ioout, "TERMINATION CRITERION MET.  KUHN-TUCKER CONDITIONS");
    fprintf ( ioout, " SATISFIED TO\nWITHIN %e AT CURRENT POINT\n", epstop );
    linect++;
w191 :
    info = 0;
    goto w480;

    /*	CHECK IF RELATIVE CHANGE IN OBJECTIVE IS LESS THAN epstop  */
    /*	FOR nstop CONSECUTIVE ITERATIONS.    */

w200 :
    if ( degen == 1 )  goto w250;
    if ( fabs(g[nobj] - objtst) > fabs(objtst*epstop) )  goto w230;

    /*	FRACTIONAL CHANGE TOO SMALL.  COUNT HOW OFTEN CONSECUTIVELY.  */

    istop++;
    if ( istop < nstop )  goto w250;

    /*    FRACTIONAL CHANGE TOO SMALL nstop OR MORE TIMES.    */
    /*    SO GO CHECK IF epnewt AT FINAL VALUE  */

    if ( ipr < 0 )  goto w201;
    fprintf ( ioout, "TOTAL FRACTIONAL CHANGE IN OBJECTIVE LESS THAN %e\n", epstop);
    fprintf ( ioout, "  FOR %d CONSECUTIVE ITERATIONS\n", istop );
    linect = linect + 2;
w201 :
    ierr = 1;
    info = 1;
    goto w480;
w230 :
    istop = 0;
    chngsb = 0;
    objtst = g[nobj];

    /*	COMPUTE SEARCH DIRECTION FOR SUPERBASICS  */

w250 :
    direc();

    if ( dfail == 1 )  goto  w520;
    if ( ipr >= 4 )    {
	fprintf ( ioout, "DIRECTION VECTOR :\n" );
	for ( i=1; i<=nsuper; i++ )
	    fprintf ( ioout, "  D[%d] = %e\n", i, d[i] );
    }
    if ( nb == 0 )  goto w300;

    /*	COMPUTE TANGENT VECTOR V  */

    tang();

    if ( ipr >= 4 )  {
	fprintf ( ioout, "TANGENT VECTOR :\n" );
	for ( i=1; i<=nb; i++ )
	    fprintf ( ioout, "V[%d] = %e\n", i, v[i] );
    }

    /*	  FIND JP,  INDEX OF FIRST BASIC VARIABLE TO HIT A BOUND    */

    chuzr();

    if ( move == 1 )   goto w300;

    /*	  DEGENERATE AND NO MOVE IN BASICS IS POSSIBLE	  */

    jr = ibv[jp];
    if ( ipr >= 3 )
	fprintf (ioout, "BASIS DEGENERATE-- VARIABLE %d LEAVING BASIS\n", jr );
    lv = jp;
    degen = 1;
    idegct++;
    if ( idegct < 15 )   goto w281;
    if ( ipr < 0 )  goto w281;
    fprintf (ioout, "DEGENERATE FOR %d STEPS.  PROBABLY CYCLING.\n", idegct );

w281 :
    printdataline ( );

    /*      EXCHANGE BASIC WITH SOME SUPERBASIC AND UPDATE BINV   */

    chuzq();

    /*	  SET LOGICALS FOR USE BY DIREC    */

    restrt = 0;
    uncon = 0;
    sbchng = 1;
    mxstep = 1;

    /*	  NOW GO TO BEGIN NEW ITERATION FOR DEGENERATE CASE    */

    goto w100;

w300 :
    degen = 0;
    idegct = 0;

    printdataline ( );

    search();

    /* IF ABSOLUTE VALUE OF X'S IS VERY SMALL, CHANGE TO 0 TO AVOID UNDERFLOW */

    for ( i=1; i<=n; i++ )
	if ( fabs(x[i]) < eps )  x[i] = 0.0;

    nsear++;
    if ( nsear == ipn4 )  ipr = 4;
    if ( nsear == ipn5 )  ipr = 5;
    if ( nsear == ipn6 )  ipr = 6;
    ipr3 = ipr - 1;

    /*	IF SUPERBASIC HAS HIT BOUND, DELETE APPROPRIATE COLUMNS OF HESSIAN  */

    if ( mxstep == 0 )	goto w400;
    ii = nsuper;
    iii = nsuper;
    for ( kk=1; kk<=ii; kk++ )	{
	iparm = ii + 1 - kk;
	j = inbv[i];
	if ( fabs(x[j] - alb[j]) > epnewt && fabs(x[j] - ub[j]) >epnewt )  goto w390;
	iii--;
	if ( varmet == 1 )   delcol( &iparm );
	if ( iparm > iii )   goto w390;
	for ( k=iparm; k<=iii; k++ ) gradp[k] = gradp[k+1];
w390 :	;
    }
w400 :
    if ( succes == 1 )	 goto w440;

    /*	TROUBLE -- NO FUNCTION DECREASE  */
    /*	TRY DROPPING CONSTRAINTS ( AND GRADIENT STEP ) IF NOT DONE ALREADY  */

    if ( drop == 1 )   goto w435;
    drop = 1;
    chngsb = 1;
    goto w40;
w435 :
    /*	NO IMPROVEMENT IN LINESEARCH.  ALL REMEDIES FAILED.  */

    ierr = 2;
    if ( ipr < 0 )   goto w436;
    fprintf (ioout,"ALL REMEDIES HAVE FAILED TO FIND A BETTER POINT.");
    fprintf (ioout,"  PROGRAM TERMINATED.\n");
    linect = linect + 2;
w436 :
    info = 2;
    goto w480;
w440 :
    if ( unbd == 0 )   goto w450;

    /*	UNBOUNDED SOLUTION  */

    ierr = 20;
    if ( ipr < 0 )  goto w441;
    fprintf (ioout,"SOLUTION UNBOUNDED--FUNCTION IMPROVING AFTER DOUBLING STEP");
    fprintf (ioout," %d TIMES.\n", ndub);
    linect++;
w441 :
    info = 4;
    goto w520;
w450 :
    nfail = 0;
    restrt = 0;
    drop = 0;
    goto w40;

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

    /*	SEGMENT CHECKS AND IF NEEDED ADJUSTS EPNEWT TO FINAL VALUE  */

w480 :
    if ( epnewt == eplast )   goto w520;
    printdataline ( );
    epnewt = eplast;
    if ( ipr < 0 )  goto w481;
    fprintf (ioout,"CONSTRAINT TOLERANCE HAS BEEN TIGHTENED TO ITS FINAL ");
    fprintf (ioout,"VALUE OF %e.\n", epnewt );
    linect = linect + 2;
w481 :
    epstop = 0.1 * epstop;
    nsear0 = nsear;
    ph1eps = 0.2;
    for ( i=1; i<=n; i++ )   {
	if ( ifix[i] != 0 )  goto w485;
	ts = ub[i] + epnewt;
	if ( x[i] > ts )  x[i] = ts;
	ts = alb[i] - epnewt;
	if ( x[i] < ts )  x[i] = ts;
w485 :	;
    }
    sclgcomp(g, x);
    nftn++;
    if ( maxim == 1 )	g[nobj] = -g[nobj];
    goto w10;

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

    /*	NORMAL TERMINATION STEP  */

w520 :
    printdataline ( );
    if ( ninf == 0 )   goto w540;

    /*	SOLUTION INFEASABLE  */

    if ( ipr < 0 )  goto w521;
    fprintf (ioout,"FEASIBLE POINT NOT FOUND.\n");
    fprintf (ioout,"  FINAL VALUE OF TRUE OBJECTIVE = %e.\n", truobj );
    fprintf (ioout,"  THE FOLLOWING %d CONSTRAINTS WERE IN VIOLATION:\n", ninf);
    linect = linect + 2;
w521 :
    info = info + 10;
    ierr = 9;
    for ( i=1; i<=nnbc; i++ )  {
	j =inbc[i];
	if ( g[j] > alb[n+j] && g[j] < ub[n+j] )   goto w530;
	if ( ipr < 0 )	goto w523;
/*08/1991 thru 11/1991*/
        if (scaled == 1)
            fprintf (ioout, "  %d    %e\n", j, g[j]*scale[n+j] );
        else
            fprintf (ioout, "  %d    %e\n", j, g[j] );
/*08/1991 thru 11/1991*/
w523 :	;
w530 :	;
    }
    g[nobj] = truobj;
w540 :
    if ( epnewt != eplast )    epstop = 0.1 * epstop;
    epnewt = eplast;
    ph1eps = phhold;

/*08/1991 thru 11/1991*/
    if ( scaled == 1 )
       /*  must unscale the x[*] and g[*] before returning */
       { for (i = 1; i <= n; i++ )
	     { x[i] /= scale[i];
	       if (ub[i]  < plinfy) ub[i]  /= scale[i];
	       if (alb[i] >-plinfy) alb[i] /= scale[i];
	     }
w1000 :
	 for (j = 1; j <= mp1; j++ )
	     { i = n + j;
	       g[j] *= scale[i];
	       if (ub[i] < plinfy)  ub[i]  *= scale[i];
	       if (alb[i] >-plinfy) alb[i] *= scale[i];
	     }
       }
w1010 :
/*08/1991 thru 11/1991*/
    return;
}