示例#1
1
double
drand48()
{
    return (double)random() / (double)0x7fffffffL; /* 2**31-1 */
}
示例#2
0
文件: daoming.c 项目: heypnus/xkx2001
//Cracked by Roath
// d/emei/npc/daoming.c 道明小师父
// Shan 96/09/24

inherit NPC;

void greeting(object);
void init();

void create()
{
	set_name("道明小师父", ({"daoming", "dao ming"}) );
	set("rank_info/respect", "小师父");
	set("gender", "男性" );
	set("age", 14+random(6));
	set("long",
	  "这是个年龄不大的小师父。他见有人来到,轻轻点头笑了笑。\n");
	set("attitude", "friendly");
        set("shen_type", 1);
        set("class", "bonze");

        set("str", 20);
        set("int", 28);
        set("con", 24);
        set("dex", 20);

        set("max_qi", 150);
        set("max_jing", 100);
        set("neili", 150);
        set("max_neili", 150);
示例#3
0
void rhizome_direct_http_dispatch(rhizome_direct_sync_request *r)
{
  DEBUGF("Dispatch size_high=%lld",r->cursor->size_high);
  rhizome_direct_transport_state_http *state = r->transport_specific_state;

  int sock=socket(AF_INET, SOCK_STREAM, 0);
  if (sock==-1) {
    WHY_perror("socket");    
    goto end;
  } 

  struct hostent *hostent;
  hostent = gethostbyname(state->host);
  if (!hostent) {
    DEBUGF("could not resolve hostname");
    goto end;
  }

  struct sockaddr_in addr;  
  addr.sin_family = AF_INET;     
  addr.sin_port = htons(state->port);   
  addr.sin_addr = *((struct in_addr *)hostent->h_addr);
  bzero(&(addr.sin_zero),8);     

  if (connect(sock,(struct sockaddr *)&addr,sizeof(struct sockaddr)) == -1) {
    WHY_perror("connect");
    close(sock);
    goto end;
  }
 
  char boundary[20];
  char buffer[8192];

  strbuf bb = strbuf_local(boundary, sizeof boundary);
  strbuf_sprintf(bb, "%08lx%08lx", random(), random());
  assert(!strbuf_overrun(bb));
  strbuf content_preamble = strbuf_alloca(200);
  strbuf content_postamble = strbuf_alloca(40);
  strbuf_sprintf(content_preamble,
      "--%s\r\n"
      "Content-Disposition: form-data; name=\"data\"; filename=\"IHAVEs\"\r\n"
      "Content-Type: application/octet-stream\r\n"
      "\r\n",
      boundary
    );
  strbuf_sprintf(content_postamble, "\r\n--%s--\r\n", boundary);
  assert(!strbuf_overrun(content_preamble));
  assert(!strbuf_overrun(content_postamble));
  int content_length = strbuf_len(content_preamble)
		     + r->cursor->buffer_offset_bytes
		     + r->cursor->buffer_used
		     + strbuf_len(content_postamble);
  strbuf request = strbuf_local(buffer, sizeof buffer);
  strbuf_sprintf(request,
      "POST /rhizome/enquiry HTTP/1.0\r\n"
      "Content-Length: %d\r\n"
      "Content-Type: multipart/form-data; boundary=%s\r\n"
      "\r\n%s",
      content_length, boundary, strbuf_str(content_preamble)
    );
  assert(!strbuf_overrun(request));

  /* TODO: Refactor this code so that it uses our asynchronous framework.
   */
  int len = strbuf_len(request);
  int sent=0;
  while(sent<len) {
    DEBUGF("write(%d, %s, %d)", sock, alloca_toprint(-1, &buffer[sent], len-sent), len-sent);
    int count=write(sock,&buffer[sent],len-sent);
    if (count == -1) {
      if (errno==EPIPE) goto rx;
      WHYF_perror("write(%d)", len - sent);
      close(sock);
      goto end;
    }
    sent+=count;
  }

  len=r->cursor->buffer_offset_bytes+r->cursor->buffer_used;
  sent=0;
  while(sent<len) {
    int count=write(sock,&r->cursor->buffer[sent],len-sent);
    if (count == -1) {
      if (errno == EPIPE)
	goto rx;
      WHYF_perror("write(%d)", count);
      close(sock);
      goto end;
    }
    sent+=count;
  }

  strbuf_reset(request);
  strbuf_puts(request, strbuf_str(content_postamble));
  len = strbuf_len(request);
  sent=0;
  while(sent<len) {
    DEBUGF("write(%d, %s, %d)", sock, alloca_toprint(-1, &buffer[sent], len-sent), len-sent);
    int count=write(sock,&buffer[sent],len-sent);
    if (count == -1) {
      if (errno==EPIPE) goto rx;
      WHYF_perror("write(%d)", len - sent);
      close(sock);
      goto end;
    }
    sent+=count;
  }

  struct http_response_parts parts;
 rx:
  /* request sent, now get response back. */
  if (receive_http_response(sock, buffer, sizeof buffer, &parts) == -1) {
    close(sock);
    goto end;
  }

  /* For some reason the response data gets overwritten during a push,
     so we need to copy it, and use the copy instead. */
  unsigned char *actionlist=alloca(parts.content_length);
  bcopy(parts.content_start, actionlist, parts.content_length);
  dump("response", actionlist, parts.content_length);

  /* We now have the list of (1+RHIZOME_BAR_PREFIX_BYTES)-byte records that indicate
     the list of BAR prefixes that differ between the two nodes.  We can now action
     those which are relevant, i.e., based on whether we are pushing, pulling or 
     synchronising (both).

     I am currently undecided as to whether it is cleaner to have some general
     rhizome direct function for doing that, or whether it just adds unnecessary
     complication, and the responses should just be handled in here.

     For now, I am just going to implement it in here, and we can generalise later.
  */
  int i;
  for(i=10;i<content_length;i+=(1+RHIZOME_BAR_PREFIX_BYTES))
    {
      int type=actionlist[i];
      unsigned long long 
	bid_prefix_ll=rhizome_bar_bidprefix_ll((unsigned char *)&actionlist[i+1]);
      DEBUGF("%s %016llx* @ 0x%x",type==1?"push":"pull",bid_prefix_ll,i);
      if (type==2&&r->pullP) {
	/* Need to fetch manifest.  Once we have the manifest, then we can
	   use our normal bundle fetch routines from rhizome_fetch.c	 

	   Generate a request like: GET /rhizome/manifestbybar/<hex of bar>
	   and add it to our list of HTTP fetch requests, then watch
	   until the request is finished.  That will give us the manifest.
	   Then as noted above, we can use that to pull the file down using
	   existing routines.
	*/
	if (!rhizome_fetch_request_manifest_by_prefix
	    (&addr,&actionlist[i+1],RHIZOME_BAR_PREFIX_BYTES,
	     1 /* import, getting file if needed */))
	  {
	    /* Fetching the manifest, and then using it to see if we want to 
	       fetch the file for import is all handled asynchronously, so just
	       wait for it to finish. */
	    while(rhizome_file_fetch_queue_count) fd_poll();
	  }
	
      } else if (type==1&&r->pushP) {
	/* Form up the POST request to submit the appropriate bundle. */

	/* Start by getting the manifest, which is the main thing we need, and also
	   gives us the information we need for sending any associated file. */
	rhizome_manifest 
	  *m=rhizome_direct_get_manifest(&actionlist[i+1],
					 RHIZOME_BAR_PREFIX_BYTES);
	if (!m) {
	  WHY("This should never happen.  The manifest exists, but when I went looking for it, it doesn't appear to be there.");
	  goto next_item;
	}

	/* Get filehash and size from manifest if present */
	const char *id = rhizome_manifest_get(m, "id", NULL, 0);
	DEBUGF("bundle id = '%s'",id);
	const char *hash = rhizome_manifest_get(m, "filehash", NULL, 0);
	DEBUGF("bundle file hash = '%s'",hash);
	long long filesize = rhizome_manifest_get_ll(m, "filesize");
	DEBUGF("file size = %lld",filesize);

	/* We now have everything we need to compose the POST request and send it.
	 */
	char *template="POST /rhizome/import HTTP/1.0\r\n"
示例#4
0
int radius_msg_add_mppe_keys(struct radius_msg *msg,
			     const u8 *req_authenticator,
			     const u8 *secret, size_t secret_len,
			     const u8 *send_key, size_t send_key_len,
			     const u8 *recv_key, size_t recv_key_len)
{
	struct radius_attr_hdr *attr;
	u32 vendor_id = htonl(RADIUS_VENDOR_ID_MICROSOFT);
	u8 *buf;
	struct radius_attr_vendor *vhdr;
	u8 *pos;
	size_t elen;
	int hlen;
	u16 salt;

	hlen = sizeof(vendor_id) + sizeof(*vhdr) + 2;

	/* MS-MPPE-Send-Key */
	buf = malloc(hlen + send_key_len + 16);
	if (buf == NULL) {
		return 0;
	}
	pos = buf;
	memcpy(pos, &vendor_id, sizeof(vendor_id));
	pos += sizeof(vendor_id);
	vhdr = (struct radius_attr_vendor *) pos;
	vhdr->vendor_type = RADIUS_VENDOR_ATTR_MS_MPPE_SEND_KEY;
	pos = (u8 *) (vhdr + 1);
	salt = random() | 0x8000;
	*pos++ = salt >> 8;
	*pos++ = salt;
	encrypt_ms_key(send_key, send_key_len, salt, req_authenticator, secret,
		       secret_len, pos, &elen);
	vhdr->vendor_length = hlen + elen - sizeof(vendor_id);

	attr = radius_msg_add_attr(msg, RADIUS_ATTR_VENDOR_SPECIFIC,
				   buf, hlen + elen);
	free(buf);
	if (attr == NULL) {
		return 0;
	}

	/* MS-MPPE-Recv-Key */
	buf = malloc(hlen + send_key_len + 16);
	if (buf == NULL) {
		return 0;
	}
	pos = buf;
	memcpy(pos, &vendor_id, sizeof(vendor_id));
	pos += sizeof(vendor_id);
	vhdr = (struct radius_attr_vendor *) pos;
	vhdr->vendor_type = RADIUS_VENDOR_ATTR_MS_MPPE_RECV_KEY;
	pos = (u8 *) (vhdr + 1);
	salt ^= 1;
	*pos++ = salt >> 8;
	*pos++ = salt;
	encrypt_ms_key(recv_key, recv_key_len, salt, req_authenticator, secret,
		       secret_len, pos, &elen);
	vhdr->vendor_length = hlen + elen - sizeof(vendor_id);

	attr = radius_msg_add_attr(msg, RADIUS_ATTR_VENDOR_SPECIFIC,
				   buf, hlen + elen);
	free(buf);
	if (attr == NULL) {
		return 0;
	}

	return 1;
}
示例#5
0
文件: longzi.c 项目: huangleon/fy2005
#include <ansi.h>

inherit NPC;

void create()
{
        set_name("张聋子", ({ "zhang longzi", "zhang","longzi" }) );
        set("long","一个手艺高超的补鞋皮匠。\n");
        set("attitude", "heroism");
        set("title", "老皮匠");

        set("combat_exp", 220000);

        set_skill("unarmed", 70+random(100));
        set_skill("sword", 70+random(100));
        set_skill("parry", 70+random(100));
        set_skill("dodge", 70+random(100));
        set_skill("dagger", 150);
        set_skill("move", 100+random(100));

        set_temp("apply/attack", 70);
        set_temp("apply/dodge", 70);
        set_temp("apply/damage", 30);
        
        set("chat_chance", 1);
        set("chat_msg", ({
        	"张聋子耷拉着脑袋,喃喃自语:臭小马,死哪里去了!\n",
        }) );
        setup();
        carry_object("/obj/armor/cloth")->wear();
        carry_object(__DIR__"obj/skinblade")->wield();
示例#6
0
文件: migd.c 项目: npe9/sprite
void
Migd_GatherLoad()
{
    int oldAllow;
    int	oldInput;
    int	oldForeign;
    static int iteration = 0;
    int numWritten;
    int error;
    int status;
    
    
    oldAllow = curVecPtr->allowMigration;
    oldInput = curVecPtr->noInput;
    oldForeign = curVecPtr->foreignProcs;
    if (migd_Debug > 2) {
	fprintf(stderr, "Migd_GatherLoad - time %d, oldAllow %d, oldInput %d\n",
	       time((int *) NULL), oldAllow, oldInput);
    }
    GetStats(curVecPtr->lengths, &curVecPtr->noInput,
	     &curVecPtr->foreignProcs);
    curVecPtr->timestamp = time((time_t *)0);
    ExamineLoads(curVecPtr);

    if ((oldInput > migd_Parms.noInput) &&
	(curVecPtr->noInput < migd_Parms.noInput) &&
	!ignoreInput && !migd_NeverEvict && !refuseMigration) {
	Migd_Evict(TRUE);
    }

    /*
     * Send the new load vector to the global daemon periodically,
     * or if our migration status changes, or if the number of
     * foreign processes goes from zero to non-zero or vice-versa.
     * This way the global daemon can track things like the last use
     * of a machine by a process that won't release the host when it
     * finishes.
     */
    if (iteration == 0 || (oldAllow != curVecPtr->allowMigration) ||
	(oldForeign > 0 && curVecPtr->foreignProcs == 0) ||
	(oldForeign == 0 && curVecPtr->foreignProcs > 0)) {
	if (migd_Debug > 2) {
	    fprintf(stderr,
		   "Notifying global server, iteration %d, oldAllow %d, newAllow %d, oldForeign %d, newForeign %d.\n",
		   iteration, oldAllow, curVecPtr->allowMigration,
		   oldForeign, curVecPtr->foreignProcs);
	}
	iteration = 0;

	/*
	 * Get the kernel's variable determining whether to refuse
	 * migrations.  We keep rechecking periodically in case it changes.
	 */

	status = Sys_Stats(SYS_PROC_MIGRATION, SYS_PROC_MIG_GET_STATE,
			   (Address) &migd_Parms.criteria);
	if (status != SUCCESS) {
	    SYSLOG1(LOG_ERR, "Error in Sys_Stats getting migration state: %s.\n",
		    Stat_GetMsg(status));
	    exit(Compat_MapCode(status));
	}
	ParseMigStatus();

	if (curVecPtr->lengths[1] >= 1.0)  {
	    struct timeval tv;
	    struct timeval curTime;
	    
	    /*
	     * The 5-minute load average is over 1.  This could
	     * happen if there is a long-running process but it
	     * also seems to happen without anything running.
	     * Sleep a short period of time to try to
	     * keep from being in lock-step with someone else.  There's
	     * nothing too magical about the number except that it's
	     * intended to be something that other processes are unlikely
	     * to sleep for.  
	     */
	    tv.tv_sec = 0;
	    tv.tv_usec = ((random() % 999) + 1) * 1000;
;
	    if (migd_Debug > 2) {
		if (gettimeofday(&curTime,
				 (struct timezone *) NULL) < 0) {
		    perror("Error in gettimeofday");
		    exit(1);
		}
		fprintf(stderr,
			"Sleeping %d usec to avoid lock step, time %d.%d.\n",
			tv.tv_usec, curTime.tv_sec, curTime.tv_usec);
	    }
	    if (select(0, (int *) NULL, (int *) NULL, (int *) NULL,
			  &tv) < 0) {
		if (migd_Debug > 2) {
		    perror("select");
		}
	    }
	    if (migd_Debug > 2) {
		if (gettimeofday(&curTime,
				 (struct timezone *) NULL) < 0) {
		    perror("Error in gettimeofday");
		    exit(1);
		}
		fprintf(stderr, "Time is now %d.%d.\n", curTime.tv_sec,
			curTime.tv_usec);
	    }
	}
	if (migd_Debug > 3) {
	    fprintf(stderr, "Writing vector to global daemon.\n");
	}

	/*
	 * OK, here's the tricky part.  We don't want our write to wait
	 * indefinitely, so we set an alarm.  But just waking up won't
	 * cause Fs_Write to return an error, so we have to longjmp.
	 * So we set the signal handler, set the timer, and setjmp, then
	 * after the write we reverse the process.
	 */
	if (setjmp(writejmp)) {
	    numWritten = -1;
	    errno = EIO;
	} else {
	    if ((int) signal(SIGALRM, WriteAlarm) < 0) {
		syslog(LOG_ERR, "Error setting signal handler: %s.\n",
		       strerror(errno));
		exit(1);
	    }
	    if (setitimer(ITIMER_REAL, &timeOutTimer,
			  (struct itimerval *) NULL) == -1) {
		syslog(LOG_ERR, "Error setting interval timer: %s.\n",
		       strerror(errno));
		exit(1);
	    }
	    numWritten = write(migdGlobalDesc, (char *) curVecPtr,
			       sizeof(Mig_LoadVector));
	}
	error = errno;
	if (setitimer(ITIMER_REAL, &noTimer,
		      (struct itimerval *) NULL) == -1) {
	    syslog(LOG_ERR, "Error disabling interval timer: %s.\n",
		   strerror(errno));
	    exit(1);
	}
	(void) signal(SIGALRM, SIG_IGN);
	errno = error;

	/*
	 * Now we're back to where we would be if all we'd done was
	 * write(), with errno and numWritten set to appropriate values.
	 */

	if (migd_Debug > 3) {
	    fprintf(stderr, "Write returned value %d.\n", numWritten);
	}
	if (numWritten < 0) {
	    if (migd_Debug > 0) {
		fprintf(stderr, "Error %d writing to global daemon: %s.\n",
		       error, strerror(error));
	    }
	    close(migdGlobalDesc);
	    if (migd_Quit || ContactGlobal() < 0) {
		fprintf(stderr, "Exiting.\n");
		exit(1);
	    }
	} else if (numWritten != sizeof(Mig_LoadVector)) {
	    SYSLOG2(LOG_WARNING, "short write to global daemon of %d/%d bytes.\n",
		   numWritten, sizeof(Mig_LoadVector));
	}
	iteration = 0;

	/*
	 * Check on currentInfo.state in case we have to reconnect to the
	 * global daemon or a user process reads the Mig_Info struct from
	 * us.
	 */
	if (curVecPtr->allowMigration &&
	    currentInfo.state == MIG_HOST_ACTIVE) {
	    currentInfo.state = MIG_HOST_IDLE;
	} else if (!curVecPtr->allowMigration &&
		   currentInfo.state == MIG_HOST_IDLE) {
	    currentInfo.state = refuseMigration ?
		MIG_HOST_REFUSES : MIG_HOST_ACTIVE;
	}

	if (CheckMessages() >= 0) {
	    if (migd_Debug > 0) {
		fprintf(stderr,
			"This host is being reclaimed by order of global migration daemon.\n");
	    }
	    Migd_Evict(FALSE);
	}

    }

    iteration = (iteration + 1) % writeRate;
}
示例#7
0
int perform(object me, object target)
{
        string msg,temp,temp1;
        int extra,num,num1;
        int myexp,yourexp, exp_bonus,cond;
        object weapon,shadow,hisweapon,newweapon;
        
        extra = me->query_skill("xinyue-dagger",1);
        exp_bonus = (me->query("combat_exp")-3000000)/3000*extra/1000;
        if (exp_bonus> extra) exp_bonus=extra;
        
        if(me->query("class")!="wolfmount")
        return notify_fail("只有狼山弟子才能使出「斗转星移」的绝技。\n");
        
        if ( extra < 106) return notify_fail("你的[新月斩]还不够纯熟!\n");
        if( !target ) target = offensive_target(me);
        if( !target
        ||      !target->is_character()
        ||      !me->is_fighting(target) )
                return notify_fail("[斗转星移]只能对战斗中的对手使用。\n");
        weapon = me->query_temp("weapon");
        myexp=me->query("combat_exp");
        yourexp=target->query("combat_exp");
        
        msg = HIR "$N一声长啸:"NOR+"      "+HIC"斗"NOR+"      "+HIY"转"NOR+
        "      "+HIW"星"NOR+"      "+HIB"移"NOR+"\n"; 
        message_vision(msg,me);
        
        if ((myexp*3/4+random(myexp*4)>yourexp)&& !target->query_temp("is_unconcious")) {
                
                msg= MAG"\n$N仿佛置身于一个极大的漩涡中,攻出的招式竟然反击回来!\n\n"NOR;
                message_vision(msg,target);
                        
                seteuid(getuid());
           if (!userp(target)) {
                        sscanf(file_name(target),"%s#%d",temp,num);
                        shadow=new(temp);
                        
                        }
                else    {
                        shadow=new("/d/fy/npc/shadefigure");
                        shadow->changeshape(target);            
                        if(hisweapon=target->query_temp("weapon"))      {
                                sscanf(file_name(hisweapon),"%s#%d",temp1,num1);
                                newweapon=new(temp1);
                                newweapon->move(shadow);
                                newweapon->wield();
                        }
                }       
                shadow->set("owner",me);
                shadow->set("possessed",me);
                shadow->move(environment(me));
                if (!target->query_temp("weapon"))
                if (newweapon=shadow->query_temp("weapon"))
                        newweapon->unequip();   
                shadow->add_killer(target->query("id"));
                
                
                simulate_set(target,shadow);
                shadow->add_temp("apply/attack", extra/2);
                message_vision(HIC "    斗\n" NOR,me);
                COMBAT_D->do_attack(shadow,target,msg);
                if (target->query_temp("damaged_during_attack"))
                                        target->set_temp("last_damage_from",me);
                
                message_vision(YEL "            转\n" NOR,me);
                simulate_set(target,shadow);
                COMBAT_D->do_attack(shadow,target,msg);
                if (target->query_temp("damaged_during_attack"))
                                        target->set_temp("last_damage_from",me);
                
                message_vision(HIW "                    星\n" NOR,me);
                simulate_set(target,shadow);
                COMBAT_D->do_attack(shadow,target,msg);
           if (target->query_temp("damaged_during_attack"))
                                        target->set_temp("last_damage_from",me);
                
                message_vision(HIB "                              移\n" NOR,me);
                simulate_set(target,shadow);
                COMBAT_D->do_attack(shadow,target,msg);
                if (target->query_temp("damaged_during_attack"))
                                        target->set_temp("last_damage_from",me);
                
                shadow->add_temp("apply/attack", -extra/2);
                if (me->is_killing(target->query("id"))) cond=1;
                destruct(shadow);
        }
示例#8
0
/*QUAKED monster_mytank_commander (1 .5 0) (-32 -32 -16) (32 32 72) Ambush Trigger_Spawn Sight
*/
void init_drone_tank (edict_t *self)
{
//	if (deathmatch->value)
//	{
//		G_FreeEdict (self);
//		return;
//	}

	self->s.modelindex = gi.modelindex ("models/monsters/tank/tris.md2");
	VectorSet (self->mins, -24, -24, -16);
	VectorSet (self->maxs, 24, 24, 64);
	self->movetype = MOVETYPE_STEP;
	self->solid = SOLID_BBOX;

	sound_pain = gi.soundindex ("tank/tnkpain2.wav");
	sound_thud = gi.soundindex ("tank/tnkdeth2.wav");
	sound_idle = gi.soundindex ("tank/tnkidle1.wav");
	sound_die = gi.soundindex ("tank/death.wav");
	sound_step = gi.soundindex ("tank/step.wav");
	sound_windup = gi.soundindex ("tank/tnkatck4.wav");
	sound_strike = gi.soundindex ("tank/tnkatck5.wav");
	sound_sight = gi.soundindex ("tank/sight1.wav");

	gi.soundindex ("tank/tnkatck1.wav");
	gi.soundindex ("tank/tnkatk2a.wav");
	gi.soundindex ("tank/tnkatk2b.wav");
	gi.soundindex ("tank/tnkatk2c.wav");
	gi.soundindex ("tank/tnkatk2d.wav");
	gi.soundindex ("tank/tnkatk2e.wav");
	gi.soundindex ("tank/tnkatck3.wav");

//	if (self->activator && self->activator->client)
	self->health = 100 + 65*self->monsterinfo.level;
	//else self->health = 100 + 65*self->monsterinfo.level;

	self->max_health = self->health;
	self->gib_health = -200;

	//if (self->activator && self->activator->client)
	self->monsterinfo.power_armor_power = 200 + 105*self->monsterinfo.level;
	//else self->monsterinfo.power_armor_power = 200 + 105*self->monsterinfo.level;

	self->monsterinfo.power_armor_type = POWER_ARMOR_SHIELD;
	self->monsterinfo.max_armor = self->monsterinfo.power_armor_power;

	self->monsterinfo.control_cost = M_TANK_CONTROL_COST;
	self->monsterinfo.cost = M_TANK_COST;
	self->mtype = M_TANK;
	
	if (random() > 0.5)
		self->item = FindItemByClassname("ammo_bullets");
	else
		self->item = FindItemByClassname("ammo_rockets");

	self->mass = 500;

	//self->pain = mytank_pain;
	self->die = mytank_die;
	//self->touch = mytank_touch;
	self->monsterinfo.stand = mytank_stand;
	self->monsterinfo.walk = tank_walk;
	self->monsterinfo.run = mytank_run;
	self->monsterinfo.dodge = NULL;
	self->monsterinfo.attack = mytank_attack;
	self->monsterinfo.melee = mytank_melee;
	self->monsterinfo.sight = mytank_sight;
	self->monsterinfo.idle = mytank_idle;
	self->monsterinfo.jumpup = 64;
	self->monsterinfo.jumpdn = 512;
	self->monsterinfo.aiflags |= AI_NO_CIRCLE_STRAFE;
	//self->monsterinfo.melee = 1;

	gi.linkentity (self);
	
	self->monsterinfo.currentmove = &mytank_move_stand;
	self->monsterinfo.scale = MODEL_SCALE;

//	walkmonster_start(self);
	self->nextthink = level.time + FRAMETIME;

//	self->activator->num_monsters += self->monsterinfo.control_cost;
}
示例#9
0
文件: genu.c 项目: gongfuPanada/xyj45
  set("str", 10);
  set("max_kee", 100);
  set("max_gin", 100);
  set("force", 100);
  set("max_force", 100);
  set("force_factor", 4);
  set_skill("unarmed", 10);
  set_skill("parry", 10);
  set_skill("dodge", 10);
  set_skill("blade", 10);
  set("chat_chance", 25);
  set("chat_msg", ({ (: random_move :) }));

  setup();

  carry_object("/d/obj/cloth/skirt")->wear();
}

int random_move ()
{
  object me = this_object();
  string *strs = ({
    "$N迷人一笑。\n",
    "$N张开樱桃小口轻唱起来。\n",
    "$N面颊桃红,唱着曲儿。\n",
  });

  message_vision (strs[random(sizeof(strs))],me);
  return 1;
}
示例#10
0
/*
==================
player_die
==================
*/
void player_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath ) {
	gentity_t   *ent;
	int anim;
	int contents = 0;
	int killer;
	int i;
	char        *killerName, *obit;
	qboolean nogib = qtrue;
	gitem_t     *item = NULL; // JPW NERVE for flag drop
	vec3_t launchvel;      // JPW NERVE
	gentity_t   *flag; // JPW NERVE

	if ( self->client->ps.pm_type == PM_DEAD ) {
		return;
	}

	if ( level.intermissiontime ) {
		return;
	}

//----(SA) commented out as we have no hook
//	if (self->client && self->client->hook)
//		Weapon_HookFree(self->client->hook);

	self->client->ps.pm_type = PM_DEAD;

	if ( attacker ) {
		killer = attacker->s.number;
		if ( attacker->client ) {
			killerName = attacker->client->pers.netname;
		} else {
			killerName = "<non-client>";
		}
	} else {
		killer = ENTITYNUM_WORLD;
		killerName = "<world>";
	}

	if ( killer < 0 || killer >= MAX_CLIENTS ) {
		killer = ENTITYNUM_WORLD;
		killerName = "<world>";
	}

	if ( meansOfDeath < 0 || meansOfDeath >= sizeof( modNames ) / sizeof( modNames[0] ) ) {
		obit = "<bad obituary>";
	} else {
		obit = modNames[ meansOfDeath ];
	}

	G_LogPrintf( "Kill: %i %i %i: %s killed %s by %s\n",
				 killer, self->s.number, meansOfDeath, killerName,
				 self->client->pers.netname, obit );

	// broadcast the death event to everyone
	ent = G_TempEntity( self->r.currentOrigin, EV_OBITUARY );
	ent->s.eventParm = meansOfDeath;
	ent->s.otherEntityNum = self->s.number;
	ent->s.otherEntityNum2 = killer;
	ent->r.svFlags = SVF_BROADCAST; // send to everyone

	self->enemy = attacker;

	self->client->ps.persistant[PERS_KILLED]++;

	if ( attacker && attacker->client ) {
		if ( attacker == self || OnSameTeam( self, attacker ) ) {
			AddScore( attacker, -1 );
		} else {
			AddScore( attacker, 1 );

			// Ridah, not in single player
			if ( g_gametype.integer != GT_SINGLE_PLAYER ) {
				// done.
				if ( meansOfDeath == MOD_GAUNTLET ) {
					attacker->client->ps.persistant[PERS_GAUNTLET_FRAG_COUNT]++;
					attacker->client->ps.persistant[PERS_REWARD] = REWARD_GAUNTLET;
					attacker->client->ps.persistant[PERS_REWARD_COUNT]++;

					// add the sprite over the player's head
//					attacker->client->ps.eFlags &= ~(EF_AWARD_IMPRESSIVE | EF_AWARD_EXCELLENT /*| EF_AWARD_GAUNTLET*/ );
					//attacker->client->ps.eFlags |= EF_AWARD_GAUNTLET;
					attacker->client->rewardTime = level.time + REWARD_SPRITE_TIME;

					// also play humiliation on target
					self->client->ps.persistant[PERS_REWARD] = REWARD_GAUNTLET;
					self->client->ps.persistant[PERS_REWARD_COUNT]++;
				}

				// check for two kills in a short amount of time
				// if this is close enough to the last kill, give a reward sound
				if ( level.time - attacker->client->lastKillTime < CARNAGE_REWARD_TIME ) {
					attacker->client->ps.persistant[PERS_REWARD_COUNT]++;
					attacker->client->ps.persistant[PERS_REWARD] = REWARD_EXCELLENT;
					attacker->client->ps.persistant[PERS_EXCELLENT_COUNT]++;

					// add the sprite over the player's head
//					attacker->client->ps.eFlags &= ~(EF_AWARD_IMPRESSIVE | EF_AWARD_EXCELLENT /*| EF_AWARD_GAUNTLET*/ );
//					attacker->client->ps.eFlags |= EF_AWARD_EXCELLENT;
					attacker->client->rewardTime = level.time + REWARD_SPRITE_TIME;
				}
				// Ridah
			}
			// done.
			attacker->client->lastKillTime = level.time;
		}
	} else {
		AddScore( self, -1 );
	}

	// Add team bonuses
	Team_FragBonuses( self, inflictor, attacker );

	// if client is in a nodrop area, don't drop anything
// JPW NERVE new drop behavior
	if ( g_gametype.integer == GT_SINGLE_PLAYER ) {   // only drop here in single player; in multiplayer, drop @ limbo
		contents = trap_PointContents( self->r.currentOrigin, -1 );
		if ( !( contents & CONTENTS_NODROP ) ) {
			TossClientItems( self );
		}
	}

	// drop flag regardless
	if ( g_gametype.integer != GT_SINGLE_PLAYER ) {
		if ( self->client->ps.powerups[PW_REDFLAG] ) {
			item = BG_FindItem( "Red Flag" );
		}
		if ( self->client->ps.powerups[PW_BLUEFLAG] ) {
			item = BG_FindItem( "Blue Flag" );
		}
		launchvel[0] = crandom() * 20;
		launchvel[1] = crandom() * 20;
		launchvel[2] = 10 + random() * 10;
		if ( item ) {
			flag = LaunchItem( item,self->r.currentOrigin,launchvel );
			flag->s.modelindex2 = self->s.otherEntityNum2; // JPW NERVE FIXME set player->otherentitynum2 with old modelindex2 from flag and restore here
		}
	}
// jpw

	Cmd_Score_f( self );        // show scores
	// send updated scores to any clients that are following this one,
	// or they would get stale scoreboards
	for ( i = 0 ; i < level.maxclients ; i++ ) {
		gclient_t   *client;

		client = &level.clients[i];
		if ( client->pers.connected != CON_CONNECTED ) {
			continue;
		}
		if ( client->sess.sessionTeam != TEAM_SPECTATOR ) {
			continue;
		}
		if ( client->sess.spectatorClient == self->s.number ) {
			Cmd_Score_f( g_entities + i );
		}
	}

	self->takedamage = qtrue;   // can still be gibbed

	self->s.powerups = 0;
// JPW NERVE -- only corpse in SP; in MP, need CONTENTS_BODY so medic can operate
	if ( g_gametype.integer == GT_SINGLE_PLAYER ) {
		self->r.contents = CONTENTS_CORPSE;
		self->s.weapon = WP_NONE;
	} else {
		self->client->limboDropWeapon = self->s.weapon; // store this so it can be dropped in limbo
	}
// jpw
	self->s.angles[0] = 0;
	self->s.angles[2] = 0;
	LookAtKiller( self, inflictor, attacker );

	VectorCopy( self->s.angles, self->client->ps.viewangles );

	self->s.loopSound = 0;

	self->r.maxs[2] = -8;

	// don't allow respawn until the death anim is done
	// g_forcerespawn may force spawning at some later time
	self->client->respawnTime = level.time + 1700;

	// remove powerups
	memset( self->client->ps.powerups, 0, sizeof( self->client->ps.powerups ) );

	if ( g_gametype.integer == GT_SINGLE_PLAYER ) {
		trap_SendServerCommand( -1, "mu_play sound/music/l_failed_1.wav 0\n" );
		trap_SetConfigstring( CS_MUSIC_QUEUE, "" );  // clear queue so it'll be quiet after hit
		trap_SendServerCommand( -1, "cp missionfail0" );
	}


	// never gib in a nodrop
	if ( self->health <= GIB_HEALTH && !( contents & CONTENTS_NODROP ) && g_blood.integer ) {
//		if(self->client->ps.eFlags & EF_HEADSHOT)
//		{
//			GibHead(self, killer);
//		}
//		else	// gib death
//		{
		GibEntity( self, killer );
		nogib = qfalse;
//		}
	}

	if ( nogib ) {
		// normal death
		static int i;

		switch ( i ) {
		case 0:
			anim = BOTH_DEATH1;
			break;
		case 1:
			anim = BOTH_DEATH2;
			break;
		case 2:
		default:
			anim = BOTH_DEATH3;
			break;
		}

		// for the no-blood option, we need to prevent the health
		// from going to gib level
		if ( self->health <= GIB_HEALTH ) {
			self->health = GIB_HEALTH + 1;
		}

// JPW NERVE for medic
		self->client->medicHealAmt = 0;
// jpw

		self->client->ps.legsAnim =
			( ( self->client->ps.legsAnim & ANIM_TOGGLEBIT ) ^ ANIM_TOGGLEBIT ) | anim;
		self->client->ps.torsoAnim =
			( ( self->client->ps.torsoAnim & ANIM_TOGGLEBIT ) ^ ANIM_TOGGLEBIT ) | anim;

		G_AddEvent( self, EV_DEATH1 + 1, killer );

		// the body can still be gibbed
		self->die = body_die;

		// globally cycle through the different death animations
		i = ( i + 1 ) % 3;
	}

	trap_LinkEntity( self );

	if ( g_gametype.integer == GT_SINGLE_PLAYER ) {
		AICast_ScriptEvent( AICast_GetCastState( self->s.number ), "death", "" );
	}
}
示例#11
0
/*
==============
G_ArmorDamage
	brokeparts is how many should be broken off now
	curbroke is how many are broken
	the difference is how many to pop off this time
==============
*/
void G_ArmorDamage( gentity_t *targ ) {
	int brokeparts, curbroke;
	int numParts;
	int dmgbits = 16;   // 32/2;
	int i;

	if ( !targ->client ) {
		return;
	}

	if ( targ->s.aiChar == AICHAR_PROTOSOLDIER ) {
		numParts = 9;
	} else if ( targ->s.aiChar == AICHAR_SUPERSOLDIER ) {
		numParts = 14;
	} else if ( targ->s.aiChar == AICHAR_HEINRICH ) {
		numParts = 20;
	} else {
		return;
	}

	if ( numParts > dmgbits ) {
		numParts = dmgbits; // lock this down so it doesn't overwrite any bits that it shouldn't.  TODO: fix this


	}
	// determined here (on server) by location of hit and existing armor, you're updating here so
	// the client knows which pieces are still in place, and by difference with previous state, which
	// pieces to play an effect where the part is blown off.
	// Need to do it here so we have info on where the hit registered (head, torso, legs or if we go with more detail; arm, leg, chest, codpiece, etc)

	// ... Ick, just discovered that the refined hit detection ("hit nearest to which tag") is clientside...

	// For now, I'll randomly pick a part that hasn't been cleared.  This might end up looking okay, and we won't need the refined hits.
	//	however, we still have control on the server-side of which parts come off, regardless of what shceme is used.

	brokeparts = (int)( ( 1 - ( (float)( targ->health ) / (float)( targ->client->ps.stats[STAT_MAX_HEALTH] ) ) ) * numParts );

	// RF, remove flame protection after enough parts gone
	if ( AICast_NoFlameDamage( targ->s.number ) && ( (float)brokeparts / (float)numParts >= 5.0 / 6.0 ) ) { // figure from DM
		AICast_SetFlameDamage( targ->s.number, qfalse );
	}

	if ( brokeparts && ( ( targ->s.dmgFlags & ( ( 1 << numParts ) - 1 ) ) != ( 1 << numParts ) - 1 ) ) {   // there are still parts left to clear

		// how many are removed already?
		curbroke = 0;
		for ( i = 0; i < numParts; i++ ) {
			if ( targ->s.dmgFlags & ( 1 << i ) ) {
				curbroke++;
			}
		}

		// need to remove more
		if ( brokeparts - curbroke >= 1 && curbroke < numParts ) {
			for ( i = 0; i < ( brokeparts - curbroke ); i++ ) {
				int remove = rand() % ( numParts );

				if ( !( ( targ->s.dmgFlags & ( ( 1 << numParts ) - 1 ) ) != ( 1 << numParts ) - 1 ) ) { // no parts are available any more
					break;
				}

				// FIXME: lose the 'while' loop.  Still should be safe though, since the check above verifies that it will eventually find a valid part
				while ( targ->s.dmgFlags & ( 1 << remove ) ) {
					remove = rand() % ( numParts );
				}

				targ->s.dmgFlags |= ( 1 << remove );    // turn off 'undamaged' part
				if ( (int)( random() + 0.5 ) ) {                       // choose one of two possible replacements
					targ->s.dmgFlags |= ( 1 << ( numParts + remove ) );
				}
			}
		}
	}
}
示例#12
0
文件: mtu.c 项目: dormclub/tjphone
int ms_discover_mtu(const char *host){
	int sock;
	int err,mtu=0,new_mtu;
	socklen_t optlen;
	char port[10];
	struct addrinfo hints,*ai=NULL;
	int rand_port;
	int retry=0;
	struct timeval tv;

	memset(&hints,0,sizeof(hints));
	hints.ai_family = PF_INET;
	hints.ai_socktype = SOCK_DGRAM;
	
	gettimeofday(&tv,NULL);	
	srandom(tv.tv_usec);
	rand_port=random() & 0xFFFF;
	if (rand_port<1000) rand_port+=1000;
	snprintf(port,sizeof(port),"%i",rand_port);
	err=getaddrinfo(host,port,&hints,&ai);
	if (err!=0){
		ms_error("getaddrinfo(): %s\n",gai_strerror(err));
		return -1;
	}
	sock=socket(PF_INET,SOCK_DGRAM,0);
	if(sock < 0)
	{
		ms_error("socket(): %s",strerror(errno));
		return sock;
	}
	mtu=IP_PMTUDISC_DO;
	optlen=sizeof(mtu);
	err=setsockopt(sock,IPPROTO_IP,IP_MTU_DISCOVER,&mtu,optlen);
	if (err!=0){
		ms_error("setsockopt(): %s",strerror(errno));
		err = close(sock);
		if (err!=0)
			ms_error("close(): %s", strerror(errno));
		return -1;
	}
	err=connect(sock,ai->ai_addr,ai->ai_addrlen);
	freeaddrinfo(ai);
	if (err!=0){
		ms_error("connect(): %s",strerror(errno));
		err = close(sock);
		if (err !=0)
			ms_error("close(): %s", strerror(errno));
		return -1;
	}
	mtu=1500;
	do{
		int send_returned;
		int datasize=mtu-28;/*minus IP+UDP overhead*/
		char *buf=ms_malloc0(datasize);

		send_returned = send(sock,buf,datasize,0);
		if (send_returned==-1){
			/*ignore*/
		}
		ms_free(buf);
		usleep(500000);/*wait for an icmp message come back */
		err=getsockopt(sock,IPPROTO_IP,IP_MTU,&new_mtu,&optlen);
		if (err!=0){
			ms_error("getsockopt(): %s",strerror(errno));
			err = close(sock);
			if (err!=0)
				ms_error("close(): %s", strerror(errno));
			return -1;
		}else{
			ms_message("Partial MTU discovered : %i",new_mtu);
			if (new_mtu==mtu) break;
			else mtu=new_mtu;
		}
		retry++;
	}while(retry<10);
	
	ms_message("mtu to %s is %i",host,mtu);

	err = close(sock);
	if (err!=0)
		ms_error("close() %s", strerror(errno));
	return mtu;
}
示例#13
0
 bool hasPathSum(TreeNode *root, int sum) {
     if (random()%2){
         return hasPathSum1(root, sum);    
     }
     return hasPathSum2(root, sum);
 }
示例#14
0
文件: GRAPHS.C 项目: rickytan/Snooker
void outchinese(int x0,int y0,char *hz,int color,int size,int speed)		/*******汉字输出*********/
{
	FILE *fp;
	int flag=0;
	register int i,j,x,y;
	char mat[ZIKU*ZIKU/8];
	unsigned char high,low;
	unsigned long position=0;
	unsigned MASK=0x80;

	if ((fp=fopen(".\\source\\hzk16","rb"))==NULL)
	{
		closegraph();
		printf("Error!!!");
		exit(0);
	}
	if (color==EOF) flag=1;

	while(*(hz))
	{
		high=*(hz)-0xa0;
		low=*(hz+1)-0xa0;

		position = ((high-1)*94+(low-1))*(ZIKU*ZIKU/8L);
		fseek(fp, position, SEEK_SET);
		fread(mat,sizeof(char),ZIKU*ZIKU/8,fp);
		y=y0;
		for (i=0;i<10*speed;i++)
			delay(20000);

		if (size==1)
		{
			for(i=0;i<ZIKU;i++)
			{
				x=x0;
				for (j = 0; j < ZIKU; j++)
				{
					if((MASK>>(j%8) & *(mat+ZIKU/8*i+j/8)))
						putpixel(x,y,(color==EOF)?random(16):color);
					x++;
				}
			y++;
			}
		}
		else
		{
			setlinestyle(0,0,1);
			setwritemode(COPY_PUT);

			for(i=0;i<ZIKU;i++)
			{
				x=x0;
				for (j = 0; j < ZIKU; ++j)
				{
					if((MASK>>(j%8) & *(mat+ZIKU/8*i+j/8)))
					{
						if (flag) color=random(16);
						setcolor(color);
						rectangle(x,y,x+size-1,y+size-1);
						setfillstyle(SOLID_FILL,color);
						floodfill(x+1,y+1,color);
					}
					x+=size;
				}
			y+=size;
			}
		}
		hz+=2;

		if (x0+(ZIKU+1)*size>getmaxx()-(ZIKU+1)*size)	/*超出屏幕自动换行*/
		{
			y0+=(ZIKU+1)*size;
			x0=0;
		}
		else
			x0+=(ZIKU+1)*size;
	}
示例#15
0
int read_power(double *voltage, double *current)
{
    *voltage = ((double)random()-RAND_MAX/2)/(RAND_MAX/2)*1+48;
    *current = ((double)random()-RAND_MAX/2)/(RAND_MAX/2)*0.5+1;
    return TRUE;
}
示例#16
0
/*
 * Initialize the TABLESAMPLE Descriptor and the TABLESAMPLE Method.
 */
TableSampleDesc *
tablesample_init(SampleScanState *scanstate, TableSampleClause *tablesample)
{
	FunctionCallInfoData fcinfo;
	int			i;
	List	   *args = tablesample->args;
	ListCell   *arg;
	ExprContext *econtext = scanstate->ss.ps.ps_ExprContext;
	TableSampleDesc	*tsdesc = (TableSampleDesc *) palloc0(sizeof(TableSampleDesc));

	/* Load functions */
	fmgr_info(tablesample->tsminit, &(tsdesc->tsminit));
	fmgr_info(tablesample->tsmnextblock, &(tsdesc->tsmnextblock));
	fmgr_info(tablesample->tsmnexttuple, &(tsdesc->tsmnexttuple));
	if (OidIsValid(tablesample->tsmexaminetuple))
		fmgr_info(tablesample->tsmexaminetuple, &(tsdesc->tsmexaminetuple));
	else
		tsdesc->tsmexaminetuple.fn_oid = InvalidOid;
	fmgr_info(tablesample->tsmreset, &(tsdesc->tsmreset));
	fmgr_info(tablesample->tsmend, &(tsdesc->tsmend));

	InitFunctionCallInfoData(fcinfo, &tsdesc->tsminit,
							 list_length(args) + 2,
							 InvalidOid, NULL, NULL);

	tsdesc->tupDesc = scanstate->ss.ss_ScanTupleSlot->tts_tupleDescriptor;
	tsdesc->heapScan = scanstate->ss.ss_currentScanDesc;

	/* First argument for init function is always TableSampleDesc */
	fcinfo.arg[0] = PointerGetDatum(tsdesc);
	fcinfo.argnull[0] = false;

	/*
	 * Second arg for init function is always REPEATABLE
	 * When tablesample->repeatable is NULL then REPEATABLE clause was not
	 * specified.
	 * When specified, the expression cannot evaluate to NULL.
	 */
	if (tablesample->repeatable)
	{
		ExprState  *argstate = ExecInitExpr((Expr *) tablesample->repeatable,
											(PlanState *) scanstate);
		fcinfo.arg[1] = ExecEvalExpr(argstate, econtext,
									 &fcinfo.argnull[1], NULL);
		if (fcinfo.argnull[1])
			ereport(ERROR,
					(errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
					 errmsg("REPEATABLE clause must be NOT NULL numeric value")));
	}
	else
	{
		fcinfo.arg[1] = UInt32GetDatum(random());
		fcinfo.argnull[1] = false;
	}

	/* Rest of the arguments come from user.  */
	i = 2;
	foreach(arg, args)
	{
		Expr	   *argexpr = (Expr *) lfirst(arg);
		ExprState  *argstate = ExecInitExpr(argexpr, (PlanState *) scanstate);

		if (argstate == NULL)
		{
			fcinfo.argnull[i] = true;
			fcinfo.arg[i] = (Datum) 0;;
		}

		fcinfo.arg[i] = ExecEvalExpr(argstate, econtext,
									 &fcinfo.argnull[i], NULL);
		i++;
	}
示例#17
0
文件: migd.c 项目: npe9/sprite
static int
ContactGlobal()
{
    int sleepTime;
    int status;
    int retries;
    int ioctlRetries;
    int realErrno;
    int success = 0;
    static int firstContact = 1; /* First time we are trying to reach the
				    global daemon? */
    int t;
    
    t = time(0);
    if (migd_Debug > 1) {
	fprintf(stderr, "ContactGlobal - %s\n", ctime(&t));
    }

    /*
     * Set a temporary variable to track firstContact, and reset it so
     * any subsequent calls have the updated value.  This avoids the
     * need to reset it before every return statement.
     */
    if (firstContact) {
	/*
	 * First time we've been called. Set up seed for random
	 * numbers.
	 */
	srandom(getpid());
	firstContact = 0;
    } 

    /*
     * Clean up any old descriptor.
     */
    if (migdGlobalDesc >= 0) {
	Fs_EventHandlerDestroy(migdGlobalDesc);
	(void) close(migdGlobalDesc);
    }
    
    sleepTime = (random() & 07) + 1;
    for (retries = 1;
	 retries <= MAX_GLOBAL_CONTACTS && !migd_Quit && !success;
	 retries++) {
	migdGlobalDesc = open(migd_GlobalPdevName, O_RDWR, 0);
	if (migdGlobalDesc < 0) {
	    if (migd_Debug > 2) {
		fprintf(stderr, "ContactGlobal - sleeping %d seconds\n",
		       sleepTime);
	    }
	    sleep(sleepTime);
	    sleepTime *= 2;
	    migdGlobalDesc = open(migd_GlobalPdevName, O_RDWR, 0);
	}
	if (migdGlobalDesc < 0) {
	    if (migd_Debug > 0) {
		fprintf(stderr,
		       "ContactGlobal: couldn't open %s: %s\n",
		       migd_GlobalPdevName, strerror(errno));
	    }
	    /*
	     * If errno is ENOENT, there is not currently a master, anywhere.
	     * (When the master exits it removes the pdev.)  EIO 
	     * may mean the daemon crashed.  EINVAL may mean the daemon's host
	     * crashed.  We special case EIO due to a race condition
	     * between recovery and starting daemons.
	     */
	    if (errno == ENOENT || errno == EIO || errno == EINVAL) {
		if (retries == MAX_GLOBAL_CONTACTS - 1 && errno != ENOENT) {
		    /*
		     * We're getting desperate here.  We can't open
		     * the file, but we should be able to.  Remove
		     * the pdev and try one last time to create the
		     * master, since it may be that the host running
		     * the master has crashed and the name server
		     * is continually returning a bad status to us.
		     * We risk clobbering someone else who has successfully
		     * opened the pdev just before us, but there's a small
		     * window of vulnerability and by this time we're sleeping
		     * a long time.  
		     */
		    (void) unlink(migd_GlobalPdevName);
		}
		if (!migd_NeverRunGlobal) {
		    if (CreateGlobal() < 0) {
			return(-1);
		    }
		}
		/*
		 * Go to start of for loop, trying to open pdev.
		 */
		continue;
	    } else {
		realErrno = errno;
		fprintf(stderr, "Migd_Init - Unable to contact master of global pdev: %s\n",
		       strerror(errno));
		errno = realErrno;
		return(-1);
	    }
	} else {
	    /*
	     * We've successfully opened the pdev.
	     * Try to tell the global master that we're a daemon.  It may say
	     * DEV_BUSY, which means that there is already a daemon.  In that
	     * case, it tells the other daemon to go away, and we will keep
	     * trying.  In some cases we may get an error doing the ioctl,
	     * such as a stale handle, in which case we close the file and
	     * go to the top again.
	     */
	    for (ioctlRetries = 1; ioctlRetries <= MAX_GLOBAL_CONTACTS;
		 ioctlRetries++) {
		status = Fs_IOControl(migdGlobalDesc, IOC_MIG_DAEMON, sizeof(Mig_Info),
				      (char *) &currentInfo,
				      0, (char *) NULL);
		if (status == DEV_BUSY) {
		    if (migd_Debug > 0) {
			fprintf(stderr, "ContactGlobal - ioctl returned busy.\n");
		    }
		    sleepTime = ((random() & 07) + 1) * ioctlRetries;
		    if (migd_Debug > 2) {
			fprintf(stderr, "ContactGlobal - sleeping %d seconds\n",
			       sleepTime);
		    }
		    sleep(sleepTime);
		} else {
		    /*
		     * An error we can't deal with, or SUCCESS.
		     */
		    break;
		}
	    }
	    if (status != SUCCESS) {
		SYSLOG1(LOG_ERR,
		       "ContactGlobal: warning: error during ioctl to global master: %s\n",
		       Stat_GetMsg(status));
		errno = Compat_MapCode(status);
		close(migdGlobalDesc);
	    } else {
		/*
		 * We did it!  Break out of the inner for loop, and the
		 * success flag will break us out of the outer loop.
		 */
		success = 1;
		break;
	    }
	}
    }
    if (!success) {
	realErrno = errno;
	SYSLOG0(LOG_ERR, "unable to contact master; giving up.\n");
	errno = realErrno;
	return(-1);
    }

#ifdef FAST_SELECT
    Fs_EventHandlerCreate(migdGlobalDesc, FS_READ|FS_EXCEPTION,
			  HandleException, (ClientData) NULL);
#endif /* FAST_SELECT */

    if (migd_Debug > 1) {
	fprintf(stderr, "ContactGlobal - completed successfully\n");
    }

    return (0);
}
示例#18
0
int perform(object me, object target)
{
	string weapon;
	object weapon1;
	int    lvl1, lvl2, amount;

	if( !target ) target = offensive_target(me);

	if( !target
	||	!target->is_character()
	||	!me->is_fighting(target) )
		return notify_fail("剑掌五连环只能对战斗中的对手使用。\n");

	weapon1 = me->query_temp("weapon");
        if( !objectp(weapon1) || weapon1->query("skill_type") != "sword" )
                return notify_fail("你手中无剑,如何使得剑掌五连环?\n");

	if( me->query_skill_mapped("strike") != "hunyuan-zhang" )
		return notify_fail("你所用的并非混元掌,不能与华山剑法配合施展剑掌五连环!\n");

	if( me->query_skill_prepared("strike") != "hunyuan-zhang" )
                return notify_fail("你所备的并非混元掌,不能与华山剑法配合施展剑掌五连环!\n");

	if( me->query_skill_mapped("force") != "zixia-gong" )
		return notify_fail("你所用的并非紫霞功,无法施展剑掌五连环!\n");

	if( me->query_skill("zixia-gong", 1) < 60 )
		return notify_fail("你的紫霞功火候未到,无法施展剑掌五连环!\n");

	if( (lvl1=me->query_skill("strike")) < 100 )
		return notify_fail("剑掌五连环需要精湛的混元掌配合,方能有效施展!\n");

	if( (lvl2=me->query_skill("sword")) < 100 )
		return notify_fail("你华山剑法修为不足,还不会使用剑掌五连环!\n");

	amount = (lvl1+lvl2) / 15;

	if ( amount < 40 ) amount = 40;
	if ( amount > 80 ) amount = 80;

	if( me->query("neili") <= amount*4 )
		return notify_fail("你的内力不够使用剑掌五连环!\n");
	if( me->query("jingli") <= amount*2 )
		return notify_fail("你的精力不够使用剑掌五连环!\n");

	if( me->query_skill_prepared("cuff") == "pishi-poyu" ) {
		me->set_temp("restore", 1);
		me->prepare_skill("cuff");
	}

	weapon = me->query_temp("weapon");

	me->add_temp("apply/damage", amount);
	me->add_temp("apply/attack", amount*2);
	me->add_temp("apply/dodge", amount*2);

	message_vision(HIR "\n突然间$N身形电闪,瞬间逼近$n,剑掌交替中向$n奋力击出三剑两掌!\n\n" NOR, me, target);

	COMBAT_D->do_attack(me, target, me->query_temp("weapon"));
	weapon->unequip();
	COMBAT_D->do_attack(me, target, me->query_temp("weapon"));
	weapon->wield();
	COMBAT_D->do_attack(me, target, me->query_temp("weapon"));
	weapon->unequip();
	COMBAT_D->do_attack(me, target, me->query_temp("weapon"));
	weapon->wield();
	COMBAT_D->do_attack(me, target, me->query_temp("weapon"));

	me->start_busy(1+random(3));
	me->add_temp("apply/damage", -amount);
	me->add_temp("apply/attack", -amount*2);
	me->add_temp("apply/dodge", -amount*2);
	me->add("neili", -amount*3);
	me->add("jingli", -amount*2);
	if( me->query_temp("restore") ) me->prepare_skill("cuff", "pishi-poyu");

	return 1;
}
示例#19
0
inherit NPC;
void create()
{
	seteuid(getuid());
        set_name("采石工",({"worker"}));
        set("gender","男性");
        set("age",(random(10)+32));
        set("str",30);
        set("con",20);
        set("combat_exp",(100+random(40)));
        set_temp("apply/dodge",(10+random(5)));
        add_money("coin",50);
        setup();
	carry_object("/obj/cloth")->wear();
	if (random(50) > 40)
	carry_object("/d/green/obj/hammer")->wield();
	else
	carry_object("/d/green/obj/rope");
}
示例#20
0
void ledCube8_Tetris::run()
{
	startTime = millis();
	init();
	while(true)
	{
		
		
		time = millis();
		
		but1->checkButton();
		but2->checkButton();
		but3->checkButton();
		but4->checkButton();
		but5->checkButton();
		but6->checkButton();
		but7->checkButton();
		but8->checkButton();
		
		
		if((time -startTime) > shiftTime)
		{
			activeObjectA = random(0,7);

			startTime = time;
 
			if(playerIsDeath == false)
			{
				shiftDownAmount++;
			}
			
			if(checkForCollision(1,0)  && playerIsDeath == false)
			{
				
				shiftDownAmount = 0;
				cubeTerain 		= cube->add(cubeTerain,activeObject3);
				activeObject1 	= objects[activeObjectA];
				
	
				
				 if(	 
					 cubeTerain.CA8 && activeObject3.CA8  >= 1 ||
					 cubeTerain.CB8 && activeObject3.CB8  >= 1 ||
					 cubeTerain.CC8 && activeObject3.CC8  >= 1 ||
					 cubeTerain.CD8 && activeObject3.CD8  >= 1 ||
					 cubeTerain.CE8 && activeObject3.CE8  >= 1 ||
					 cubeTerain.CF8 && activeObject3.CF8  >= 1 ||
					 cubeTerain.CG8 && activeObject3.CG8  >= 1 ||
					 cubeTerain.CH8 && activeObject3.CH8  >= 1 
				 )
				 {
					 playerIsDeath = true;
				 }
				if( playerIsDeath == false)
				 {
					 shiftDownAmount 	= 0;
					 shiftLeftAmount	= 3;
					 shiftYAmount		= 3;
					 rotationXAmount	= 0;
					 rotationYAmount    = 0;
					 rotationZAmount    = 0;
					 activeObject1 		= objects[activeObjectA];
					 activeObjectOnlyRotate = activeObject1;
					 
					 score++;
					 checkForDelete();
				 }
			}
			
			
			calculate();
			send();
			
			/*p_lcd->clear();
			p_lcd->                         setCursor  (0, 0);
			
		p_lcd->                         print      ("Player 1: ");
	
		p_lcd->                         print      (scoreP1);
		
		p_lcd->                         setCursor  (0, 1);
		
		p_lcd->                         print      ("Player 2: ");
	
		p_lcd->                         print      (scoreP2);
		send();*/
			
			
		}
		//checkForDelete();
		if(playerIsDeath == true)
		{
			Serial.println("******************************");
			Serial.print("Score: ");
			Serial.println(score);
			
			p_lcd->		clear();
			p_lcd-> 	setCursor  (0, 0);
			p_lcd->     print      ("Score: ");
			p_lcd->     print      (score);
			p_lcd->     setCursor  (0, 1);
			stop();
			return;
		}
		send();
	}
}
示例#21
0
文件: engine.c 项目: Eiyeron/BIOME
void engine(settings sets) {
	unsigned char done = 0;
	unsigned char* topTable;
	unsigned char* backTable;
	unsigned char* tableA = (unsigned char*)(malloc(sizeof(unsigned char) * sets.width * sets.height));
	unsigned char* tableB = (unsigned char*)(malloc(sizeof(unsigned char) * sets.width * sets.height));
	
	
	srandom(RTC_GetTicks());
	unsigned int numCells = sets.width*sets.height;
	for(unsigned int i =0; i<numCells; i++) {
		tableB[i] = random()%2;
		tableA[i] = tableB[i];
	}
	
	topTable = tableA; backTable = tableB;
	
	int decal = 0;
	int menu_vy = 0;
	while(!done) {
	
		if(KeyDown(68)) {//OPTN
			if(decal == 0)
				menu_vy = 2;
			else if(decal == 10)
				menu_vy = -2;
		}
		decal+= menu_vy;
		if(decal == 0 || decal == 10)
			menu_vy = 0;
		
		if(decal == 10)
			UI(&sets, topTable, backTable);
		
		if(KeyDown(47))
		done = 1;
		
		//switching tables
		unsigned char* temp;
		temp = backTable;
		backTable = topTable;
		topTable = temp;
		
		//operating
		switch(sets.sim_type) {
		case GOL:
			GoL_reaction(topTable, backTable, sets);
			break;
		case WW:
			WW_reaction(topTable, backTable, sets);
			break;
			
		}
		
		//drawing
		Bdisp_AllClr_VRAM();
		Bdisp_EnableColor(1);
		draw_grid(topTable, sets);
		drawMenu(decal);
		Bdisp_PutDisp_DD();	
		
	}
	
	free(tableA);
	free(tableB);
	
}
示例#22
0
void ledCube8_Tetris::init()
{	
		 p_lcd-> init();
		p_lcd->clear();
		/*p_lcd->          				setCursor  (0, 1);
		p_lcd->                         print      ("Player 2: ");*/
		cubeData = {
		0,0,0,0,0,0,0,0,
			0,0,0,0,0,0,0,0,
			0,0,0,0,0,0,0,0,
			0,0,0,0,0,0,0,0,
			0,0,0,0,0,0,0,0,
			0,0,0,0,0,0,0,0,
			0,0,0,0,0,0,0,0,
			0,0,0,0,0,0,0,0		
		};
		cubeTerain = {
			0,0,0,0,0,0,0,0,
			0,0,0,0,0,0,0,0,
			0,0,0,0,0,0,0,0,
			0,0,0,0,0,0,0,0,
			0,0,0,0,0,0,0,0,
			0,0,0,0,0,0,0,0,
			0,0,0,0,0,0,0,0,
			0,0,0,0,0,0,0,0
		};
		objects[0]  ={
			
		0,0,0,0,0,0,0,0,	
		0,0,0,0,0,0,0,0,	
		0,0,0,0,8,0,0,0,	
		0,0,0,0,8,0,0,0,	
		0,0,0,0,8,0,0,0,	
		0,0,0,0,8,0,0,0,	
		0,0,0,0,0,0,0,0,	
		0,0,0,0,0,0,0,0
		};
		objects[1]  ={
			
			0,0,0,0,0,0,0,0,
			0,0,0,0,0,0,0,0,
			0,0,0,0,8,0,0,0,
			0,0,0,0,8,0,0,0,
			0,0,0,8,8,0,0,0,
			0,0,0,0,0,0,0,0,
			0,0,0,0,0,0,0,0,
			0,0,0,0,0,0,0,0
		};
		objects[2]  ={
			
			0,0,0,0,0,0,0,0,
			0,0,0,0,0,0,0,0,
			0,0,0,8,0,0,0,0,
			0,0,0,8,0,0,0,0,
			0,0,0,8,8,0,0,0,
			0,0,0,0,0,0,0,0,
			0,0,0,0,0,0,0,0,
			0,0,0,0,0,0,0,0
		};
		objects[3]  ={
			
			0,0,0,0,0,0,0,0,
			0,0,0,0,0,0,0,0,
			0,0,0,0,0,0,0,0,
			0,0,0,8,8,0,0,0,
			0,0,0,8,8,0,0,0,
			0,0,0,0,0,0,0,0,
			0,0,0,0,0,0,0,0,
			0,0,0,0,0,0,0,0
		};
		objects[4]  ={
			
			0,0,0,0,0,0,0,0,
			0,0,0,0,0,0,0,0,
			0,0,0,0,0,0,0,0,
			0,0,0,0,8,8,0,0,
			0,0,0,8,8,0,0,0,
			0,0,0,0,0,0,0,0,
			0,0,0,0,0,0,0,0,
			0,0,0,0,0,0,0,0
		};
		objects[5]  ={
			
			0,0,0,0,0,0,0,0,
			0,0,0,0,0,0,0,0,
			0,0,0,0,0,0,0,0,
			0,0,0,8,8,8,0,0,
			0,0,0,0,8,0,0,0,
			0,0,0,0,0,0,0,0,
			0,0,0,0,0,0,0,0,
			0,0,0,0,0,0,0,0
		};
		objects[6]  ={
			
			0,0,0,0,0,0,0,0,
			0,0,0,0,0,0,0,0,
			0,0,0,0,0,0,0,0,
			0,0,0,8,8,0,0,0,
			0,0,0,0,8,8,0,0,
			0,0,0,0,0,0,0,0,
			0,0,0,0,0,0,0,0,
			0,0,0,0,0,0,0,0
		};
		
		
		startTime 				= 0;
		time					= 0;
		shiftTime 				= 3000;
		
		activeObjectA 			= random(0,7);
		score					= 0;
		rotationXAmount			= 0;
		rotationYAmount         = 0;
		rotationZAmount         = 0;
		shiftDownAmount 		= 0;
		shiftLeftAmount 		= 3;
		shiftYAmount			= 3;
		
		playerIsDeath			= false;
		
		activeObject1	= objects[activeObjectA];
		activeObject2	= cubeData;
		activeObject3 	= cubeData;
		cubeTerain		= cubeData;
		activeObjectOnlyRotate = activeObject1;

}
示例#23
0
long
mrand48()
{
    return random();
}
示例#24
0
static int conf_choice(struct menu *menu)
{
	struct symbol *sym, *def_sym;
	struct menu *child;
	bool is_new;

	sym = menu->sym;
	is_new = !sym_has_value(sym);
	if (sym_is_changable(sym)) {
		conf_sym(menu);
		sym_calc_value(sym);
		switch (sym_get_tristate_value(sym)) {
		case no:
			return 1;
		case mod:
			return 0;
		case yes:
			break;
		}
	} else {
		switch (sym_get_tristate_value(sym)) {
		case no:
			return 1;
		case mod:
			printf("%*s%s\n", indent - 1, "", menu_get_prompt(menu));
			return 0;
		case yes:
			break;
		}
	}

	while (1) {
		int cnt, def;

		printf("%*s%s\n", indent - 1, "", menu_get_prompt(menu));
		def_sym = sym_get_choice_value(sym);
		cnt = def = 0;
		line[0] = 0;
		for (child = menu->list; child; child = child->next) {
			if (!menu_is_visible(child))
				continue;
			if (!child->sym) {
				printf("%*c %s\n", indent, '*', menu_get_prompt(child));
				continue;
			}
			cnt++;
			if (child->sym == def_sym) {
				def = cnt;
				printf("%*c", indent, '>');
			} else
				printf("%*c", indent, ' ');
			printf(" %d. %s", cnt, menu_get_prompt(child));
			if (child->sym->name)
				printf(" (%s)", child->sym->name);
			if (!sym_has_value(child->sym))
				printf(" (NEW)");
			printf("\n");
		}
		printf("%*schoice", indent - 1, "");
		if (cnt == 1) {
			printf("[1]: 1\n");
			goto conf_childs;
		}
		printf("[1-%d", cnt);
		if (sym->help)
			printf("?");
		printf("]: ");
		switch (input_mode) {
		case ask_new:
		case ask_silent:
			if (!is_new) {
				cnt = def;
				printf("%d\n", cnt);
				break;
			}
			check_stdin();
		case ask_all:
			fflush(stdout);
			fgets(line, 128, stdin);
			strip(line);
			if (line[0] == '?') {
				printf("\n%s\n", menu->sym->help ?
					menu->sym->help : nohelp_text);
				continue;
			}
			if (!line[0])
				cnt = def;
			else if (isdigit(line[0]))
				cnt = atoi(line);
			else
				continue;
			break;
		case set_random:
			def = (random() % cnt) + 1;
		case set_default:
		case set_yes:
		case set_mod:
		case set_no:
			cnt = def;
			printf("%d\n", cnt);
			break;
		}

	conf_childs:
		for (child = menu->list; child; child = child->next) {
			if (!child->sym || !menu_is_visible(child))
				continue;
			if (!--cnt)
				break;
		}
		if (!child)
			continue;
		if (strlen(line) > 0 && line[strlen(line) - 1] == '?') {
			printf("\n%s\n", child->sym->help ?
				child->sym->help : nohelp_text);
			continue;
		}
		sym_set_choice_value(sym, child->sym);
		if (child->list) {
			indent += 2;
			conf(child->list);
			indent -= 2;
		}
		return 1;
	}
}
示例#25
0
void MainWindow::refresh_clicked()
{
    if(!checked)
    {
        if(ui->spanishRB->isChecked())
        {
            ui->slovak_label->setText(slovak.at(randNum));

            QString slovakWord = slovak.at(randNum);
            QString slovakTranslation = ui->slovak_lineEdit->text();
            bool equal;
            if(slovakWord.contains(";")) // sklada sa z viacerych slov
            {
                QStringList wordList; wordList = slovakWord.split(";");

                QListIterator<QString> iter(wordList);
                while(iter.hasNext())
                {
                    QString word = iter.next();
                    equal = checkWords(slovakTranslation, word);
                    if(equal) break;
                }
            }
            else
            {
                equal = checkWords(slovakTranslation, slovakWord);
            }

            if(equal)
            {
                ui->slovak_label->setStyleSheet("QLabel {color : green; }");

                int correct = ui->correctLabel->text().toInt();
                ui->correctLabel->setText(QString::number(correct + 1));
                ui->correctLabel->setStyleSheet("QLabel {color : green; }");
            }
            else
            {
                ui->slovak_label->setStyleSheet("QLabel {color : red; }");
                ui->correctLabel->setText("0");
                ui->correctLabel->setStyleSheet("QLabel {color : red; }");
            }
        }
        else if(ui->slovakRB->isChecked())
        {
            ui->spanish_label->setText(spanish.at(randNum));

            QString spanishWord = spanish.at(randNum);
            QString spanishTranslation = ui->spanish_lineEdit->text();
            bool equal;
            if(spanishWord.contains(";")) // sklada sa z viacerych slov
            {
                QStringList wordList; wordList = spanishWord.split(";");

                QListIterator<QString> iter(wordList);
                while(iter.hasNext())
                {
                    QString word = iter.next();
                    equal = checkWords(spanishTranslation, word);
                    if(equal) break;
                }
            }
            else
            {
                equal = checkWords(spanishTranslation, spanishWord);
            }

            if(equal)
            {
                ui->spanish_label->setStyleSheet("QLabel {color : green; }");
                int correct = ui->correctLabel->text().toInt();
                ui->correctLabel->setText(QString::number(correct + 1));
                ui->correctLabel->setStyleSheet("QLabel {color : green; }");
            }
            else
            {
                ui->spanish_label->setStyleSheet("QLabel {color : red; }");
                ui->correctLabel->setText("0");
                ui->correctLabel->setStyleSheet("QLabel {color : red; }");
            }
        }

        checked = true;
    }
    else
    {
        randNum = random(0, vocabLen);
        ui->spanish_label->clear();
        ui->slovak_label->clear();

        if(ui->spanishRB->isChecked())
        {
            ui->slovak_lineEdit->clear();
            ui->spanish_lineEdit->setText(spanish.at(randNum));
        }
        else if(ui->slovakRB->isChecked())
        {
            ui->spanish_lineEdit->clear();
            ui->slovak_lineEdit->setText(slovak.at(randNum));
        }

        checked = false;
    }
}
示例#26
0
static void conf_askvalue(struct symbol *sym, const char *def)
{
	enum symbol_type type = sym_get_type(sym);
	tristate val;

	if (!sym_has_value(sym))
		printf("(NEW) ");

	line[0] = '\n';
	line[1] = 0;

	if (!sym_is_changable(sym)) {
		printf("%s\n", def);
		line[0] = '\n';
		line[1] = 0;
		return;
	}

	switch (input_mode) {
	case set_no:
	case set_mod:
	case set_yes:
	case set_random:
		if (sym_has_value(sym)) {
			printf("%s\n", def);
			return;
		}
		break;
	case ask_new:
	case ask_silent:
		if (sym_has_value(sym)) {
			printf("%s\n", def);
			return;
		}
		check_stdin();
	case ask_all:
		fflush(stdout);
		fgets(line, 128, stdin);
		return;
	case set_default:
		printf("%s\n", def);
		return;
	default:
		break;
	}

	switch (type) {
	case S_INT:
	case S_HEX:
	case S_STRING:
		printf("%s\n", def);
		return;
	default:
		;
	}
	switch (input_mode) {
	case set_yes:
		if (sym_tristate_within_range(sym, yes)) {
			line[0] = 'y';
			line[1] = '\n';
			line[2] = 0;
			break;
		}
	case set_mod:
		if (type == S_TRISTATE) {
			if (sym_tristate_within_range(sym, mod)) {
				line[0] = 'm';
				line[1] = '\n';
				line[2] = 0;
				break;
			}
		} else {
			if (sym_tristate_within_range(sym, yes)) {
				line[0] = 'y';
				line[1] = '\n';
				line[2] = 0;
				break;
			}
		}
	case set_no:
		if (sym_tristate_within_range(sym, no)) {
			line[0] = 'n';
			line[1] = '\n';
			line[2] = 0;
			break;
		}
	case set_random:
		do {
			val = (tristate)(random() % 3);
		} while (!sym_tristate_within_range(sym, val));
		switch (val) {
		case no: line[0] = 'n'; break;
		case mod: line[0] = 'm'; break;
		case yes: line[0] = 'y'; break;
		}
		line[1] = '\n';
		line[2] = 0;
		break;
	default:
		break;
	}
	printf("%s", line);
}
示例#27
0
static int
mkstemp_custom (char *tmpl, int kind)
{
  char *copy;
  int count, fd, i, len, rc;
  int save_errno = errno;
  time_t junk;
  struct stat file_stats;

  /* characters used in temporary filenames */
  static const char letters[] =
  "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

  /* determine length of template and allocate storage */
  len = (int) strlen (tmpl);
  copy = (char *) malloc ((len + 1) * sizeof (char));

  /* initialize random number generator */
  time (&junk);
#ifdef HAVE_LRAND48
  srand48 (((long) junk + (long) getpid ()) % (long) 1073741824);
#elif defined(HAVE_RANDOM)
  srandom (((unsigned int) junk + (unsigned int) getpid ()) % (unsigned int) 1073741824);
#else
  srand (((unsigned int) junk + (unsigned int) getpid ()) % (unsigned int) 1073741824);
#endif

  for (count = 0; count < TMP_MAX; ++count)
    {
      strcpy (copy, tmpl);

      for (i = 0; i < len; ++i)
        if (copy[i] == 'X')
#if defined(HAVE_LRAND48)
          copy[i] = letters[(int) lrand48 () % 62];
#elif defined(HAVE_RANDOM)
          copy[i] = letters[(int) random () % 62];
#else
          copy[i] = letters[(int) rand () % 62];
#endif

      switch (kind)
        {
        case GT_FILE:
          fd = open (copy, O_RDWR | O_CREAT | O_EXCL, 0600);
          if (fd >= 0)
            {
              errno = save_errno;
              strcpy (tmpl, copy);
              free (copy);
              return (fd);
            }
          else if (errno != EEXIST)
            {
              /* any other error will apply also to other names we might
                 try, and there are VERY many of them, so give up now */
              free (copy);
              return (-1);
            }
          break;

        case GT_DIR:
          rc = mkdir (copy, 0700);
          if (rc == 0)
            {
              errno = save_errno;
              strcpy (tmpl, copy);
              free (copy);
              return (0);
            }
          else if (errno != EEXIST)
            {
              /* any other error will apply also to other names we might
                 try, and there are VERY many of them, so give up now */
              free (copy);
              return (-1);
            }
          break;

        case GT_NOCREATE:
          rc = stat (copy, &file_stats);
          if (rc < 0)
            {
              if (errno == ENOENT)
                {
                  errno = save_errno;
                  strcpy (tmpl, copy);
                  free (copy);
                  return (0);
                }
              else
                {
                  /* any other error will apply also to other names we might
                     try, and there are VERY many of them, so give up now */
                  free (copy);
                  return (-1);
                }
            }
          break;

        default:
          fprintf (stderr, "tempname assertion failure: bad switch logic\n");
          return (-2);
        }
    }

  /* tried too many times, bailing... */
  errno = EEXIST;
  free (copy);
  return (-1);
}
示例#28
0
#include <std.h>
inherit WEAPON;

create() {
::create();
    set_id(({"lance","lava lance"}));
    set_name("lava Lance");
    set_short("%^BOLD%^%^RED%^L%^RESET%^%^RED%^a%^BOLD%^%^RED%^v"
              "%^RESET%^%^RED%^a %^BOLD%^%^RED%^L%^RESET%^%^RED%^a"
              "%^BOLD%^%^RED%^n%^RESET%^%^RED%^c%^BOLD%^%^RED%^e");
    set_long( "%^RED%^ This lance is one of a kind, that could only "
              "be found in the firey deeps..");
    set_mass(50);
    set_value(400+random(40));
    set_wc(10);
    set_ac(5);
    set_type("blade");
    set_hands(1);
}              
int query_auto_load()
{
 if (wizardp(this_player())) return 1;
 return 1;
}     
示例#29
0
文件: xxdizi.c 项目: aricxu/xkx100
// Room: /d/xingxiu/npc/xxdizi.c
// Last Modified by winder on Apr. 25 2001

inherit NPC;
void create()
{
	set_name("�����ɵ���", ({ "xingxiu dizi", "dizi"}));
	set("long", "���������ɵĶ�ͽ, ��ɱ�����, �޶�����\n");
	set("gender", "����");
	set("age", 30 + random(10));
	set("attitude", "peaceful");
	set("shen", -1000);

	set("str", 30);
	set("int", 20);
	set("con", 22);
	set("dex", 22);

	set("max_qi", 500);
	set("max_jing", 500);
	set("neili", 500);
	set("max_neili", 500);
	set("jiali", 20);
	set("combat_exp", 10000 + random(20000));

	set_skill("force", 50);
	set_skill("huagong-dafa", 30);
	set_skill("dodge", 50);
	set_skill("zhaixinggong", 30);
	set_skill("strike", 50);
	set_skill("chousui-zhang", 30);
示例#30
0
int main(int argc, char **argv)
{
    // count the cards in the system
    int total = PO8e::cardCount();
    printf("Found %d card(s) in the system.\n", total);
    if (0 == total)
    {
        printf("  exiting\n");
        exit(0);
    }

    // connect to the first (0) card
    printf(" Connecting to card\n");
    PO8e *card = PO8e::connectToCard(0);
    if (card == NULL)
        printf("  connection failed\n");
    else
    {
        printf("  established connection %p\n", (void*)card);
        // enable data collection
        if (! card->startCollecting())
        {
            printf("  startCollecting() failed with: %d\n",
                   card->getLastError());
            PO8e::releaseCard(card);
            exit(1);
        }
        else
            printf("  card is collecting incoming data.\n");
    }

    // wait for streaming to start
    printf("Waiting for the stream to start\n");
    while(card->samplesReady() == 0)
        compatUSleep(5000);

    // loop over reading data and print a progress line to show we're still running
    int64_t pos = 0;
    bool stopped = false;
    while(! stopped)
    {
        // compute the rate in megabytes per second
        char posChar = "|/-\\"[pos % 4];

        // working with just one card, so wait efficiently
        if (! card->waitForDataReady())
            break;

        size_t numSamples = card->samplesReady(&stopped);
        if (! stopped && numSamples > 0)
        {
            int channel = random() % card->numChannels();

            printf("Card has %4d samples of %4d channels. %c \r", numSamples, card->numChannels(), posChar);
            fflush(stdout);

            short buffer[8192];

// We can read a channel of data at a time...
#if READ_BY_CHANNEL
	    size_t count = card->readChannel(channel, buffer, (int)numSamples);
	    if (count != numSamples)
                printf("  reading %d samples from channel %d failed\n",
                       numSamples, channel);

            // once we're done reading the data into our own buffers, discard those samples
            card->flushBufferedData(count);
	    pos += count;
#else
// ... or read samples from every channel iteratively.  This is more efficient if you need to read multiple channels
            short temp[1024];
            for(int i = 0; i < (int)numSamples; i++)
            {
                // reading more than one sample at a time would be more efficient
                int64_t offsets[BLOCK_SIZE];
                if (card->readBlock(temp, BLOCK_SIZE, offsets) != BLOCK_SIZE)
                    printf("  reading block of %d samples failed\n", numSamples);
                buffer[i] = temp[channel];

                // checking if we've lost any data
                if (pos + BLOCK_SIZE != offsets[BLOCK_SIZE - 1])
                {
                    printf("\n  skipping %lld to position %lld\n", offsets[BLOCK_SIZE - 1] - (pos + BLOCK_SIZE), offsets[BLOCK_SIZE - 1]);
                    pos = offsets[BLOCK_SIZE - 1];
                }
                else
                    pos += BLOCK_SIZE;

                // once we're done reading the data into our own buffers, discard those samples
                card->flushBufferedData(BLOCK_SIZE);
            }
#endif

            // TODO: do something with the data in buffer?
        }
    }
    printf("\n");

    printf("Releasing the card\n");
    PO8e::releaseCard(card);

    return 0;
}