Пример #1
0
/** Called when the plunger hits the track. In this case, notify the rubber
 *  band, and remove the plunger (but keep it alive).
 */
void Plunger::hitTrack()
{
    hit(NULL, NULL);
}   // hitTrack
Пример #2
0
GameBoard::GameBoard( QWidget *parent, const char *name )
        : QWidget( parent, name )
{
    QPushButton *quit = new QPushButton( "&Quit", this, "quit" );
    quit->setFont( QFont( "Times", 18, QFont::Bold ) );

    connect( quit, SIGNAL(clicked()), qApp, SLOT(quit()) );

    LCDRange *angle  = new LCDRange( "ANGLE", this, "angle" );
    angle->setRange( 5, 70 );

    LCDRange *force  = new LCDRange( "FORCE", this, "force" );
    force->setRange( 10, 50 );

    cannonField = new CannonField( this, "cannonField" );

    connect( angle, SIGNAL(valueChanged(int)),
	     cannonField, SLOT(setAngle(int)) );
    connect( cannonField, SIGNAL(angleChanged(int)),
	     angle, SLOT(setValue(int)) );

    connect( force, SIGNAL(valueChanged(int)),
	     cannonField, SLOT(setForce(int)) );
    connect( cannonField, SIGNAL(forceChanged(int)),
	     force, SLOT(setValue(int)) );

    connect( cannonField, SIGNAL(hit()),
	     this, SLOT(hit()) );
    connect( cannonField, SIGNAL(missed()),
	     this, SLOT(missed()) );

    QPushButton *shoot = new QPushButton( "&Shoot", this, "shoot" );
    shoot->setFont( QFont( "Times", 18, QFont::Bold ) );

    connect( shoot, SIGNAL(clicked()), SLOT(fire()) );
    connect( cannonField, SIGNAL(canShoot(bool)),
	     shoot, SLOT(setEnabled(bool)) );

    QPushButton *restart 
	= new QPushButton( "&New Game", this, "newgame" );
    restart->setFont( QFont( "Times", 18, QFont::Bold ) );

    connect( restart, SIGNAL(clicked()), this, SLOT(newGame()) );

    hits = new QLCDNumber( 2, this, "hits" );
    shotsLeft = new QLCDNumber( 2, this, "shotsleft" );
    QLabel *hitsL = new QLabel( "HITS", this, "hitsLabel" );
    QLabel *shotsLeftL 
	= new QLabel( "SHOTS LEFT", this, "shotsleftLabel" );

    QGridLayout *grid = new QGridLayout( this, 2, 2, 10 );
    grid->addWidget( quit, 0, 0 );
    grid->addWidget( cannonField, 1, 1 );
    grid->setColStretch( 1, 10 );

    QVBoxLayout *leftBox = new QVBoxLayout;
    grid->addLayout( leftBox, 1, 0 );
    leftBox->addWidget( angle );
    leftBox->addWidget( force );

    QHBoxLayout *topBox = new QHBoxLayout;
    grid->addLayout( topBox, 0, 1 );
    topBox->addWidget( shoot );
    topBox->addWidget( hits );
    topBox->addWidget( hitsL );
    topBox->addWidget( shotsLeft );
    topBox->addWidget( shotsLeftL );
    topBox->addStretch( 1 );
    topBox->addWidget( restart );

    angle->setValue( 60 );
    force->setValue( 25 );
    angle->setFocus();

    newGame();
}
Пример #3
0
void clusterErf() {

  TFile* file = new TFile("complete.root");

  TTree* tree = (TTree *)file->Get("Signal");

  int nEvents = tree->GetEntries();

  double addresses[121] = {};
  for (int k=0; k<121; k++){
    std::stringstream ss2;
    ss2 << k; 
    string str = "Crystal_"+ss2.str();
    const char* charstr = str.c_str(); 
    tree->SetBranchAddress(charstr, &addresses[k]);
  }

  TH1D* energyResoX = new TH1D("energyResoX", "Energy_Resolution_X", 100, -10, 10);

  TH1D* energyResoY = new TH1D("energyResoX", "Energy_Resolution_X", 100, -10, 10);

  TH1D* posResoX = new TH1D("posResoX", "Pos_Resolution_X", 50, -5, 5);

  TH1D* posResoY = new TH1D("posResoY", "Pos_Resolution_Y", 50, -5, 5);

  double energyThresHi = 50.;

  //Going through each scan of the calorimeter
  for (int k=0; k<nEvents; k++)
    {
      tree->GetEntry(k);

      pair<int, double> bump(0, 0.); 
      vector<pair<int, double> > geant;
      vector<pair<int, double> > hitMap;

      for(int i=0; i<121; i++)
	{
	  pair<int, double> hit(i, addresses[i]);
	  geant.push_back(hit);
	  if (addresses[i] > energyThresHi)
	    { hitMap.push_back(hit);}
	  if (hit.second>bump.second)
	    { bump = hit;}
	}
	
      erfFit(bump, geant, energyResoX, energyResoY, posResoX, posResoY);


    } //end of event
 
  TF1* g1d1 = new TF1("g1d1", "gaus", -10, 10);
  TF1* g1d2 = new TF1("g1d2", "gaus", -10, 10);
  TF1* g1d3 = new TF1("g1d3", "gaus", -5, 5);
  TF1* g1d4 = new TF1("g1d4", "gaus", -5, 5);

 TCanvas* canvas = new TCanvas("canvas", "canvas", 700,700);
canvas->Divide(2, 2);
 energyResoX->Fit(g1d1);
 canvas->cd(1); energyResoX->Draw();
 energyResoY->Fit(g1d2);
 canvas->cd(2); energyResoY->Draw();
 posResoX->Fit(g1d3);
 canvas->cd(3); posResoX->Draw();
 posResoY->Fit(g1d4);
 canvas->cd(4); posResoY->Draw();
  

}
Пример #4
0
void play()
{
	char str[256],str2[256],log[81],done,doub,dh,split_card,suggestion
		,*YouWereDealt="\1n\1k\0015 You \1n\1m were dealt: %s\r\n"
		,*UserWasDealt="\1n\1m\1h%s\1n\1m was dealt: %s\r\n"
		,*YourHand="\1n\1k\0015 You \1n\1m                     (%2d) %s"
		,*UserHand="\1n\1m\1h%-25s \1n\1m(%2d) %s"
		,*DealerHand="\1n\1hDealer                    \1n\1m(%2d) "
		,*Bust="\1n\1r\1hBust\1n\r\n"
		,*Natural="\1g\1h\1iNatural "
		,*Three7s="\1r\1h\1iThree 7's "
		,*Blackjack="\1n\0011\1k Blackjack! \1n\r\n"
		,*TwentyOne="\1n\0012\1k Twenty-one \1n\r\n";
	int h,i,j,file;
	uint max;
	long val;
	time_t start,now;
	struct tm* tm;

sprintf(str,"MESSAGE.%d",node_num);         /* remove message if waiting */
if(fexist(str))
    remove(str);

getgamedat(0);
if(node[node_num-1]) {
	getgamedat(1);
	node[node_num-1]=0;
	putgamedat();
	getgamedat(0); }

if(total_players && misc&INPLAY) {
	bputs("\r\n\1hWaiting for end of hand (^A to abort)...\1n");
	start=now=time(NULL);
	getgamedat(0);
	while(total_players && misc&INPLAY) {
		if((i=inkey(0))!=0) {	 /* if key was hit */
			if(i==1) {		 /* if ctrl-a */
				bputs("\r\n");
				return; } }  /* return */
		mswait(100);
		getgamedat(0);
		now=time(NULL);
		if(now-start>300) { /* only wait up to 5 minutes */
			bputs("\r\ntimeout\r\n");
			return; } }
	bputs("\r\n"); }

getgamedat(1);
node[node_num-1]=user_number;
putgamedat();

if(!total_players)
    shuffle();
else
	listplayers();

sprintf(str,"\1n\1m\1h%s \1n\1m%s\r\n",user_name,joined());
putallnodemsg(str);

while(1) {
	aborted=0;
	#if DEBUG
	debugline("top of loop");
	#endif
	if(autoplay)
		lncntr=0;
	bprintf(ShoeStatus,cur_card,total_decks*52);
	if(cur_card>(total_decks*52)-(total_players*10)-10 && lastplayer())
		shuffle();
	getgamedat(1);
	misc&=~INPLAY;
	status[node_num-1]=BET;
	node[node_num-1]=user_number;
	putgamedat();

	bprintf("\r\n\1n\1cYou have \1h%s\1n\1ck credits\r\n"
		,ultoac(credits/1024L,str));
	if(credits<min_bet/1024) {
		bprintf("\1n\1cMinimum bet: \1h%uk\r\n",min_bet);
		bputs("\1n\1r\1hCome back when you have more credits.\r\n");
        break; }
	if(credits/1024L>(ulong)max_bet)
		max=max_bet;
	else
		max=credits/1024L;
	sprintf(str,"\r\nBet amount (in kilobytes) or ~Quit [%u]: "
		,ibet<credits/1024L ? ibet : credits/1024L);
	chat();
	mnemonics(str);
	if(autoplay && keyhit())
		autoplay=0;
	if(autoplay)
		i=ibet;
	else
		i=getnum(max);
	if(i==-1)	/* if user hit ^C or 'Q' */
		break;
	bputs("\r\n");
	if(i)		/* if user entered a value */
		bet[0]=i;
	else		/* if user hit enter */
		bet[0]=ibet<credits/1024L ? ibet : credits/1024L;
	if(bet[0]<min_bet) {
		bprintf("\1n\1cMinimum bet: \1h%uk\r\n",min_bet);
		bputs("\1n\1r\1hCome back when you're ready to bet more.\r\n");
		break; }
	ibet=bet[0];
	getgamedat(0);	/* to get all new arrivals */
	sprintf(str,"\1m\1h%s\1n\1m bet \1n\1h%u\1n\1mk\r\n",user_name,bet[0]);
	putallnodemsg(str);

	pc[0]=2;						/* init player's 1st hand to 2 cards */
	for(i=1;i<MAX_HANDS;i++)		/* init player's other hands to 0 cards */
		pc[i]=0;
	hands=1;						/* init total player's hands to 1 */

	getgamedat(1);					/* first come first serve to be the */
	for(i=0;i<total_nodes;i++)		/* dealer in control of sync */
		if(node[i] && status[i]==SYNC_D)
			break;
	if(i==total_nodes) {
		#if DEBUG
		debugline("syncdealer");
		#endif
		syncdealer();  }			/* all players meet here */
	else {							/* first player is current after here */
		#if DEBUG
		debugline("syncplayer");
		#endif
		syncplayer(); } 			/* game is closed (INPLAY) at this point */

	#if DEBUG
	debugline("waitturn 1");
	#endif
    waitturn();
	getnodemsg();
										/* Initial deal card #1 */
	getcarddat();
	player[0][0]=card[cur_card++];
	putcarddat();
	sprintf(str,YouWereDealt,cardstr(card[cur_card-1]));
	if(!symbols)
		strip_symbols(str);
    bputs(str);
	sprintf(str,UserWasDealt,user_name,cardstr(card[cur_card-1]));
    putallnodemsg(str);
	
	if(lastplayer()) {
		getcarddat();
		dealer[0]=card[cur_card++];
		dc=1;
		putcarddat(); }
	nextplayer();
	#if DEBUG
	debugline("waitturn 2");
	#endif
	waitturn();
	getnodemsg();

	getcarddat();					   /* Initial deal card #2 */
	player[0][1]=card[cur_card++];
	putcarddat();
	sprintf(str,YouWereDealt,cardstr(card[cur_card-1]));
	if(!symbols)
		strip_symbols(str);
	bputs(str);
	sprintf(str,UserWasDealt,user_name,cardstr(card[cur_card-1]));
    putallnodemsg(str);
	
	if(lastplayer()) {
		getcarddat();
		dealer[1]=card[cur_card++];
		dc=2;
		putcarddat(); }
	nextplayer();
	#if DEBUG
	debugline("waitturn 3");
	#endif
	waitturn();
	getnodemsg();
	getcarddat();

	for(i=0;i<hands;i++) {
		if(autoplay)
			lncntr=0;
		done=doub=0;
		while(!done && pc[i]<MAX_CARDS && cur_card<total_decks*52) {
			h=hand(player[i],pc[i]);
			str[0]=0;
			for(j=0;j<pc[i];j++) {
				strcat(str,cardstr(player[i][j]));
				strcat(str," "); }
			j=bstrlen(str);
			while(j++<19)
				strcat(str," ");
			if(h>21) {
				strcat(str,Bust);
				sprintf(str2,YourHand,h,str);
				if(!symbols)
					strip_symbols(str2);
				bputs(str2);
				sprintf(str2,UserHand,user_name,h,str);
				putallnodemsg(str2);
				break; }
			if(h==21) {
				if(pc[i]==2) {	/* blackjack */
					if(player[i][0].suit==player[i][1].suit)
						strcat(str,Natural);
					strcat(str,Blackjack); }
				else {
					if(player[i][0].value==7
						&& player[i][1].value==7
						&& player[i][2].value==7)
						strcat(str,Three7s);
					strcat(str,TwentyOne); }
				sprintf(str2,YourHand,h,str);
				if(!symbols)
					strip_symbols(str2);
				bputs(str2);
				sprintf(str2,UserHand,user_name,h,str);
                putallnodemsg(str2);
				// fdelay(500);
				break; }
			strcat(str,"\r\n");
			sprintf(str2,YourHand,h,str);
			if(!symbols)
				strip_symbols(str2);
			bputs(str2);
			sprintf(str2,UserHand,user_name,h,str);
			putallnodemsg(str2);
			if(doub)
				break;
			sprintf(str,"\1n\1hDealer\1n\1m card up: %s\r\n"
				,cardstr(dealer[1]));
			if(!symbols)
				strip_symbols(str);
			bputs(str);

			if(tutor) {
				if(pc[i]==2)
					split_card=pair(player[i],pc[i]);
				else
					split_card=0;
                if(split_card==A
					|| (split_card==9 && (dealer[1].value<7
						|| (dealer[1].value>7 && dealer[1].value<10)))
                    || split_card==8
					|| (split_card==7 && dealer[1].value<9)
					|| (split_card==6 && dealer[1].value<7)
					|| (split_card==4 && dealer[1].value==5)
					|| (split_card && split_card<4 && dealer[1].value<8))
					suggestion='P';
                else if(soft(player[i],pc[i])) {
                    if(h>18)
						suggestion='S';
					else if(pc[i]==2
						&& ((h==18
							&& dealer[1].value>3 && dealer[1].value<7)
                        || (h==17
							&& dealer[1].value>2 && dealer[1].value<7)
                        || (h>13
							&& dealer[1].value>3 && dealer[1].value<7)
                        || (h==12
							&& dealer[1].value>4 && dealer[1].value<7)))
						suggestion='D';
                    else
						suggestion='H'; }
                else { /* hard */
					if(h>16 || (h>13 && dealer[1].value<7)
						|| (h==12 && dealer[1].value>3 && dealer[1].value<7))
						suggestion='S';
					else if(pc[i]==2
						&& (h==11 || (h==10 && dealer[1].value<10)
						|| (h==9 && dealer[1].value<7)))
						suggestion='D';
                    else
						suggestion='H'; } }

			if(tutor==1)
				suggest(suggestion);
			strcpy(str,"\r\n~Hit");
			strcpy(tmp,"H\r");
			if(bet[i]+ibet<=credits/1024L && pc[i]==2) {
				strcat(str,", ~Double");
				strcat(tmp,"D"); }
			if(bet[i]+ibet<=credits/1024L && pc[i]==2 && hands<MAX_HANDS
				&& player[i][0].value==player[i][1].value) {
				strcat(str,", ~Split");
				strcat(tmp,"S"); }
			strcat(str,", or [Stand]: ");
			chat();
			mnemonics(str);
			if(autoplay && keyhit())
				autoplay=0;


			if(autoplay) {
				lncntr=0;
				bputs("\r\n");
				strcpy(str,stand());
				bputs(str);
				putallnodemsg(str);
				done=1; }
			else
			switch(getkeys(tmp,0)) {
				case 'H':     /* hit */
					if(tutor==2 && suggestion!='H')
						wrong(suggestion);
					strcpy(str,hit());
					bputs(str);
					putallnodemsg(str);
					getcarddat();
					player[i][pc[i]++]=card[cur_card++];
					putcarddat();
					break;
				case 'D':   /* double down */
					if(tutor==2 && suggestion!='D')
                        wrong(suggestion);
					strcpy(str,doubit());
					bputs(str);
					putallnodemsg(str);
					getcarddat();
					player[i][pc[i]++]=card[cur_card++];
					putcarddat();
					doub=1;
					bet[i]+=ibet;
					break;
				case 'S':   /* split */
					if(tutor==2 && suggestion!='P')
                        wrong(suggestion);
					strcpy(str,split());
					bputs(str);
					putallnodemsg(str);
					player[hands][0]=player[i][1];
					getcarddat();
					player[i][1]=card[cur_card++];
					player[hands][1]=card[cur_card++];
					putcarddat();
					pc[hands]=2;
					bet[hands]=ibet;
					hands++;
					break;
				case CR:
					if(tutor==2 && suggestion!='S')
                        wrong(suggestion);
					strcpy(str,stand());
					bputs(str);
					putallnodemsg(str);
					done=1;
					break; } } }

	if(lastplayer()) {	/* last player plays the dealer's hand */
		getcarddat();
		while(hand(dealer,dc)<17 && dc<MAX_CARDS && cur_card<total_decks*52)
			dealer[dc++]=card[cur_card++];
		putcarddat(); }

	nextplayer();
	#if DEBUG
	debugline("waitturn 4");
	#endif
	waitturn();
	getnodemsg();

	if(firstplayer()==node_num) {
		strcpy(str,"\1n\0014\1h Final \1n\r\n");
		bputs(str);
		putallnodemsg(str); }
	getcarddat();
	dh=hand(dealer,dc); 					/* display dealer's hand */
	sprintf(str,DealerHand,dh);
	for(i=0;i<dc;i++) {
		strcat(str,cardstr(dealer[i]));
		strcat(str," "); }
	i=bstrlen(str);
	while(i++<50)				/* was 50 */
		strcat(str," ");
	if(dh>21) {
		strcat(str,Bust);
		if(!symbols)
			strip_symbols(str);
		bputs(str); }
	else if(dh==21) {
		if(dc==2) { 	/* blackjack */
			if(dealer[0].suit==dealer[1].suit)
				strcat(str,Natural);
			strcat(str,Blackjack); }
		else {			/* twenty-one */
			if(dc==3 && dealer[0].value==7 && dealer[1].value==7
				&& dealer[2].value==7)
				strcat(str,Three7s);
			strcat(str,TwentyOne); }
		if(!symbols)
            strip_symbols(str);
		bputs(str); }
	else {
		if(!symbols)
            strip_symbols(str);
		bprintf("%s\r\n",str); }

	for(i=0;i<hands;i++) {						/* display player's hand(s) */
		h=hand(player[i],pc[i]);
		str[0]=0;
		for(j=0;j<pc[i];j++) {
			strcat(str,cardstr(player[i][j]));
			strcat(str," "); }
		j=bstrlen(str);
		while(j++<19)
			strcat(str," ");
		if(logit) {
			now=time(NULL);
			tm=localtime(&now);
			sprintf(log,"%02d%02d%02d.log"                  /* log winnings */
				,tm->tm_mon+1,tm->tm_mday,tm->tm_year%100);
			if((file=nopen(log,O_RDONLY))!=-1) {
				read(file,tmp,filelength(file));
				tmp[filelength(file)]=0;
				val=atol(tmp);
				close(file); }
			else
				val=0L;
			if((file=nopen(log,O_WRONLY|O_CREAT|O_TRUNC))==-1) {
				bprintf("error opening %s\r\n",log);
				return; } }
		if(h<22 && (h>dh || dh>21	/* player won */
			|| (h==21 && pc[i]==2 && dh==21 && dh>2))) {	/* blackjack */
			j=bet[i];								  /* and dealer got 21 */
			if(h==21 && 	/* natural blackjack or three 7's */
				((player[i][0].value==7 && player[i][1].value==7
				&& player[i][2].value==7)
				|| (pc[i]==2 && player[i][0].suit==player[i][1].suit)))
				j*=2;
			else if(h==21 && pc[i]==2)	/* regular blackjack */
				j*=1.5; /* blackjack pays 1 1/2 to 1 */
			sprintf(tmp,"\1n\1h\1m\1iWon!\1n\1h %u\1n\1mk",j);
			strcat(str,tmp);
			credits+=j*1024L;
			val-=j*1024L;
			moduserdat(); }
		else if(h<22 && h==dh)
			strcat(str,"\1n\1hPush");
		else {
			strcat(str,"\1nLost");
			credits-=bet[i]*1024L;
			val+=bet[i]*1024L;
			moduserdat(); }
		if(logit) {
			sprintf(tmp,"%ld",val);
			write(file,tmp,strlen(tmp));
			close(file); }					/* close winning log */
		strcat(str,"\1n\r\n");
		sprintf(str2,YourHand,h,str);
		if(!symbols)
			strip_symbols(str2);
		bputs(str2);
		sprintf(str2,UserHand,user_name,h,str);
		putallnodemsg(str2); }

	nextplayer();
	if(!lastplayer()) {
		#if DEBUG
		debugline("lastplayer waitturn");
		#endif
		waitturn();
		nextplayer(); }
	#if DEBUG
	debugline("end of loop");
	#endif
	getnodemsg(); }

getgamedat(1);
node[node_num-1]=0;
putgamedat();
sprintf(str,"\1n\1m\1h%s \1n\1m%s\r\n",user_name,left());
putallnodemsg(str);
}
Пример #5
0
/** Updates the bowling ball ineach frame. If this function returns true, the
 *  object will be removed by the projectile manager.
 *  \param dt Time step size.
 *  \returns True of this object should be removed.
 */
bool Bowling::updateAndDelete(float dt)
{
    bool can_be_deleted = Flyable::updateAndDelete(dt);
    if(can_be_deleted)
        return true;

    const AbstractKart *kart=0;
    Vec3        direction;
    float       minDistance;
    getClosestKart(&kart, &minDistance, &direction);
    if(kart && minDistance<m_st_max_distance_squared)   // move bowling towards kart
    {
        // limit angle, so that the bowling ball does not turn
        // around to hit a kart behind
        if(fabs(m_body->getLinearVelocity().angle(direction)) < 1.3)
        {
            direction*=1/direction.length()*m_st_force_to_target;
            m_body->applyCentralForce(direction);
        }
    }
    
   
    // Bowling balls lose energy (e.g. when hitting the track), so increase
    // the speed if the ball is too slow, but only if it's not too high (if
    // the ball is too high, it is 'pushed down', which can reduce the
    // speed, which causes the speed to increase, which in turn causes
    // the ball to fly higher and higher.
    //btTransform trans = getTrans();
    float hat = (getXYZ() - getHitPoint()).length();
    if(hat-0.5f*m_extend.getY()<0.01f)
    {
        const Material *material = getMaterial();
        if(!material || material->isDriveReset())
        {
            hit(NULL);
            return true;
        }
    }
    btVector3 v       = m_body->getLinearVelocity();
    float vlen        = v.length2();
    if (hat<= m_max_height)
    {
        if(vlen<0.8*m_speed*m_speed)
        {   // bowling lost energy (less than 80%), i.e. it's too slow - speed it up:
            if(vlen==0.0f) {
                v = btVector3(.5f, .0, 0.5f);  // avoid 0 div.
            }
 //           m_body->setLinearVelocity(v*(m_speed/sqrt(vlen)));
        }   // vlen < 0.8*m_speed*m_speed
    }   // hat< m_max_height

    if(vlen<0.1)
    {
        hit(NULL);
        return true;
    }

    if (m_roll_sfx->getStatus()==SFXBase::SFX_PLAYING)
        m_roll_sfx->setPosition(getXYZ());

    return false;
}   // updateAndDelete
Пример #6
0
vec3 DirectLightIntegrator::income(const Ray &r,
	const shared_ptr<Scene> &scene,
	int level) {

	vec3 L(0.0f);

	Intersection hit(NULL, NULL, CONST_FAR);

	// Is there intersection?
	if (!scene->intersect(r, hit)) {
		return L;
	}

    // Is this intersection on the light?
    if (hit.type == INTERSECTION_LIGHT) {
        // Simply return the color from the light.
        const Light *light = static_cast<const Light *>(hit.intersectable);
        return light->Le(hit.point) * clamp(dot(hit.normal, -r.d), 0.0f, 1.0f);
    }

	// Sample for one light.
    if (!hit.m->bsdf->isDelta()) {

        // This is not a delta brdf. Randomly pick one light.
        int lightId = floor(Sampler::sample1D(0.0f, (float)scene->lights.size() - 0.1f));
        const shared_ptr<Light> &light = scene->lights[lightId];

        // Get the shadow ray and the distance to the light.
        vec3 Lo(0.0f);
        for (int i = 0; i < nLightSamples; ++i) {
            auto sample = light->genShadowRay(hit);

            Ray shadowRay = sample.first;
            float lightPDF = sample.second;

            if (lightPDF < CONST_EPSILON) {
                continue;
            }

            // Use the shadow ray to find intersect.
            if (scene->occlude(shadowRay)) {
                continue;
            }

            // Get the light color.
            vec3 pointOnLight = shadowRay.o + shadowRay.tmax * shadowRay.d;
            vec3 Le = light->Le(pointOnLight);
            vec3 f = hit.m->bsdf->bsdf(hit, r.d, shadowRay.d);
            float w = powerHeuristec(lightPDF, nLightSamples, hit.m->bsdf->pdf(hit, r.d, shadowRay.d), nBSDFSamples);

            // Here the geometry term is inside the pdf.
            // Use power heuristic.
            Lo += f * Le * w / lightPDF;
        }
        Lo /= nLightSamples;
        L += Lo;

        // Sample for BSDF.
        if (level < maxDepth - 1) {

            vec3 LBSDF(0.0f);
            for (int i = 0; i < nBSDFSamples; ++i) {
                while (true) {
                    auto sample = hit.m->bsdf->sample(hit, r.d);
                    if (sample.second > 0.1f) {
                        auto Li = income(sample.first, scene, level + 1);
                        vec3 f = hit.m->bsdf->bsdf(hit, r.d, sample.first.d);

                        float w = powerHeuristec(sample.second, nBSDFSamples, light->pdfRay(hit, sample.first.d), nLightSamples);
                        //float w = 1.0f;
                        LBSDF += w * f * Li / sample.second;
                        break;
                    }
                }
            }
            LBSDF /= nBSDFSamples;
            L += clamp(LBSDF, 0.0f, 1.0f);

        }
    }
    else {
        // This is a delta brdf. Just sample the delta direction.
        if (level < maxDepth - 1) {
            auto sample = hit.m->bsdf->sample(hit, r.d);
            auto Li = income(sample.first, scene, level + 1);
            vec3 f = hit.m->bsdf->bsdf(hit, r.d, sample.first.d);
            L += f * Li;
        }
    }

	return L;
}
Пример #7
0
HitResponse
Jumpy::collision_badguy(BadGuy& , const CollisionHit& chit)
{
  return hit(chit);
}
Пример #8
0
QString ASVat::getCalculation(const QDate& fromDate, const QDate& toDate)
{
    QString report;

    QHash<const ASVatCategory *, QPair<double, double> > category;

    int indent = 15;

    ASTransactionList::const_iterator it = m_transactions->constBegin();
    for (; it != m_transactions->constEnd(); ++it)
    {
        const ASVatCategory * cat = dynamic_cast<const ASVatCategory*>(*it);
        if (cat)
        {
            category.insert(cat, QPair<double, double>(0.0, 0.0));
            if (cat->getDescription().length() > indent)
            {
                indent = cat->getDescription().length();
            }
        }
    }
    indent += 3;

    it = m_transactions->constBegin();
    for (; it != m_transactions->constEnd(); ++it)
    {
        const ASAccountEntry * ae = dynamic_cast<const ASAccountEntry*>(*it);
        if (!ae)
            continue;

        if (ae->getOverwrittenBy() || ae->getHidden())
            continue;

        if (ae->getDate() >= fromDate && ae->getDate() <= toDate)
        {
            double charge = ae->getAmount() * ae->getChargePercentage() / 100.0;
            double chargeVat = ae->getVatAmount() * ae->getChargePercentage() / 100.0;
            ASVatCategoryList vl = ae->getVatCategories();
            ASVatCategoryList::const_iterator it2 = vl.constBegin();
            for (; it2 != vl.constEnd(); ++it2)
            {
                category[*it2].first += qAbs((double)(qRound(charge * 100)) / 100.0);
                category[*it2].second += qAbs((double)(qRound(chargeVat * 100)) / 100.0);
                const ASVatCategory * vp = (*it2)->getParent();
                while (vp)
                {
                    category[vp].first += qAbs((double)(qRound(charge * 100)) / 100.0);
                    category[vp].second += qAbs((double)(qRound(chargeVat * 100)) / 100.0);
                    vp = vp->getParent();
                }
            }
        }
    }

    QString line = QString("%1 %2 %3\n")
        .arg("Description", -indent)
        .arg("Base amount", 15)
        .arg("VAT amount", 15);
    report.append(line);
    report.append("\n");

    QHashIterator<const ASVatCategory *, QPair<double, double> > hit(category);
    while (hit.hasNext()) {
        hit.next();
        line = QString("%1 %2 %3\n")
            .arg(hit.key()->getDescription(), -indent)
            .arg(hit.value().first, 15, 'f', 2)
            .arg(hit.value().second, 15, 'f', 2);
        report.append(line);
    }

    return report;
}
Пример #9
0
Файл: Mesh.cpp Проект: dicta/ray
bool Mesh::shadowHit(const Ray& ray, double& tmin) const {
   ShadeRecord sr;
   return hit(ray, tmin, sr);
}
Пример #10
0
void ShadingPoint::fetch_source_geometry() const
{
    assert(hit());
    assert(!(m_members & HasSourceGeometry));

    // Retrieve the assembly.
    m_assembly = &m_assembly_instance->get_assembly();

    // Retrieve the object instance.
    m_object_instance = m_assembly->object_instances().get_by_index(m_object_instance_index);
    assert(m_object_instance);

    // Retrieve the object.
    m_object = &m_object_instance->get_object();

    // Retrieve the region kit of the object.
    assert(m_region_kit_cache);
    const RegionKit& region_kit =
        *m_region_kit_cache->access(
            m_object->get_uid(), m_object->get_region_kit());

    // Retrieve the region.
    const IRegion* region = region_kit[m_region_index];

    // Retrieve the tessellation of the region.
    assert(m_tess_cache);
    const StaticTriangleTess& tess =
        *m_tess_cache->access(
            region->get_uid(), region->get_static_triangle_tess());
    const size_t motion_segment_count = tess.get_motion_segment_count();

    // Retrieve the triangle.
    const Triangle& triangle = tess.m_primitives[m_triangle_index];

    // Copy the index of the triangle attribute.
    m_triangle_pa = triangle.m_pa;

    // Copy the texture coordinates from UV set #0.
    if (triangle.has_vertex_attributes() && tess.get_uv_vertex_count() > 0)
    {
        m_v0_uv = tess.get_uv_vertex(triangle.m_a0);
        m_v1_uv = tess.get_uv_vertex(triangle.m_a1);
        m_v2_uv = tess.get_uv_vertex(triangle.m_a2);
    }
    else
    {
        // UV set #0 doesn't exist, or this triangle doesn't have vertex attributes.
        m_v0_uv =
        m_v1_uv =
        m_v2_uv = GVector2(0.0);
    }

    // Copy the object instance space triangle vertices.
    assert(triangle.m_v0 != Triangle::None);
    assert(triangle.m_v1 != Triangle::None);
    assert(triangle.m_v2 != Triangle::None);
    if (motion_segment_count > 0)
    {
        // Fetch triangle vertices from the previous pose.
        const size_t prev_index = truncate<size_t>(m_ray.m_time * motion_segment_count);
        GVector3 prev_v0, prev_v1, prev_v2;
        if (prev_index == 0)
        {
            prev_v0 = tess.m_vertices[triangle.m_v0];
            prev_v1 = tess.m_vertices[triangle.m_v1];
            prev_v2 = tess.m_vertices[triangle.m_v2];
        }
        else
        {
            prev_v0 = tess.get_vertex_pose(triangle.m_v0, prev_index - 1);
            prev_v1 = tess.get_vertex_pose(triangle.m_v1, prev_index - 1);
            prev_v2 = tess.get_vertex_pose(triangle.m_v2, prev_index - 1);
        }

        // Fetch triangle vertices from the next pose.
        const GVector3 next_v0 = tess.get_vertex_pose(triangle.m_v0, prev_index);
        const GVector3 next_v1 = tess.get_vertex_pose(triangle.m_v1, prev_index);
        const GVector3 next_v2 = tess.get_vertex_pose(triangle.m_v2, prev_index);

        // Interpolate triangle vertices.
        const GScalar k = static_cast<GScalar>(m_ray.m_time * motion_segment_count - prev_index);
        m_v0 = (GScalar(1.0) - k) * prev_v0 + k * next_v0;
        m_v1 = (GScalar(1.0) - k) * prev_v1 + k * next_v1;
        m_v2 = (GScalar(1.0) - k) * prev_v2 + k * next_v2;
    }
    else
    {
        m_v0 = tess.m_vertices[triangle.m_v0];
        m_v1 = tess.m_vertices[triangle.m_v1];
        m_v2 = tess.m_vertices[triangle.m_v2];
    }

    // Copy the object instance space triangle vertex normals.
    assert(triangle.m_n0 != Triangle::None);
    assert(triangle.m_n1 != Triangle::None);
    assert(triangle.m_n2 != Triangle::None);
    m_n0 = tess.m_vertex_normals[triangle.m_n0];
    m_n1 = tess.m_vertex_normals[triangle.m_n1];
    m_n2 = tess.m_vertex_normals[triangle.m_n2];
    assert(is_normalized(m_n0));
    assert(is_normalized(m_n1));
    assert(is_normalized(m_n2));
}
Пример #11
0
/** Updates this flyable. It calls Moveable::update. If this function returns
 *  true, the flyable will be deleted by the projectile manager.
 *  \param dt Time step size.
 *  \returns True if this object can be deleted.
 */
bool Flyable::updateAndDelete(float dt)
{
    m_time_since_thrown += dt;
    if(m_max_lifespan > -1 && m_time_since_thrown > m_max_lifespan)
        hit(NULL);

    if(m_has_hit_something) return true;

    //Vec3 xyz=getBody()->getWorldTransform().getOrigin();
    const Vec3 &xyz=getXYZ();
    // Check if the flyable is outside of the track. If so, explode it.
    const Vec3 *min, *max;
    World::getWorld()->getTrack()->getAABB(&min, &max);

    // I have seen that the bullet AABB can be slightly different from the
    // one computed here - I assume due to minor floating point errors
    // (e.g. 308.25842 instead of 308.25845). To avoid a crash with a bullet
    // assertion (see bug 3058932) I add an epsilon here - but admittedly
    // that does not really explain the bullet crash, since bullet tests
    // against its own AABB, and should therefore not cause the assertion.
    // But since we couldn't reproduce the problem, and the epsilon used
    // here does not hurt, I'll leave it in.
    float eps = 0.1f;
    assert(!isnan(xyz.getX()));
    assert(!isnan(xyz.getY()));
    assert(!isnan(xyz.getZ()));
    if(xyz[0]<(*min)[0]+eps || xyz[2]<(*min)[2]+eps || xyz[1]<(*min)[1]+eps ||
       xyz[0]>(*max)[0]-eps || xyz[2]>(*max)[2]-eps || xyz[1]>(*max)[1]-eps   )
    {
        hit(NULL);    // flyable out of track boundary
        return true;
    }

    // Add the position offset so that the flyable can adjust its position
    // (usually to do the raycast from a slightly higher position to avoid
    // problems finding the terrain in steep uphill sections).
    if(m_do_terrain_info)
        TerrainInfo::update(xyz+m_position_offset);

    if(m_adjust_up_velocity)
    {
        float hat = xyz.getY()-getHoT();

        // Use the Height Above Terrain to set the Z velocity.
        // HAT is clamped by min/max height. This might be somewhat
        // unphysical, but feels right in the game.

        float delta = m_average_height - std::max(std::min(hat, m_max_height),
                                                  m_min_height);
        Vec3 v = getVelocity();
        assert(!isnan(v.getX()));
        assert(!isnan(v.getX()));
        assert(!isnan(v.getX()));
        float heading = atan2f(v.getX(), v.getZ());
        assert(!isnan(heading));
        float pitch   = getTerrainPitch(heading);
        float vel_up = m_force_updown*(delta);
        if (hat < m_max_height) // take into account pitch of surface
            vel_up += v.length_2d()*tanf(pitch);
        assert(!isnan(vel_up));
        v.setY(vel_up);
        setVelocity(v);
    }   // if m_adjust_up_velocity

    Moveable::update(dt);

    return false;
}   // updateAndDelete
Пример #12
0
OSL::ShaderGlobals& ShadingPoint::get_osl_shader_globals() const
{
    assert(hit());

    if (!(m_members & HasOSLShaderGlobals))
    {
        const ShadingRay& ray(get_ray());

        m_shader_globals.P = Vector3f(get_point());
        m_shader_globals.dPdx = OSL::Vec3(0, 0, 0);
        m_shader_globals.dPdy = OSL::Vec3(0, 0, 0);
        m_shader_globals.dPdz = OSL::Vec3(0, 0, 0);

        m_shader_globals.I = Vector3f(normalize(ray.m_dir));
        m_shader_globals.dIdx = OSL::Vec3(0, 0, 0);
        m_shader_globals.dIdy = OSL::Vec3(0, 0, 0);

        m_shader_globals.N = Vector3f(get_shading_normal());
        m_shader_globals.Ng = Vector3f(get_geometric_normal());

        m_shader_globals.u = get_uv(0).x;
        m_shader_globals.dudx = 0;
        m_shader_globals.dudy = 0;

        m_shader_globals.v = get_uv(0).y;
        m_shader_globals.dvdx = 0;
        m_shader_globals.dvdy = 0;

        m_shader_globals.dPdu = Vector3f(get_dpdu(0));
        m_shader_globals.dPdv = Vector3f(get_dpdv(0));

        m_shader_globals.time = ray.m_time;
        m_shader_globals.dtime = 0;
        m_shader_globals.dPdtime = OSL::Vec3(0, 0, 0);
        
        m_shader_globals.Ps = OSL::Vec3(0, 0, 0);
        m_shader_globals.dPsdx = OSL::Vec3(0, 0, 0);
        m_shader_globals.dPsdy = OSL::Vec3(0, 0, 0);
        
        m_shader_globals.renderstate = 0;
        m_shader_globals.tracedata = 0;
        m_shader_globals.objdata = 0;

        m_obj_transform_info.m_assembly_instance_transform = 
            &get_assembly_instance().cumulated_transform_sequence();
        m_obj_transform_info.m_object_instance_transform = 
            &get_object_instance().get_transform();

        m_shader_globals.object2common = reinterpret_cast<OSL::TransformationPtr>(&m_obj_transform_info);

        m_shader_globals.shader2common = 0;
        m_shader_globals.surfacearea = 0;

        m_shader_globals.raytype = static_cast<int>(ray.m_type);

        m_shader_globals.flipHandedness = 0;
        m_shader_globals.backfacing = get_side() == ObjectInstance::FrontSide ? 0 : 1;

        m_shader_globals.context = 0;
        m_shader_globals.Ci = 0;
        
        m_members |= HasOSLShaderGlobals;
    }
    else
    {
        // Update always the raytype, as it might have changed from the previous run.
        m_shader_globals.raytype = static_cast<int>(get_ray().m_type);
    }

    return m_shader_globals;
}
Пример #13
0
bool Bbox::hit(const Ray& ray)
{
	float tMin, tMax;
	return hit(ray, tMin, tMax);
}
Пример #14
0
void monster::hit_player(game *g, player &p, bool can_grab)
{
 if (type->melee_dice == 0) // We don't attack, so just return
  return;
 add_effect(ME_HIT_BY_PLAYER, 3); // Make us a valid target for a few turns
 if (has_flag(MF_HIT_AND_RUN))
  add_effect(ME_RUN, 4);
 bool is_npc = p.is_npc();
 int  junk;
 bool u_see = (!is_npc || g->u_see(p.posx, p.posy, junk));
 std::string you  = (is_npc ? p.name : "you");
 std::string You  = (is_npc ? p.name : "You");
 std::string your = (is_npc ? p.name + "'s" : "your");
 std::string Your = (is_npc ? p.name + "'s" : "Your");
 body_part bphit;
 int side = rng(0, 1);
 int dam = hit(g, p, bphit), cut = type->melee_cut, stab = 0;
 technique_id tech = p.pick_defensive_technique(g, this, NULL);
 p.perform_defensive_technique(tech, g, this, NULL, bphit, side,
                               dam, cut, stab);
 if (dam == 0 && u_see)
  g->add_msg("The %s misses %s.", name().c_str(), you.c_str());
 else if (dam > 0) {
  if (u_see && tech != TEC_BLOCK)
   g->add_msg("The %s hits %s %s.", name().c_str(), your.c_str(),
              body_part_name(bphit, side).c_str());
// Attempt defensive moves

  if (!is_npc) {
   if (g->u.activity.type == ACT_RELOAD)
    g->add_msg("You stop reloading.");
   else if (g->u.activity.type == ACT_READ)
    g->add_msg("You stop reading.");
   else if (g->u.activity.type == ACT_CRAFT)
    g->add_msg("You stop crafting.");
   g->u.activity.type = ACT_NULL;
  }
  if (p.has_active_bionic(bio_ods)) {
   if (u_see)
    g->add_msg("%s offensive defense system shocks it!", Your.c_str());
   hurt(rng(10, 40));
  }
  if (p.encumb(bphit) == 0 &&
      (p.has_trait(PF_SPINES) || p.has_trait(PF_QUILLS))) {
   int spine = rng(1, (p.has_trait(PF_QUILLS) ? 20 : 8));
   g->add_msg("%s %s puncture it!", Your.c_str(),
              (g->u.has_trait(PF_QUILLS) ? "quills" : "spines"));
   hurt(spine);
  }

  if (dam + cut <= 0)
   return; // Defensive technique canceled damage.

  p.hit(g, bphit, side, dam, cut);
  if (has_flag(MF_VENOM)) {
   if (!is_npc)
    g->add_msg("You're poisoned!");
   p.add_disease(DI_POISON, 30, g);
  } else if (has_flag(MF_BADVENOM)) {
   if (!is_npc)
    g->add_msg("You feel poison flood your body, wracking you with pain...");
   p.add_disease(DI_BADPOISON, 40, g);
  }
  if (has_flag(MF_BLEED) && dam > 6 && cut > 0) {
   if (!is_npc)
    g->add_msg("You're Bleeding!");
   p.add_disease(DI_BLEED, 30, g);
  }
  if (can_grab && has_flag(MF_GRABS) &&
      dice(type->melee_dice, 10) > dice(p.dodge(g), 10)) {
   if (!is_npc)
    g->add_msg("The %s grabs you!", name().c_str());
   if (p.weapon.has_technique(TEC_BREAK, &p) &&
       dice(p.dex_cur + p.skillLevel("melee").level(), 12) > dice(type->melee_dice, 10)){
    if (!is_npc)
     g->add_msg("You break the grab!");
   } else
    hit_player(g, p, false);
  }

  if (tech == TEC_COUNTER && !is_npc) {
   g->add_msg("Counter-attack!");
   hurt( p.hit_mon(g, this) );
  }
 } // if dam > 0
 if (is_npc) {
  if (p.hp_cur[hp_head] <= 0 || p.hp_cur[hp_torso] <= 0) {
   npc* tmp = dynamic_cast<npc*>(&p);
   tmp->die(g);
   int index = g->npc_at(p.posx, p.posy);
   if (index != -1 && index < g->active_npc.size())
    g->active_npc.erase(g->active_npc.begin() + index);
   plans.clear();
  }
 }
// Adjust anger/morale of same-species monsters, if appropriate
 int anger_adjust = 0, morale_adjust = 0;
 for (unsigned int i = 0; i < type->anger.size(); i++) {
  if (type->anger[i] == MTRIG_FRIEND_ATTACKED)
   anger_adjust += 15;
 }
 for (unsigned int i = 0; i < type->placate.size(); i++) {
  if (type->placate[i] == MTRIG_FRIEND_ATTACKED)
   anger_adjust -= 15;
 }
 for (unsigned int i = 0; i < type->fear.size(); i++) {
  if (type->fear[i] == MTRIG_FRIEND_ATTACKED)
   morale_adjust -= 15;
 }
 if (anger_adjust != 0 && morale_adjust != 0) {
  for (unsigned int i = 0; i < g->z.size(); i++) {
   g->z[i].morale += morale_adjust;
   g->z[i].anger += anger_adjust;
  }
 }
}
Пример #15
0
int Piovra( struct char_data *pChar, int nCmd, const char *szArg,
            struct char_data *pMob, int nType )
{
  struct room_data *pRoom;
  if( pMob == NULL )
  {
    mudlog( LOG_SYSERR, "pMob == NULL in Piovra( carceri.h )" );
    return FALSE;
  }
  
  if( ( pRoom = real_roomp( pMob->in_room ) ) != NULL )
  {
    if( nType == EVENT_TICK && pMob->generic < 8 && AWAKE( pMob ) )
    {
      struct char_data *pNext, *pTar;
      
      for( pTar = pRoom->people; pTar; pTar = pNext )
      {
        pNext = pTar->next_in_room;
        
        if( IS_PC( pTar ) && IS_SET( pTar->specials.act, PLR_NOHASSLE ) )
          continue;  /* Ignora chi e` in NOHASSLE */
          
        if( pTar->specials.fighting && 
            mob_index[ pTar->specials.fighting->nr ].iVNum == TENTACOLI &&
            CAN_SEE( pMob, pTar ) )
          AddHated( pMob, pTar );
        if( ( pTar->specials.fighting == pMob || Hates( pMob, pTar ) ) &&
            CAN_SEE( pMob, pTar ) && ( !pTar->attackers || 
            ( pTar->attackers == 1 && pMob->specials.fighting == pTar ) ) )
        {
          struct char_data *pTentacolo = read_mobile( TENTACOLI, VIRTUAL );
          if( pTentacolo )
          {
            char_to_room( pTentacolo, pMob->in_room );
            hit( pTentacolo, pTar, TYPE_CRUSH );
            pMob->generic++;
            if( pMob->mult_att > 1 )
              pMob->mult_att--;
          }
          else
            mudlog( LOG_ERROR, 
                    "Cannot load mob Tentacolo in Piovra(carceri.c)" );
                            
        }
        else if( mob_index[ pTar->nr ].iVNum == TENTACOLI && 
                 !pTar->specials.fighting && pTar->attackers <= 0 )
        {
          extract_char( pTar );
          pMob->generic--;
          if( pMob->mult_att < 6 )
            pMob->mult_att++;
        }
      }
    }
    else if( nType == EVENT_DEATH )
    {
      struct char_data *pNext, *pTar;
      
      for( pTar = pRoom->people; pTar; pTar = pNext )
      {
        pNext = pTar->next_in_room;
        if( mob_index[ pTar->nr ].iVNum == TENTACOLI )
          extract_char( pTar );
      }
    }
    else if( nType == EVENT_COMMAND && nCmd == CMD_BASH ) 
    {
      while( isspace( *szArg ) )
        szArg++;
        
      if( ( !*szArg && pChar->specials.fighting == pMob ) ||
          ( *szArg && get_char_room_vis( pChar, szArg ) == pMob ) )
      {
        act( "Cerchi di colpire $N ma rimbalzi contro il suo corpo morbido.", 
             TRUE, pChar, 0, pMob, TO_CHAR );
        act( "$n cerca di colpire $N ma rimbalza contro il suo corpo morbido.",
             TRUE, pChar, 0, pMob, TO_ROOM );
        WAIT_STATE( pChar, PULSE_VIOLENCE * 2 );
        GET_POS( pChar ) = POSITION_SITTING;
        if( AWAKE( pMob ) )
          AddHated( pMob, pChar );
        return TRUE;
      }
    }
  }
  else
    mudlog( LOG_SYSERR, "pMob in invalid room in Piovra( carceri.c )" );

  return FALSE;
}
Пример #16
0
 // ------------------------------------------------------------------------
 virtual void hitTrack ()                      { hit(NULL);               }
Пример #17
0
void
psionic_best_attack(struct creature *ch, struct creature *vict)
{
    int aggression = calculate_mob_aggression(ch, vict);

    // Psions can't really do anything when there's a psishield in place
    if (AFF3_FLAGGED(vict, AFF3_PSISHIELD)
        && can_cast_spell(ch, SPELL_PSIONIC_SHATTER)) {
        cast_spell(ch, vict, NULL, NULL, SPELL_PSIONIC_SHATTER);
        return;
    }
    if (aggression > 75) {
        // extremely aggressive - just attack hard
        if (!affected_by_spell(vict, SPELL_PSYCHIC_SURGE)
            && can_cast_spell(ch, SPELL_PSYCHIC_SURGE)) {
            cast_spell(ch, vict, NULL, NULL, SPELL_PSYCHIC_SURGE);
            return;
        } else if (can_cast_spell(ch, SKILL_PSIBLAST)) {
            perform_offensive_skill(ch, vict, SKILL_PSIBLAST);
            return;
        } else if (GET_POSITION(vict) > POS_SITTING
            && can_cast_spell(ch, SPELL_EGO_WHIP)) {
            cast_spell(ch, vict, NULL, NULL, SPELL_EGO_WHIP);
            return;
        }
    }
    if (aggression > 50) {
        // somewhat aggressive - balance attacking with crippling
        if (!affected_by_spell(vict, SPELL_PSYCHIC_CRUSH)
            && can_cast_spell(ch, SPELL_PSYCHIC_CRUSH)) {
            cast_spell(ch, vict, NULL, NULL, SPELL_PSYCHIC_CRUSH);
            return;
        } else if (!affected_by_spell(vict, SPELL_MOTOR_SPASM)
            && can_cast_spell(ch, SPELL_MOTOR_SPASM)) {
            cast_spell(ch, vict, NULL, NULL, SPELL_MOTOR_SPASM);
            return;
        } else if (GET_POSITION(vict) > POS_SITTING
            && can_cast_spell(ch, SPELL_EGO_WHIP)) {
            cast_spell(ch, vict, NULL, NULL, SPELL_EGO_WHIP);
            return;
        } else if (can_cast_spell(ch, SKILL_PSIBLAST)) {
            perform_offensive_skill(ch, vict, SKILL_PSIBLAST);
            return;
        }
    }
    if (aggression > 25) {
        // not very aggressive - play more defensively
        if (!IS_CONFUSED(vict)
            && can_cast_spell(ch, SPELL_CONFUSION)
            && (IS_MAGE(vict) || IS_PSIONIC(vict) || IS_CLERIC(vict) ||
                IS_KNIGHT(vict) || IS_PHYSIC(vict))) {
            cast_spell(ch, vict, NULL, NULL, SPELL_CONFUSION);
            return;
        } else if (!AFF2_FLAGGED(ch, AFF2_VERTIGO)
            && can_cast_spell(ch, SPELL_VERTIGO)) {
            cast_spell(ch, vict, NULL, NULL, SPELL_VERTIGO);
            return;
        } else if (!affected_by_spell(vict, SPELL_PSYCHIC_FEEDBACK)
            && can_cast_spell(ch, SPELL_PSYCHIC_FEEDBACK)) {
            cast_spell(ch, vict, NULL, NULL, SPELL_PSYCHIC_FEEDBACK);
            return;
        } else if (nullpsi_is_advisable(vict)
            && can_cast_spell(ch, SPELL_NULLPSI)) {
            cast_spell(ch, vict, NULL, NULL, SPELL_NULLPSI);
            return;
        } else if (can_cast_spell(ch, SKILL_PSIBLAST)) {
            perform_offensive_skill(ch, vict, SKILL_PSIBLAST);
            return;
        }
    }
    if (aggression > 5) {
        // attempt to neutralize or get away
        if (GET_POSITION(vict) > POS_SLEEPING
            && can_cast_spell(ch, SPELL_MELATONIC_FLOOD)) {
            cast_spell(ch, vict, NULL, NULL, SPELL_MELATONIC_FLOOD);
            return;
        } else if (can_cast_spell(ch, SPELL_ASTRAL_SPELL)) {
            cast_spell(ch, vict, NULL, NULL, SPELL_ASTRAL_SPELL);
            return;
        } else if (can_cast_spell(ch, SPELL_AMNESIA)) {
            cast_spell(ch, vict, NULL, NULL, SPELL_AMNESIA);
            return;
        } else if (can_cast_spell(ch, SPELL_FEAR)) {
            cast_spell(ch, vict, NULL, NULL, SPELL_FEAR);
            return;
        }
    }
    // desperation - just attack full force, as hard as possible
    if (!affected_by_spell(vict, SPELL_PSYCHIC_SURGE)
        && can_cast_spell(ch, SPELL_PSYCHIC_SURGE)) {
        cast_spell(ch, vict, NULL, NULL, SPELL_PSYCHIC_SURGE);
        return;
    } else if (!affected_by_spell(vict, SPELL_PSYCHIC_CRUSH)
        && can_cast_spell(ch, SPELL_PSYCHIC_CRUSH)) {
        cast_spell(ch, vict, NULL, NULL, SPELL_PSYCHIC_CRUSH);
        return;
    } else if (!affected_by_spell(vict, SPELL_MOTOR_SPASM)
        && can_cast_spell(ch, SPELL_MOTOR_SPASM)) {
        cast_spell(ch, vict, NULL, NULL, SPELL_MOTOR_SPASM);
        return;
    } else if (can_cast_spell(ch, SKILL_PSIBLAST)) {
        perform_offensive_skill(ch, vict, SKILL_PSIBLAST);
        return;
    } else if (GET_POSITION(vict) > POS_SITTING
        && can_cast_spell(ch, SPELL_EGO_WHIP)) {
        cast_spell(ch, vict, NULL, NULL, SPELL_EGO_WHIP);
        return;
    } else if (GET_POSITION(vict) > POS_SLEEPING
        && can_cast_spell(ch, SPELL_MELATONIC_FLOOD)) {
        cast_spell(ch, vict, NULL, NULL, SPELL_MELATONIC_FLOOD);
        return;
    } else if (can_cast_spell(ch, SPELL_ASTRAL_SPELL)) {
        cast_spell(ch, vict, NULL, NULL, SPELL_ASTRAL_SPELL);
        return;
    } else if (can_cast_spell(ch, SPELL_AMNESIA)) {
        cast_spell(ch, vict, NULL, NULL, SPELL_AMNESIA);
        return;
    } else if (can_cast_spell(ch, SPELL_FEAR)) {
        cast_spell(ch, vict, NULL, NULL, SPELL_FEAR);
        return;
    } else {
        hit(ch, vict, TYPE_UNDEFINED);
    }
}
void game()
{
    int left=players;///for deciding if the dealer has to hit
    int grandgame=1;
    while (grandgame==1)
    {

    int first=0;
    srand(time(NULL));
    for(var=0;var<players+1;var++)///card amounts
    {
        hands[var]=1;///reset
        for(var2=3;var2>=0;var2--)
        {
            hand[var][var2][13]=0;///fill hand 13's with 0
        }
    }
    for(var=1;var<players+1;var++)
    {
        if (finance[var]==0)
        {
            continue;///can't play
        }
        printf("Player %d, how much would you like to bet?",var);
        printf(" You have %c%d available.\n",pounds,finance[var]);
        scanf("%d",&hand[var][0][14]);
        while (hand[var][0][14]>finance [var])
        {
            printf("You do not have enough money.You have %c%d available. Please choose again\n",pounds,finance[var]);
            scanf("%d",&hand[var][0][14]);
        }
        finance [var]=finance [var]-hand[var][0][14];
    }
    while(first<2)
    {
        for(var=0;var<players+1;var++)
            {
                if (hand[var][0][14]==0&&var>0)
                {
                    continue;
                }

                for (var2=0;var2<hands[var];var2++)
                {

                    a=hand[var][var2][13];

                    b=rand();
                    hand[var][var2][a]=pick(b);///last needs to be the card in hand being dealt
                    hand [var][var2][13]++;///how many cards in hand

                }

            }
            if (firstdeal==0)
                {
                    firstdeal=1;
                    var++;
                }
                first++;
    }
    int play=1;
    while (play==1)
    {
        printf("\t\tDealer Cards:");
        switch(hand[0][0][0])
        {
        case 1:
            printf("A ");
            break;
        case 11:
            printf("J ");
            break;
        case 12:
            printf("Q ");
            break;
        case 13:
            printf("K ");
            break;
        default:
            printf("%d ",hand[0][0][0]);
        }
        printf(" ?\n\n");
        var=0;
        var2=0;
        if(value()==21)
        {
            print();
            printf("Dealer Blackjack!\n");
            for(var=1;var<players+1;var++)
            {

                if (value()==21)
                {
                    printf("Player %d has a Blackjack- Push.",var);
                    finance[var]=finance[var]+hand[var][0][14];
                    hand[var][0][14]=0;
                }
                else
                {
                    printf("Player %d, you lose your bet.\n",var);
                    hand[var][0][14]=0;

                }
                hand[var][0][13]=0;
            }
            break;
        }
        for(var=1;var<players+1;var++)
        {
            printf("Player %d hand:",var);
            print();

        }
        printf("\n\n");
        for (var=1;var<=players;var++)//choice, not made by dealer !!!!do busts first!!!!
        {
            for (var2=0;var2<hands[var];var2++)
            {
                if (hand[var][var2][14]==0&&var>0)//skip empty hands
                {
                    continue;
                }
                if (finance[var]>=hand[var][var2][14])//only can split if have enough money
                {
                    left+=split();//amount of hands in play for dealer to hit
                }
                    if (value()>21)
                    {
                        printf("player %d has 'bust' and lost his bet\n\n Funds remaining= %c%d\n",var,pounds,finance[var]);
                        hand[var][var2][13]=0;///no cards
                        hand[var][var2][14]=0;
                        left--;
                        continue;
                    }
                    if (value()==21&&hand[var][var2][13]==2)
                    {
                        printf("Player %d, you have a blackjack! ",var);
                        if (hands[var]>1)
                        {
                            printf("with hand %d: ",var2);
                        }
                        else
                        {
                            ("with hand:");
                        }
                        print();
                        finance [var]=finance[var]+hand[var][var2][14];//both bet replaced and added (following) could do in one line using precedence.
                        finance [var]=finance[var]+hand[var][var2][14];
                        hand[var][var2][14]=0;
                        left--;
                        printf("Your total money is now %c%d\n\n",pounds,finance[var]);
                        continue;///move on to next hand.
                    }
                    printf("\nPlayer %d, your cards are:   ",var);
                    print();
                    if (finance [var]>=hand[var][var2][14])
                    {
                        printf("Do you want to 1. Hit, 2.Stand, or 3. Double-down");
                    }
                    else
                    {
                        printf("Do you want to 1. Hit, or 2.Stand");
                    }
                    if(var2>1)
                    {
                        printf(" with hand %d",var2+1);
                    }
                    printf("?\n");
                    scanf("%d",&hand[var][var2][12]);
                    //switch to send off to correct function.
                    switch (hand[var][var2][12])
                        {
                            case 1:
                                b=rand();
                                hit(b);
                                print();
                                var2--;//so can keep hitting, i.e. the for loop. could change previous if to while, but leave for now
                                hand[var][var2][12]=0;//allows to do this move and others
                                break;
                            case 2:
                                break;//for loop moves it on.
                            case 3:
                                if (finance [var]>=hand[var][var2][14])//only allows if enough money
                                {
                                    doubledown();
                                    break;
                                }
                            default:
                                printf("Invalid choice.\n");
                                var2--;//to replay that bit
                            }

                }

            }
            var=0;//set to dealer for functions using these variables
            var2=0;
            printf("Dealer Cards");
            print();
            if (left>0)
            {
                while (value()<17)
                {
                    a=hand[0][0][13];
                    b=rand();
                    hand[0][0][a]=pick(b);
                    hand [0][0][13]++;
                }
            }
            printf("Dealer Cards");
            print();
            printf("Dealer hand Value = %d\n",value());
            int dealertotal=value();

            for (var=1;var<=players;var++)//choice, not made by dealer !!!!do busts first!!!!
            {
                for (var2=0;var2<hands[var];var2++)
                {
                    if (hand[var][var2][14]==0)
                    {
                        continue;//to skip out already bust players.
                    }
                    if (dealertotal<22&&dealertotal>value())
                    {
                        hand[var][var2][14]=0;
                        printf("Bad news, player %d, you lost your bet.\n\n Your total money is now %c%d\n\n",var,pounds,finance[var]);
                    }
                    else if(dealertotal<22&&dealertotal==value())
                    {
                        finance [var]=finance[var]+hand[var][var2][14];
                        hand[var][var2][14]=0;
                        printf("Player %d, it's a push.\n\n Your total money is now %c%d\n\n",var,pounds,finance[var]);
                    }
                    else
                    {
                        finance [var]=finance[var]+hand[var][var2][14];
                        finance [var]=finance[var]+hand[var][var2][14];
                        hand[var][var2][14]=0;
                        printf("Well done player %d! You won this hand!\n\n Your total money is now %c%d\n\n",var,pounds,finance[var]);
                    }
                }
            }

            char carryon='r';
            while (carryon!='y'&&carryon!='n')
            {
                printf("Do you want another game, y/n ?\n");
                scanf(" %c",&carryon);
                if (carryon=='y')
                {
                    left=players;//or else dealer will stop hitting!(also could just reposition original...
                    var2=0;
                    if (decks<3)
                    {
                        for (var2=13;var2>0;var2--)//fill the cards
                        {
                            cards [var2]=decks*4;//amount of cards in pack x packs
                        }
                    }
                    else
                    {
                            for (var=1;var<14;var++)//how many cards left
                        {
                            var2=var2+cards[var];
                        }
                        if (var2<decks*17)//aprox a third of 52
                        {
                            for (var2=13;var2>0;var2--)//fill the cards
                            {
                                cards [var2]=decks*4;//amount of cards in pack x packs
                            }
                        }
                    }
                    play=0;
                }
                else if (carryon=='n')
                {
                    exit(0);
                }
            }


        }
    }
}
Пример #19
0
void
Jumpy::collision_solid(const CollisionHit& chit)
{
  hit(chit);
}
Пример #20
0
/* return TRUE if mon still alive */
bool
hmon(struct monst *mon, struct obj *obj, int thrown)
{
	int tmp;
	bool hittxt = FALSE;

	if (!obj) {
		tmp = rnd(2);	/* attack with bare hands */
		if (mon->data->mlet == 'c' && !uarmg) {
			pline("You hit the cockatrice with your bare hands.");
			pline("You turn to stone ...");
			done_in_by(mon);
		}
	} else if (obj->olet == WEAPON_SYM || obj->otyp == PICK_AXE) {
		if (obj == uwep && (obj->otyp > SPEAR || obj->otyp < BOOMERANG))
			tmp = rnd(2);
		else {
			if (strchr(mlarge, mon->data->mlet)) {
				tmp = rnd(objects[obj->otyp].wldam);
				if (obj->otyp == TWO_HANDED_SWORD)
					tmp += d(2, 6);
				else if (obj->otyp == FLAIL)
					tmp += rnd(4);
			} else
				tmp = rnd(objects[obj->otyp].wsdam);
			tmp += obj->spe;
			if (!thrown && obj == uwep && obj->otyp == BOOMERANG
			    && !rn2(3)) {
				pline("As you hit %s, the boomerang breaks into splinters.",
				    monnam(mon));
				freeinv(obj);
				setworn(NULL, obj->owornmask);
				obfree(obj, NULL);
				tmp++;
			}
		}
		if (mon->data->mlet == 'O' && obj->otyp == TWO_HANDED_SWORD &&
		    !strcmp(ONAME(obj), "Orcrist"))
			tmp += rnd(10);
	} else
		switch (obj->otyp) {
		case HEAVY_IRON_BALL:
			tmp = rnd(25);
			break;
		case EXPENSIVE_CAMERA:
			pline("You succeed in destroying your camera. Congratulations!");
			freeinv(obj);
			if (obj->owornmask)
				setworn(NULL, obj->owornmask);
			obfree(obj, NULL);
			return (TRUE);
		case DEAD_COCKATRICE:
			pline("You hit %s with the cockatrice corpse.",
			      monnam(mon));
			if (mon->data->mlet == 'c') {
				tmp = 1;
				hittxt = TRUE;
				break;
			}
			pline("%s is turned to stone!", Monnam(mon));
			killed(mon);
			return (FALSE);
		case CLOVE_OF_GARLIC:	/* no effect against demons */
			if (strchr(UNDEAD, mon->data->mlet))
				mon->mflee = 1;
			tmp = 1;
			break;
		default:
			/* non-weapons can damage because of their weight */
			/* (but not too much) */
			tmp = obj->owt / 10;
			if (tmp < 1)
				tmp = 1;
			else
				tmp = rnd(tmp);
			if (tmp > 6)
				tmp = 6;
		}

	/****** NOTE: perhaps obj is undefined!! (if !thrown && BOOMERANG) */

	tmp += u.udaminc + dbon();
	if (u.uswallow) {
		if ((tmp -= u.uswldtim) <= 0) {
			pline("Your arms are no longer able to hit.");
			return (TRUE);
		}
	}
	if (tmp < 1)
		tmp = 1;
	mon->mhp -= tmp;
	if (mon->mhp < 1) {
		killed(mon);
		return (FALSE);
	}
	if (mon->mtame && (!mon->mflee || mon->mfleetim)) {
		mon->mflee = 1;		/* Rick Richardson */
		mon->mfleetim += 10 * rnd(tmp);
	}

	if (!hittxt) {
		if (thrown) {
			/* this assumes that we cannot throw plural things */
			hit(xname(obj) /* or: objects[obj->otyp].oc_name */,
			    mon, exclam(tmp));
		} else if (Blind)
			pline("You hit it.");
		else
			pline("You hit %s%s", monnam(mon), exclam(tmp));
	}

	if (u.umconf && !thrown) {
		if (!Blind) {
			pline("Your hands stop glowing blue.");
			if (!mon->mfroz && !mon->msleep)
				pline("%s appears confused.", Monnam(mon));
		}
		mon->mconf = 1;
		u.umconf = 0;
	}
	return (TRUE);		/* mon still alive */
}
Пример #21
0
//This function uses the contents of m_blastOutput (the raw output from the
//BLAST search) to construct the BlastHit objects.
//It looks at the filters to possibly exclude hits which fail to meet user-
//defined thresholds.
void BlastSearch::buildHitsFromBlastOutput()
{
    QStringList blastHitList = m_blastOutput.split("\n", QString::SkipEmptyParts);

    for (int i = 0; i < blastHitList.size(); ++i)
    {
        QString hitString = blastHitList[i];
        QStringList alignmentParts = hitString.split('\t');

        if (alignmentParts.size() < 12)
            continue;

        QString queryName = alignmentParts[0];
        QString nodeLabel = alignmentParts[1];
        double percentIdentity = alignmentParts[2].toDouble();
        int alignmentLength = alignmentParts[3].toInt();
        int numberMismatches = alignmentParts[4].toInt();
        int numberGapOpens = alignmentParts[5].toInt();
        int queryStart = alignmentParts[6].toInt();
        int queryEnd = alignmentParts[7].toInt();
        int nodeStart = alignmentParts[8].toInt();
        int nodeEnd = alignmentParts[9].toInt();
        SciNot eValue(alignmentParts[10]);
        double bitScore = alignmentParts[11].toDouble();

        //Only save BLAST hits that are on forward strands.
        if (nodeStart > nodeEnd)
            continue;

        QString nodeName = getNodeNameFromString(nodeLabel);
        DeBruijnNode * node;
        if (g_assemblyGraph->m_deBruijnGraphNodes.contains(nodeName))
            node = g_assemblyGraph->m_deBruijnGraphNodes[nodeName];
        else
            continue;

        BlastQuery * query = g_blastSearch->m_blastQueries.getQueryFromName(queryName);
        if (query == 0)
            continue;

        QSharedPointer<BlastHit> hit(new BlastHit(query, node, percentIdentity, alignmentLength,
                                                  numberMismatches, numberGapOpens, queryStart, queryEnd,
                                                  nodeStart, nodeEnd, eValue, bitScore));

        //Check the user-defined filters.
        if (g_settings->blastAlignmentLengthFilterOn &&
                alignmentLength < g_settings->blastAlignmentLengthFilterValue)
            continue;
        if (g_settings->blastQueryCoverageFilterOn)
        {
            if (100.0 * hit->getQueryCoverageFraction() <= g_settings->blastQueryCoverageFilterValue)
                continue;
        }
        if (g_settings->blastIdentityFilterOn &&
                percentIdentity < g_settings->blastIdentityFilterValue)
            continue;
        if (g_settings->blastEValueFilterOn &&
                eValue > g_settings->blastEValueFilterValue)
                continue;
        if (g_settings->blastBitScoreFilterOn &&
                bitScore < g_settings->blastBitScoreFilterValue)
            continue;

        m_allHits.push_back(hit);
        query->addHit(hit);
    }
}
Пример #22
0
/*
 * Remove an affected_type structure from a char (called when duration
 * reaches zero). Pointer *af must never be NIL!  Frees mem and calls
 * affect_location_apply
 */
void affect_remove(struct char_data * ch, struct affected_type * af, int output)
{
  struct affected_type *temp;
  struct affected_type aff;
  bool accum_affect = FALSE;
  int k;

  if (ch->affected == NULL) {
    core_dump();
    return;
  }

  switch (af->type)
  {

    case SPELL_CHARM:
    { 
      struct char_data* victim = ch->master;
      if (output == 0) break;

      affect_modify(ch, af->location, af->modifier, af->bitvector, FALSE);
      REMOVE_FROM_LIST(af, ch->affected, next);
      free(af);
      affect_total(ch);

      if (ch->master)
      {
        stop_follower(ch);
      }

      if (victim)
      {
        if(IS_NPC(ch))
        {
          SET_BIT(MOB_FLAGS(ch), MOB_AGGRESSIVE | MOB_MEMORY);
        }
        if (mag_savingthrow(victim, SAVING_SPELL))
        {
          hit(victim, ch, TYPE_UNDEFINED);
        }
      }
      return;
    }

    case SPELL_LIGHT:
      if (output == 0) break;
      if (!af->next || (af->next->type != af->type) ||
         (af->next->duration > 0)) 
      {
        if (world[ch->in_room].name != (char*) NULL)
        {
          world[ch->in_room].light -= 10;
        }
      }
      break;
    case SPELL_DARKNESS:
      if (output == 0) break;
      if (!af->next || (af->next->type != af->type) ||
         (af->next->duration > 0)) 
      {
        if (world[ch->in_room].name != (char*) NULL)
        {
          world[ch->in_room].light += 10;
        }
      }
      break;
    case SPELL_BLACK_PLAGUE:
      mag_affects(30, ch, ch, SPELL_BREATH_OF_LIFE, SAVING_SPELL);
      break;
    case SPELL_CALL_ANIMAL_SPIRIT:
    case SPELL_ANIMAL_SUMMONING:
    case SPELL_ANIMAL_SUMMONING_II:
    case SPELL_ANIMAL_SUMMONING_III:
    case SPELL_CONJURE_ELEMENTAL:
    case SPELL_GREATER_ELEMENTAL:
    case SPELL_DUST_DEVIL:
    case SPELL_STICKS_TO_SNAKES:
    case SPELL_SUMMON_INSECTS:
    case SPELL_AERIAL_SERVANT:
    case SPELL_SUMMON_GUARD:
      if (IS_NPC(ch))
      {
        if (GET_POS(ch) > POS_DEAD)
        {
          if (output == 1)
          {
            affect_modify(ch, af->location, af->modifier, af->bitvector, FALSE);
            REMOVE_FROM_LIST(af, ch->affected, next);
            free(af);
            affect_total(ch);

            GET_NAME(ch, chname);
	    stop_fighting(ch); /*Fighting Bug Fix Jasrags*/
            sprintf(buf, "%s disappears into thin air as the summoning ends.", 
              chname);
            act(buf, FALSE, world[ch->in_room].people, 0, 0, TO_ROOM);
            FREE_NAME(chname);
            extract_char(ch);
            ch = NULL;
            return;
          }
        }
      }
      break;
   case SPELL_POLYMORPH:
   if (!PRF_FLAGGED(ch, PRF_NOTSELF)) {
          affect_modify(ch, af->location, af->modifier, af->bitvector, FALSE);
          REMOVE_FROM_LIST(af, ch->affected, next);
          free(af);
          affect_total(ch);
          return;
   }
   break;
   case SPELL_DONTUSEME:
   if(AFF_FLAGGED(ch, AFF_STANCE) && !AFF_FLAGGED(ch, AFF_TIRED)) {
      aff.type = SKILL_STANCE;
      aff.duration = 2;
      aff.location = APPLY_STR;
      aff.modifier = -2;
      aff.bitvector = AFF_TIRED;
      accum_affect = FALSE;

      affect_to_char(ch, &aff);
    }
   break;
    default:
      break;
  }

  if (output && (af->type > 0) && (af->type <= MAX_SPELLS) && af->type != SPELL_POLYMORPH && af->type != SPELL_DONTUSEME) {
    if (!af->next || (af->next->type != af->type) ||
        (af->next->duration > 0)) {
      if (*spell_wear_off_msg[af->type]) {
        send_to_char(spell_wear_off_msg[af->type], ch);
        send_to_char("\r\n", ch);
      }
  }
}

if (output && (af->type > 0) && (af->type <= MAX_SPELLS) && af->type == SPELL_POLYMORPH)  {

  if (!af->next || (af->next->type != af->type) ||
        (af->next->duration > 0)) {
   if (PLR_FLAGGED(ch, PLR_RABBIT)){
REMOVE_BIT(PLR_FLAGS(ch), PLR_RABBIT);
REMOVE_BIT(PRF_FLAGS(ch), PRF_NOTSELF);
send_to_char("You feel yourself growing, and your ears shrinking. You no longer feel like a rabbit.\r\n", ch);
act("$n's body grows, $s ears shrinking. $n no longer looks like a rabbit.\r\n", 0, ch, 0, 0, TO_ROOM);

}
if (PLR_FLAGGED(ch, PLR_BIRD)) {
REMOVE_BIT(PLR_FLAGS(ch), PLR_BIRD);
REMOVE_BIT(PRF_FLAGS(ch), PRF_NOTSELF);
send_to_char("You feel yourself growing and your feathers falling away. You no longer feel like a bird.\r\n", ch);
act("$n's body grows, $s feathers falling away as it expands. $n no longer looks like a bird.\r\n", 0, ch, 0, 0, TO_ROOM);

}
if (PLR_FLAGGED(ch, PLR_WOLF)) {
REMOVE_BIT(PLR_FLAGS(ch), PLR_WOLF);
REMOVE_BIT(PRF_FLAGS(ch), PRF_NOTSELF);
send_to_char("You feel your your fur shed and your teeth shrink. You no longer feel like a wolf.\r\n", ch);
act("$n's teeth shrink, $s fur shedding. $n no longer looks like a wolf.\r\n", 0, ch, 0, 0, TO_ROOM);
}
if (PLR_FLAGGED(ch, PLR_BEAR)) {
REMOVE_BIT(PLR_FLAGS(ch), PLR_BEAR);
REMOVE_BIT(PRF_FLAGS(ch), PRF_NOTSELF);
send_to_char("Your claws shrink as does the rest of your body. You no longer feel like a bear.\r\n", ch);
act("$n's claws shrink as does the rest of $s body. $n no longer looks like a bear.\r\n", 0, ch, 0, 0, TO_ROOM);
}
if (PLR_FLAGGED(ch, PLR_CAT)){
REMOVE_BIT(PLR_FLAGS(ch), PLR_CAT);
REMOVE_BIT(PRF_FLAGS(ch), PRF_NOTSELF);
send_to_char("You feel your body growing, and your fur shedding. You no longer feel like a cat.\r\n", ch);
act("$n's body slowly grows, $s fur shedding. $n no longer looks like a cat.\r\n", 0, ch, 0, 0, TO_ROOM);
}

for (k = 0; k < NUM_WEARS; k++)
  if (GET_EQ(ch, k)){
    GET_OBJ_DISGUISE(GET_EQ(ch, k)) = 0;
  }

}
} 

  affect_modify(ch, af->location, af->modifier, af->bitvector, FALSE);
  REMOVE_FROM_LIST(af, ch->affected, next);
  free(af);
  affect_total(ch);
}
Пример #23
0
boost::optional<double> Instance::hitDistance(Ray r)
{
    return (hit(r)).first;
}
/** Updates the rubber ball.
 *  \param dt Time step size.
 *  \returns True if the rubber ball should be removed.
 */
bool RubberBall::updateAndDelete(float dt)
{
    LinearWorld *world = dynamic_cast<LinearWorld*>(World::getWorld());
    // FIXME: what does the rubber ball do in case of battle mode??
    if(!world) return true;

    if(m_delete_timer>0)
    {
        m_delete_timer -= dt;
        if(m_delete_timer<=0)
        {
            hit(NULL);
#ifdef PRINT_BALL_REMOVE_INFO
            Log::debug("RubberBall", "ball %d deleted.", m_id);
#endif
            return true;
        }
    }

    // Update the target in case that the first kart was overtaken (or has
    // finished the race).
    computeTarget();
    updateDistanceToTarget();

    // Determine the new position. This new position is only temporary,
    // since it still needs to be adjusted for the height of the terrain.
    Vec3 next_xyz;
    if(m_aiming_at_target)
        moveTowardsTarget(&next_xyz, dt);
    else
        interpolate(&next_xyz, dt);

    // If the ball is close to the ground, we have to start the raycast
    // slightly higher (to avoid that the ball tunnels through the floor).
    // But if the ball is close to the ceiling of a tunnel and we would
    // start the raycast slightly higher, the ball might end up on top
    // of the ceiling.
    // The ball is considered close to the ground if the height above the
    // terrain is less than half the current maximum height.
    bool close_to_ground = 2.0*m_previous_height < m_current_max_height;

    float vertical_offset = close_to_ground ? 4.0f : 2.0f;
    // Note that at this stage getHoT still reports the height at
    // the previous location (since TerrainInfo wasn't updated). On
    // the other hand, we can't update TerrainInfo without having
    // at least a good estimation of the height.
    next_xyz.setY(getHoT() + vertical_offset);
    // Update height of terrain (which isn't done as part of
    // Flyable::update for rubber balls.
    TerrainInfo::update(next_xyz);

    m_height_timer += dt;
    float height    = updateHeight()+m_extend.getY()*0.5f;
    float new_y     = getHoT()+height;

    if(UserConfigParams::logFlyable())
        printf("ball %d: %f %f %f height %f new_y %f gethot %f ",
                m_id, next_xyz.getX(), next_xyz.getY(), next_xyz.getZ(), height, new_y, getHoT());

    // No need to check for terrain height if the ball is low to the ground
    if(height > 0.5f)
    {
        float terrain_height = getMaxTerrainHeight(vertical_offset)
                             - m_extend.getY();
        if(new_y>terrain_height)
            new_y = terrain_height;
    }

    if(UserConfigParams::logFlyable())
        Log::verbose("RubberBall", "newy2 %f gmth %f", new_y,
                     getMaxTerrainHeight(vertical_offset));

    next_xyz.setY(new_y);
    m_previous_xyz = getXYZ();
    m_previous_height = next_xyz.getY()-getHoT();
    setXYZ(next_xyz);

    if(checkTunneling())
        return true;

    // Determine new distance along track
    TrackSector::update(next_xyz);

    // Ball squashing:
    // ===============
    if(height<1.5f*m_extend.getY())
        m_node->setScale(core::vector3df(1.0f, height/m_extend.getY(),1.0f));
    else
        m_node->setScale(core::vector3df(1.0f, 1.0f, 1.0f));

    return Flyable::updateAndDelete(dt);
}   // updateAndDelete
Пример #25
0
Bool_t TTSelector::Process(Long64_t entry){
  Int_t trbSeqId,ch,mcp,pix,col,row;;
  Double_t timeTot(0), grTime0(0), grTime1(0),timeLe(0),coarseTime;
  Double_t time[50000];
  
  if(entry%1000==0) std::cout<<"event # "<< entry <<std::endl;
  GetEntry(entry);
  
  fEvent = new TPrtEvent();
  fEvent->SetReferenceChannel(gTrigger);
  for(Int_t i=0; i<Hits_; i++){
    trbSeqId = tdcmap[Hits_nTrbAddress[i]];
    ch = 32*trbSeqId+Hits_nTdcChannel[i];
    
    if(++mult[ch]>50) continue;
    coarseTime = 5*(Hits_nEpochCounter[i]*pow(2.0,11) + Hits_nCoarseTime[i]);
    time[i] = coarseTime-gGr[ch]->Eval(Hits_nFineTime[i]);

    timeTe0[ch][mult[ch]]=time[i];
    if(Hits_nTdcChannel[i]==0) {  // is ref channel
      trbRefTime[trbSeqId] = time[i];
      if(gTrigger!=0 && (gTrigger-ch)<=32 && (gTrigger-ch)>0) grTime0 = time[i];
    }
    if(gTrigger!=0 && ch==gTrigger) grTime1 = time[i];
  }
  
  if((grTime0>0 && grTime1>0) || gTrigger==0){
    for(Int_t i=0; i<Hits_; i++){
      if(Hits_nTrbAddress[i]==0) continue;
      trbSeqId = tdcmap[Hits_nTrbAddress[i]];
      ch = 32*trbSeqId+Hits_nTdcChannel[i];
      mcp = ch/128;
      pix = (ch%128)/2;	
      col = pix/2 - 8*(pix/16);
      row = pix%2 + 2*(pix/16);
      pix = (7-col)*8+row;
      
      if(ch%2==0) continue; // go away trailing edge
      if(ch<3000) {
	timeLe = time[i]-trbRefTime[trbSeqId];
	timeLe = timeLe - (grTime1-grTime0);
	
	//if(ch == 241) hL->Fill(timeLe);
	
        timeTot = timeTe0[ch+1][1] - timeTe0[ch][1]; 
	if(gMode == 1 && ch<1920) timeLe -= gGrDiff[ch]->Eval(timeTot);

	TPrtHit hit(Hits_nTrbAddress[i],Hits_nTdcChannel[i],ch,mcp,pix+1,timeLe,timeTot);
	fEvent->AddHit(hit);
      }
    }
  }

  for(Int_t i=0; i<Hits_; i++){
    trbSeqId = tdcmap[Hits_nTrbAddress[i]];
    ch = 32*trbSeqId+Hits_nTdcChannel[i];
    mult[ch]=0;
    for(Int_t j=0; j<50; j++){
      timeTe0[ch][j]=0; 
    }
  }
  fTree->Fill();
  fEvent->Clear();
  delete fEvent;

  return kTRUE;
}
Пример #26
0
 bool Primitive::hit(const utils::Ray &ws_ray) const {
   float thit;
   return hit(ws_ray, thit);
 }
Пример #27
0
int player::hit_mon(game *g, monster *z)
{
 bool is_u = (this == &(g->u));	// Affects how we'll display messages
 int j;
 bool can_see = (is_u || g->u_see(posx, posy, j));
 std::string You  = (is_u ? "You"  : name);
 std::string Your = (is_u ? "Your" : name + "'s");
 std::string your = (is_u ? "your" : (male ? "his" : "her"));

// Types of combat (may overlap!)
 bool unarmed  = unarmed_attack(), bashing = weapon.is_bashing_weapon(),
      cutting  = weapon.is_cutting_weapon(),
      stabbing = (weapon.has_flag(IF_SPEAR) ||
                  weapon.has_flag(IF_STAB)    );

// Recoil penalty
 if (recoil <= 30)
  recoil += 6;
// Movement cost
 moves -= weapon.attack_time() + 20 * encumb(bp_torso);
// Different sizes affect your chance to hit
 if (hit_roll() < z->dodge_roll() ||
     one_in(4 + dex_cur + weapon.type->m_to_hit)) {// A miss!
  stumble(g);
  return 0;
 }
// For very high hit rolls, we crit!
 bool critical_hit = scored_crit(z->dodge_roll());
 int dam = base_damage(true);
 int cutting_penalty = 0; // Moves lost from getting a cutting weapon stuck

// Drunken Master damage bonuses
 if (has_trait(PF_DRUNKEN) && has_disease(DI_DRUNK)) {
// Remember, a single drink gives 600 levels of DI_DRUNK
  int mindrunk, maxdrunk;
  if (unarmed) {
   mindrunk = disease_level(DI_DRUNK) / 600;
   maxdrunk = disease_level(DI_DRUNK) / 250;
  } else {
   mindrunk = disease_level(DI_DRUNK) / 900;
   maxdrunk = disease_level(DI_DRUNK) / 400;
  }
  dam += rng(mindrunk, maxdrunk);
 }

 if (unarmed) { // Unarmed bonuses
  dam += rng(0, sklevel[sk_unarmed]);
  if (has_trait(PF_TALONS) && z->type->armor - sklevel[sk_unarmed] < 10) {
   int z_armor = (z->type->armor - sklevel[sk_unarmed]);
   if (z_armor < 0)
    z_armor = 0;
   dam += 10 - z_armor;
  }
 }
 if (rng(1, 45 - dex_cur) < 2 * sklevel[sk_unarmed] &&
     rng(1, 65 - dex_cur) < 2 * sklevel[sk_unarmed]   ) {
// Bonus unarmed attack!
  if (is_u || can_see) {
   switch (rng(1, 4)) {
    case 1: g->add_msg("%s kick%s the %s!", You.c_str(), (is_u ? "" : "s"),
                       z->name().c_str()); break;
    case 2: g->add_msg("%s headbutt%s the %s!", You.c_str(), (is_u ? "" : "s"),
                       z->name().c_str()); break;
    case 3: g->add_msg("%s elbow%s the %s!", You.c_str(), (is_u ? "" : "s"),
                       z->name().c_str()); break;
    case 4: g->add_msg("%s knee%s the %s!", You.c_str(), (is_u ? "" : "s"),
                       z->name().c_str()); break;
   }
  }
  if (sklevel[sk_unarmed] >= 4)
   dam += rng(1, sklevel[sk_unarmed] / 2);
  else
   dam++;
  practice(sk_unarmed, 2);
 }
// Melee skill bonus
 dam += rng(0, sklevel[sk_melee]);
// Bashing damage bonus
 int bash_dam = weapon.damage_bash(),
     bash_cap = 5 + str_cur + sklevel[sk_bashing];
 if (bash_dam > bash_cap)// Cap for weak characters
  bash_dam = (bash_cap * 3 + bash_dam) / 4;
 if (bashing)
  bash_dam += rng(0, sklevel[sk_bashing] + sqrt(double(str_cur)));
 if (z->has_flag(MF_PLASTIC))
  bash_dam /= rng(2, 4);
 int bash_min = bash_dam / 4;
 if (bash_min < sklevel[sk_bashing] )
  bash_min = sklevel[sk_bashing];
 dam += rng(bash_min, bash_dam);
// Take some moves away from the target; at this point it's skill & bash damage
 z->moves -= rng(0, dam * 2);
// Spears treat cutting damage specially.
 if (weapon.has_flag(IF_SPEAR) &&
     weapon.damage_cut() > z->type->armor - int(sklevel[sk_stabbing])) {
  int z_armor = z->type->armor - int(sklevel[sk_stabbing]);
  dam += int(weapon.damage_cut() / 5);
  int minstab = sklevel[sk_stabbing] *  5 + weapon.volume() * 2,
      maxstab = sklevel[sk_stabbing] * 15 + weapon.volume() * 4;
  int monster_penalty = rng(minstab, maxstab);
  if (monster_penalty >= 150)
   g->add_msg("You force the %s to the ground!", z->name().c_str());
  else if (monster_penalty >= 50)
   g->add_msg("The %s is skewered and flinches!", z->name().c_str());
  z->moves -= monster_penalty;
  cutting_penalty = weapon.damage_cut() * 4 + z_armor * 8 -
                    dice(sklevel[sk_stabbing], 10);
  practice(sk_stabbing, 2);
// Cutting damage bonus
 } else if (weapon.damage_cut() >
            z->type->armor - int(sklevel[sk_cutting] / 2)) {
  int z_armor = z->type->armor - int(sklevel[sk_cutting] / 2);
  if (z_armor < 0)
   z_armor = 0;
  dam += weapon.damage_cut() - z_armor;
  cutting_penalty = weapon.damage_cut() * 3 + z_armor * 8 -
                    dice(sklevel[sk_cutting], 10);
 }
 if (weapon.has_flag(IF_MESSY)) { // e.g. chainsaws
  cutting_penalty /= 6; // Harder to get stuck
  for (int x = z->posx - 1; x <= z->posx + 1; x++) {
   for (int y = z->posy - 1; y <= z->posy + 1; y++) {
    if (!one_in(3)) {
     if (g->m.field_at(x, y).type == fd_blood &&
         g->m.field_at(x, y).density < 3)
      g->m.field_at(x, y).density++;
     else
      g->m.add_field(g, x, y, fd_blood, 1);
    }
   }
  }
 }

// Bonus attacks!

 bool shock_them = (has_bionic(bio_shock) && power_level >= 2 && unarmed &&
                    one_in(3));
 bool drain_them = (has_bionic(bio_heat_absorb) && power_level >= 1 &&
                    !is_armed() && z->has_flag(MF_WARM));
 bool  bite_them = (has_trait(PF_FANGS) && z->armor() < 18 &&
                    one_in(20 - dex_cur - sklevel[sk_unarmed]));
 bool  peck_them = (has_trait(PF_BEAK)  && z->armor() < 16 &&
                    one_in(15 - dex_cur - sklevel[sk_unarmed]));
 if (drain_them)
  power_level--;
 drain_them &= one_in(2);	// Only works half the time

// Critical hit effects
 if (critical_hit) {
  bool headshot = (!z->has_flag(MF_NOHEAD) && !one_in(3));
// Second chance for shock_them, drain_them, bite_them and peck_them
  shock_them = (shock_them || (has_bionic(bio_shock)&& power_level >= 2 &&
                               unarmed && !one_in(3)));
  drain_them = (drain_them || (has_bionic(bio_heat_absorb) && !is_armed() &&
                               power_level >= 1 && z->has_flag(MF_WARM) &&
                               !one_in(3)));
  bite_them  = ( bite_them || (has_trait(PF_FANGS) && z->armor() < 18 &&
                               one_in(5)));
  peck_them  = ( peck_them || (has_trait(PF_BEAK)  && z->armor() < 16 &&
                               one_in(4)));

  if (weapon.has_flag(IF_SPEAR) || weapon.has_flag(IF_STAB)) {
   dam += weapon.damage_cut();
   dam += weapon.damage_cut() * double(sklevel[sk_stabbing] / 10);
   practice(sk_stabbing, 5);
  }

  if (unarmed) {
   dam += rng(1, 4) * sklevel[sk_unarmed];
   if (sklevel[sk_unarmed] > 5)
    dam += 4 * (sklevel[sk_unarmed] - 5);
   z->moves -= dam;	// Stunning blow
   if (weapon.type->id == itm_bio_claws) {
    if (sklevel[sk_cutting] >= 3)
     dam += 5;
    headshot &= z->hp < dam && one_in(2);
    if (headshot && can_see)
     g->add_msg("%s claws pierce the %s's skull!", Your.c_str(),
                z->name().c_str());
    else if (can_see)
     g->add_msg("%s claws stab straight through the %s!", Your.c_str(),
                z->name().c_str());
   } else if (has_trait(PF_TALONS)) {
    dam += 2;
    headshot &= z->hp < dam && one_in(2);
    if (headshot && can_see)
     g->add_msg("%s talons tear the %s's head open!", Your.c_str(),
                z->name().c_str());
    else if (can_see)
     g->add_msg("%s bur%s %s talons into the %s!", You.c_str(),(is_u?"y":"ies"),
                your.c_str(), z->name().c_str());
   } else {
    headshot &= z->hp < dam && one_in(2);
    if (headshot && can_see)
     g->add_msg("%s crush%s the %s's skull in a single blow!", 
                You.c_str(), (is_u ? "" : "es"), z->name().c_str());
    else if (can_see)
     g->add_msg("%s deliver%s a crushing punch!",You.c_str(),(is_u ? "" : "s"));
   }
   if (z->hp > 0 && rng(1, 5) < sklevel[sk_unarmed])
    z->add_effect(ME_STUNNED, 1 + sklevel[sk_unarmed]);
  } else {	// Not unarmed
   if (bashing) {
    dam += 8 + (str_cur / 2);
    int turns_stunned = int(dam / 20) + int(sklevel[sk_bashing] / 2);
    if (turns_stunned > 6)
     turns_stunned = 6;
    z->add_effect(ME_STUNNED, turns_stunned);
   }
   if (cutting || stabbing) {
    double cut_multiplier = double(sklevel[sk_cutting] / 12);
    if (cut_multiplier > 1.5)
     cut_multiplier = 1.5;
    dam += cut_multiplier * weapon.damage_cut();
    headshot &= z->hp < dam;
    if (stabbing) {
     if (headshot && can_see)
      g->add_msg("%s %s stabs through the %s's skull!", Your.c_str(),
                 weapon.tname(g).c_str(), z->name().c_str());
     else if (can_see)
      g->add_msg("%s stab %s %s through the %s!", You.c_str(), your.c_str(),
                 weapon.tname(g).c_str(), z->name().c_str());
    } else {
     if (headshot && can_see)
      g->add_msg("%s %s slices the %s's head off!", Your.c_str(),
                 weapon.tname(g).c_str(), z->name().c_str());
     else
      g->add_msg("%s %s cuts the %s deeply!", Your.c_str(),
                 weapon.tname(g).c_str(), z->name().c_str());
    }
   } else if (bashing) {
    headshot &= z->hp < dam;
    if (headshot && can_see)
     g->add_msg("%s crush%s the %s's skull!", You.c_str(), (is_u ? "" : "es"),
                z->name().c_str());
    else if (can_see)
     g->add_msg("%s crush%s the %s's body!", You.c_str(), (is_u ? "" : "es"),
                z->name().c_str());
   }
  }	// End of not-unarmed
 }	// End of critical hit

 if (shock_them) {
  power_level -= 2;
  if (can_see)
   g->add_msg("%s shock%s the %s!", You.c_str(), (is_u ? "" : "s"),
              z->name().c_str());
  int shock = rng(2, 5);
  dam += shock * rng(1, 3);
  z->moves -= shock * 180;
 }
 if (drain_them) {
  charge_power(rng(0, 4));
  if (can_see)
   g->add_msg("%s drain%s the %s's body heat!", You.c_str(), (is_u ? "" : "s"),
              z->name().c_str());
  dam += rng(4, 10);
  z->moves -= rng(80, 120);
 }
 if (bite_them) {
  if (can_see)
   g->add_msg("%s sink %s fangs into the %s!", You.c_str(), your.c_str(),
              z->name().c_str());
  dam += 18 - z->armor();
 }
 if (peck_them) {
  if (can_see)
   g->add_msg("%s peck%s the %s viciously!", You.c_str(), (is_u ? "" : "s"),
              z->name().c_str());
  dam += 16 - z->armor();
 }

// Make a rather quiet sound, to alert any nearby monsters
 g->sound(posx, posy, 8, "");

// Glass weapons shatter sometimes
 if (weapon.made_of(GLASS) &&
     rng(0, weapon.volume() + 8) < weapon.volume() + str_cur) {
  if (can_see)
   g->add_msg("%s %s shatters!", Your.c_str(), weapon.tname(g).c_str());
  g->sound(posx, posy, 16, "");
// Dump its contents on the ground
  for (int i = 0; i < weapon.contents.size(); i++)
   g->m.add_item(posx, posy, weapon.contents[i]);
  hit(g, bp_arms, 1, 0, rng(0, weapon.volume() * 2));// Take damage
  if (weapon.is_two_handed(this))// Hurt left arm too, if it was big
   hit(g, bp_arms, 0, 0, rng(0, weapon.volume()));
  dam += rng(0, 5 + int(weapon.volume() * 1.5));// Hurt the monster extra
  remove_weapon();
 }

 if (dam <= 0) {
  if (is_u)
   g->add_msg("You hit the %s, but do no damage.", z->name().c_str());
  else if (can_see)
   g->add_msg("%s's %s hits the %s, but does no damage.", You.c_str(),
              weapon.tname(g).c_str(), z->name().c_str());
  practice(sk_melee, rng(2, 5));
  if (unarmed)
   practice(sk_unarmed, 2);
  if (bashing)
   practice(sk_bashing, 2);
  if (cutting)
   practice(sk_cutting, 2);
  if (stabbing)
   practice(sk_stabbing, 2);
  return 0;
 }
 if (is_u)
  g->add_msg("You hit the %s for %d damage.", z->name().c_str(), dam);
 else if (can_see)
  g->add_msg("%s hits the %s with %s %s.", You.c_str(), z->name().c_str(),
             (male ? "his" : "her"),
             (weapon.type->id == 0 ? "fists" : weapon.tname(g).c_str()));
 practice(sk_melee, rng(5, 10));
 if (unarmed)
  practice(sk_unarmed, rng(5, 10));
 if (bashing)
  practice(sk_bashing, rng(5, 10));
 if (cutting)
  practice(sk_cutting, rng(5, 10));
 if (stabbing)
  practice(sk_stabbing, rng(5, 10));

// Penalize the player if their cutting weapon got stuck
 if (!unarmed && dam < z->hp && cutting_penalty > dice(str_cur * 2, 20)) {
  if (is_u)
   g->add_msg("Your %s gets stuck in the %s, pulling it out of your hands!",
              weapon.tname().c_str(), z->type->name.c_str());
  z->add_item(remove_weapon());
  if (weapon.has_flag(IF_SPEAR) || weapon.has_flag(IF_STAB))
   z->speed *= .7;
  else
   z->speed *= .85;
 } else {
  if (dam >= z->hp) {
   cutting_penalty /= 2;
   cutting_penalty -= rng(sklevel[sk_cutting], sklevel[sk_cutting] * 2 + 2);
  }
  if (cutting_penalty > 0)
   moves -= cutting_penalty;
  if (cutting_penalty >= 50 && is_u)
   g->add_msg("Your %s gets stuck in the %s, but you yank it free.",
              weapon.tname().c_str(), z->type->name.c_str());
  if (weapon.has_flag(IF_SPEAR) || weapon.has_flag(IF_STAB))
   z->speed *= .9;
 }

 return dam;
}
Пример #28
0
void
Kugelblitz::collision_solid(const CollisionHit& chit)
{
  hit(chit);
}
Пример #29
0
void monster::hit_player(game *g, player &p, bool can_grab)
{
    moves -= 100;

    if (type->melee_dice == 0) // We don't attack, so just return
    {
        return;
    }
    add_effect(ME_HIT_BY_PLAYER, 3); // Make us a valid target for a few turns
    if (has_flag(MF_HIT_AND_RUN))
    {
        add_effect(ME_RUN, 4);
    }
    bool is_npc = p.is_npc();
    bool u_see = (!is_npc || g->u_see(p.posx, p.posy));
    std::string you  = (is_npc ? p.name : "you");
    std::string You  = (is_npc ? p.name : "You");
    std::string your = (is_npc ? p.name + "'s" : "your");
    std::string Your = (is_npc ? p.name + "'s" : "Your");
    body_part bphit;
    int side = rng(0, 1);
    int dam = hit(g, p, bphit), cut = type->melee_cut, stab = 0;
    technique_id tech = p.pick_defensive_technique(g, this, NULL);
    p.perform_defensive_technique(tech, g, this, NULL, bphit, side, dam, cut, stab);

    //110*e^(-.3*[melee skill of monster]) = % chance to miss. *100 to track .01%'s
    //Returns ~80% at 1, drops quickly to 33% at 4, then slowly to 5% at 10 and 1% at 16
    if (rng(0, 10000) < 11000 * exp(-.3 * type->melee_skill))
    {
        g->add_msg("The %s misses.", name().c_str());
    }
    else
    {
        //Reduce player's ability to dodge by monster's ability to hit
        int dodge_ii = p.dodge(g) - rng(0, type->melee_skill);
        if (dodge_ii < 0)
        {
            dodge_ii = 0;
        }

        // 100/(1+99*e^(-.6*[dodge() return modified by monster's skill])) = % chance to dodge
        // *100 to track .01%'s
        // 1% minimum, scales slowly to 16% at 5, then rapidly to 80% at 10,
        // then returns less with each additional point, reaching 99% at 16
        if (rng(0, 10000) < 10000/(1 + 99 * exp(-.6 * dodge_ii)))
        {
            g->add_msg("%s dodge the %s.", You.c_str(), name().c_str());
            p.practice(g->turn, "dodge", type->melee_skill * 2); //Better monster = more skill gained
        }

        //Successful hit with damage
        else if (dam > 0)
        {
            p.practice(g->turn, "dodge", type->melee_skill);
            if (u_see && tech != TEC_BLOCK)
            {
                g->add_msg("The %s hits %s %s.", name().c_str(), your.c_str(),
                           body_part_name(bphit, side).c_str());
            }

            // Attempt defensive moves
            if (!is_npc)
            {
                if (g->u.activity.type == ACT_RELOAD)
                {
                    g->add_msg("You stop reloading.");
                }
                else if (g->u.activity.type == ACT_READ)
                {
                    g->add_msg("You stop reading.");
                }
                else if (g->u.activity.type == ACT_CRAFT || g->u.activity.type == ACT_LONGCRAFT)
                {
                    g->add_msg("You stop crafting.");
                    g->u.activity.type = ACT_NULL;
                }
            }
            if (p.has_active_bionic("bio_ods"))
            {
                if (u_see)
                {
                    g->add_msg("%s offensive defense system shocks it!", Your.c_str());
                }
                if (hurt(rng(10, 40)))
                    die(g);
            }
            if (p.encumb(bphit) == 0 &&(p.has_trait(PF_SPINES) || p.has_trait(PF_QUILLS)))
            {
                int spine = rng(1, (p.has_trait(PF_QUILLS) ? 20 : 8));
                g->add_msg("%s %s puncture it!", Your.c_str(),
                           (g->u.has_trait(PF_QUILLS) ? "quills" : "spines"));
                if (hurt(spine))
                    die(g);
            }

            if (dam + cut <= 0)
            {
                return; // Defensive technique canceled damage.
            }

            //Hurt the player
            dam = p.hit(g, bphit, side, dam, cut);

            //Monster effects
            if (dam > 0 && has_flag(MF_VENOM))
            {
                if (!is_npc)
                {
                    g->add_msg("You're poisoned!");
                }
                p.add_disease("poison", 30);
            }
            else if (dam > 0 && has_flag(MF_BADVENOM))
            {
                if (!is_npc)
                {
                    g->add_msg("You feel poison flood your body, wracking you with pain...");
                }
                p.add_disease("badpoison", 40);
            }
            if (has_flag(MF_BLEED) && dam > 6 && cut > 0)
            {
                if (!is_npc)
                {
                    g->add_msg("You're Bleeding!");
                }
                p.add_disease("bleed", 60);
            }

            //Same as monster's chance to not miss
            if (can_grab && has_flag(MF_GRABS) && (rng(0, 10000) > 11000 * exp(-.3 * type->melee_skill)))
            {
                if (!is_npc)
                {
                    g->add_msg("The %s grabs you!", name().c_str());
                }
                if (p.weapon.has_technique(TEC_BREAK, &p) &&
                    dice(p.dex_cur + p.skillLevel("melee"), 12) > dice(type->melee_dice, 10))
                {
                    if (!is_npc)
                    {
                        g->add_msg("You break the grab!");
                    }
                }
                else
                    hit_player(g, p, false); //We grabed, so hit them again
            }

            //Counter-attack?
            if (tech == TEC_COUNTER && !is_npc)
            {
                g->add_msg("Counter-attack!");
                // A counterattack is a free action to avoid stunlocking the player.
                int player_moves = p.moves;
                hurt( p.hit_mon(g, this) );
                p.moves = player_moves;
            }
        }
    }

    // if dam > 0
    if (is_npc)
    {
        if (p.hp_cur[hp_head] <= 0 || p.hp_cur[hp_torso] <= 0)
        {
            npc* tmp = dynamic_cast<npc*>(&p);
            tmp->die(g);
            int index = g->npc_at(p.posx, p.posy);
            if (index != -1 && index < g->active_npc.size())
            {
                g->active_npc.erase(g->active_npc.begin() + index);
            }
            plans.clear();
        }
    }

    // Adjust anger/morale of same-species monsters, if appropriate
    int anger_adjust = 0, morale_adjust = 0;
    for (int i = 0; i < type->anger.size(); i++)
    {
        if (type->anger[i] == MTRIG_FRIEND_ATTACKED)
        {
            anger_adjust += 15;
        }
    }
    for (int i = 0; i < type->placate.size(); i++)
    {
        if (type->placate[i] == MTRIG_FRIEND_ATTACKED)
        {
            anger_adjust -= 15;
        }
    }
    for (int i = 0; i < type->fear.size(); i++)
    {
        if (type->fear[i] == MTRIG_FRIEND_ATTACKED)
        {
            morale_adjust -= 15;
        }
    }
    if (anger_adjust != 0 && morale_adjust != 0)
    {
        for (int i = 0; i < g->z.size(); i++)
        {
            g->z[i].morale += morale_adjust;
            g->z[i].anger += anger_adjust;
        }
    }
}
Пример #30
0
void
mage_best_attack(struct creature *ch, struct creature *vict)
{
    int calculate_mob_aggression(struct creature *, struct creature *);
    int aggression = calculate_mob_aggression(ch, vict);

    if (aggression > 75) {
        // extremely aggressive - just attack hard
        if (mage_damaging_attack(ch, vict))
            return;
    }
    if (aggression > 50) {
        // somewhat aggressive - balance attacking with crippling
        if (GET_POSITION(vict) > POS_SLEEPING
            && can_cast_spell(ch, SPELL_WORD_STUN)) {
            cast_spell(ch, vict, NULL, NULL, SPELL_WORD_STUN);
            return;
        } else if (GET_POSITION(vict) > POS_SLEEPING
            && can_cast_spell(ch, SPELL_SLEEP)) {
            cast_spell(ch, vict, NULL, NULL, SPELL_SLEEP);
            return;
        } else if (!AFF_FLAGGED(vict, AFF_BLIND)
            && can_cast_spell(ch, SPELL_BLINDNESS)) {
            cast_spell(ch, vict, NULL, NULL, SPELL_BLINDNESS);
            return;
        } else if (!AFF_FLAGGED(vict, AFF_CURSE)
            && can_cast_spell(ch, SPELL_CURSE)) {
            cast_spell(ch, vict, NULL, NULL, SPELL_CURSE);
            return;
        }
    }
    if (aggression > 25) {
        // not very aggressive - play more defensively
        if (can_cast_spell(ch, SPELL_DISPEL_MAGIC)
            && dispel_is_advisable(vict)) {
            cast_spell(ch, vict, NULL, NULL, SPELL_DISPEL_MAGIC);
            return;
        } else if (!AFF2_FLAGGED(vict, AFF2_SLOW)
            && can_cast_spell(ch, SPELL_SLOW)) {
            cast_spell(ch, vict, NULL, NULL, SPELL_SLOW);
            return;
        } else if (mage_damaging_attack(ch, vict))
            return;
    }
    if (aggression > 5) {
        if (can_cast_spell(ch, SPELL_ASTRAL_SPELL)) {
            cast_spell(ch, vict, NULL, NULL, SPELL_ASTRAL_SPELL);
            return;
        } else if (can_cast_spell(ch, SPELL_TELEPORT)) {
            cast_spell(ch, vict, NULL, NULL, SPELL_TELEPORT);
            return;
        } else if (can_cast_spell(ch, SPELL_LOCAL_TELEPORT)) {
            cast_spell(ch, vict, NULL, NULL, SPELL_LOCAL_TELEPORT);
            return;
        }
    }
    // desperation - just attack full force, as hard as possible
    if (mage_damaging_attack(ch, vict))
        return;
    else if (can_cast_spell(ch, SKILL_PUNCH))
        perform_offensive_skill(ch, vict, SKILL_PUNCH);
    else
        hit(ch, vict, TYPE_UNDEFINED);
}