Пример #1
0
int
naive_grasp(data *d, int flags)
{
    int dim = d->numnodes;
    int start, cost, swaps;
    int *tour, *best_tour, best_cost, no_improvements;
    int use_three_opt = flags & DO_3OPT;
    long int i, limit;
    bool break_line = false;

    tour = MALLOC(dim, int);
    best_tour = MALLOC(dim, int);

    limit = (long int)dim * dim;
    printf("\nGRASP, %ld runs starting.. \n", limit);
    best_cost = INT_MAX;
    no_improvements = 0;
    for (i = 0; i < limit; i++) {
        start = RANDOM(dim);
        semi_greedy(d, start, tour, &cost);
        if (use_three_opt) {
            local_3opt(d, tour, &cost, &swaps);
        } else {
            local_2opt(d, tour, &cost, &swaps);
        }
        if (cost < best_cost) {
            if (flags & BE_VERBOSE) {
                if (break_line) {
                    break_line = false;
                    printf("\n");
                }
                printf("%ld: %d, %d\n", i, cost, start);
            }
            best_cost = cost;
            memcpy(best_tour, tour, dim * sizeof(int));
            no_improvements = 0;
        } else {
            no_improvements++;
            if (flags & BE_VERBOSE && !(no_improvements % 50)) {
                printf(">");
                break_line = true;
                fflush(stdout);
            }
        }
        if (no_improvements == 5000) {
            if (flags & BE_VERBOSE) {
                if (break_line) {
                    printf("\n");
                    break_line = false;
                }
                printf("No improvements for %d runs, stopping.\n",
                       no_improvements);
            }
            break;
        }
    }
    if (flags & BE_VERBOSE) {
        if (break_line) printf("\n");
        show_sol(best_tour, dim, best_cost);
        printf("Executions: %ld\n", i);
    }
    printf("\nGRASP final cost: %d\n", best_cost);

    free(tour);
    free(best_tour);
    return 0;
}
Пример #2
0
main(int argc, char *argv[]){
  int i,j,k;
  int nr, n_run;
  int n,m;
  double **A, **At, **G, **Gt, **GtG, **U, **Ut, **UtU, *w, **V, norm;
  double *v;
  
  FILE *stream;
  if (argc <4){
    fprintf(stderr,"Usage: %s m n n_run <datfile>\n", argv[0]);
    exit(EXIT_FAILURE);
  }
  m = atoi(argv[1]); 
  n = atoi(argv[2]);
  n_run = atoi(argv[3]);
  if (argc == 5){
    if ((stream = fopen(argv[4], "r")) == NULL){
      fprintf(stderr, "Can't open file %s.\n", argv[4]);
      exit(EXIT_FAILURE);
    }
  } else {
    stream = stdin;
  }
  
  A = ALLOC_MATRIX(m,n);
/*   for(i=0; i<m; ++i){ */
/*     for(j=0; j<n; ++j){ */
/*       if (fscanf(stream,"%lf", A[i]+j) != 1){ */
/* 	fprintf(stderr,"Error occured in reading the data.\n"); */
/* 	exit(EXIT_FAILURE); */
/*       } */
/*     } */
/*   } */

  for(i=0; i<m; ++i){  
      for(j=0; j<n; ++j){ 
	  A[i][j] = RANDOM(-10.0,10.0);
      }
  }

  /* print A */
  U = ALLOC_MATRIX(m,n);
  COPY_VECTOR(A[0], U[0], m*n);
  for(i=0; i<m; ++i){
    for(j=0; j<n; ++j)
      printf("%8.2f ", U[i][j]);
    printf("\n");
  }

  printf("Using Gram-Schmidt\n");
  /* gram-schmidt */
  At = RECT_TRANSPOSE(A, m,n);
  Gt = ALLOC_MATRIX(n,m);
  for(i=0; i<n_run; ++i){
      COPY_VECTOR(At[0], Gt[0], n*m);
      GRAM_SCHMIDT(Gt,n,m);
  }

  printf("Orthogonal vectors are \n");
  for (i=0; i<n; ++i){
      for(j=0, norm=0.0; j<m; ++j){
	  norm += SQR(Gt[i][j]);
	  printf("%.6f ", Gt[i][j]);
      }
      printf(" %f\n",norm);
  }

  G = RECT_TRANSPOSE(Gt,n,m);
  GtG = ALLOC_MATRIX(n,n);
  printf("S=\n");
  for(i=0; i<n; ++i){
      for(j=0; j<n; ++j){
	  GtG[i][j]=0.0;
	  for(k=0; k<m; ++k)
	      GtG[i][j]+=Gt[i][k]*G[k][j];
	  printf("%8.1e ", GtG[i][j]);
      }
      printf("\n");
  }

  /* project random vector against orthogonal basis */
  v = ALLOC_VECTOR(m);
  for(i=0; i<m; ++i)
      v[i] = RANDOM(-10,10);
  PROJECT(v, m, Gt, n);
  for(i=0; i<n; ++i)
      printf("v.G[%2d] = %9.2e\n", i, DOTP(v,Gt[i],m));
}
Пример #3
0
/* benchmark alloc / free */
ilong memory_case(ilong limit, ilong hiwater, ilong times, int rate, ilong seed)
{
	struct case_t { ilong size, m1, m2; char *ptr; };
	struct case_t *record, *p;
	iulong startup = 0, water = 0, maxmem = 0, sizev = 0;
	ilong pagesize, page_in, page_out, page_inuse;
	double waste;
	char *ptr;
	int count = 0, maxium = 0;
	int mode, size, pos;
	int retval = 0;

	record = (struct case_t*)malloc(100);
	xseed = seed;
	startup = gettime();

	for (; times >= 0; times--) {
		mode = 0;
		if (RANDOM(100) < rate) {
			size = RANDOM(limit);
			if (size < sizeof(ilong) * 2) size = sizeof(ilong) * 2;
			if (water + size >= hiwater) mode = 1;
		}	else {
			mode = 1;
		}
		
		/* TO ALLOC new memory block */
		if (mode == 0) {
			if (count + 4 >= maxium) {
				maxium = maxium? maxium * 2 : 8;
				maxium = maxium >= count + 4? maxium : count + 4;
				sizev = maxium * sizeof(struct case_t);
				record = (struct case_t*)realloc(record, 
					maxium * sizeof(struct case_t));
				assert(record);
			}
			ptr = xmalloc(size);
			assert(ptr);
			/* record pointer */
			p = &record[count++];
			p->ptr = ptr;
			p->size = size;
			p->m1 = rand() & 0x7ffffff;
			p->m2 = rand() & 0x7ffffff;
			water += size;
			/* writing magic data */
			*(ilong*)ptr = p->m1;
			*(ilong*)(ptr + p->size - sizeof(ilong)) = p->m2;
		}	
		/* TO FREE old memory block */
		else if (count > 0) {
			pos = RANDOM(count);
			record[count] = record[pos];
			p = &record[count];
			record[pos] = record[--count];
			ptr = p->ptr;
			/* checking magic data */
			if (*(ilong*)ptr != p->m1) {
				printf("[BAD] bad magic1: %lxh size=%d times=%d\n", ptr, p->size, times);
				return -1;
			}
			if (*(ilong*)(ptr + p->size - sizeof(ilong)) != p->m2) {
				printf("[BAD] bad magic2: %lxh size=%d times=%d\n", ptr, p->size, times);
				return -1;
			}
			xfree(ptr);
			water -= p->size;
		}
		if (water > maxmem) maxmem = water;
	}

	/* state page-supplier */
	page_in = imem_gfp_default.pages_new;
	page_out = imem_gfp_default.pages_del;
	page_inuse = imem_gfp_default.pages_inuse;
	pagesize = imem_page_size;

	/* free last memory blocks */
	for (pos = 0; pos < count; pos++) {
		p = &record[pos];
		ptr = p->ptr;
		if (*(ilong*)ptr != p->m1) {
			printf("[BAD] bad magic: %lxh\n", ptr);
			return -1;
		}
		if (*(ilong*)(ptr + p->size - sizeof(ilong)) != p->m2) {
			printf("[BAD] bad magic: %lxh\n", ptr);
			return -1;
		}
		xfree(ptr);
	}
	/* caculate time */
	startup = gettime() - startup;
	free(record);

	if (kmem_turnon && water > 0) {
		waste = (pagesize * page_inuse - water) * 100.0 / water;
	}	else {
		waste = 0;
	}

	printf("timing: total time is %lums maxmem is %lubytes\n", startup, maxmem);
	if (kmem_turnon) {
		printf(	"status: pages (in=%lu out=%lu inuse=%lu) waste=%.2f%%\n",
			page_in, page_out, page_inuse, waste);
	}
	printf("\n");
	return (ilong)startup;
}
Пример #4
0
void effect_tick(void)
{
	int n,cnt=0,in,m,co,fn,cn,in2,flag,z;

	for (n=1; n<MAXEFFECT; n++) {
		if (fx[n].used==USE_EMPTY) continue;
		cnt++;
		if (fx[n].used!=USE_ACTIVE) continue;

		if (fx[n].type==1) {	// remove injury flag from map
			fx[n].duration--;
			if (fx[n].duration==0) {
				fx[n].used=USE_EMPTY;
				map[fx[n].data[0]+fx[n].data[1]*MAPX].flags&=~(MF_GFX_INJURED|MF_GFX_INJURED1|MF_GFX_INJURED2);
			}
		}

		if (fx[n].type==2) {	// timer for character respawn
			if (fx[n].duration) fx[n].duration--;
			if (fx[n].duration==0 && plr_check_target(fx[n].data[0]+fx[n].data[1]*MAPX)) {
				m=fx[n].data[0]+fx[n].data[1]*MAPX;
				map[m].flags|=MF_MOVEBLOCK;
				fx[n].type=8;
			}
		}

		if (fx[n].type==3) {	// death mist
			fx[n].duration++;
			if (fx[n].duration==19) {

				fx[n].used=0;

				m=fx[n].data[0]+fx[n].data[1]*MAPX;
				map[m].flags&=~MF_GFX_DEATH;
			} else {
				m=fx[n].data[0]+fx[n].data[1]*MAPX;
				map[m].flags&=~MF_GFX_DEATH;
				map[m].flags|=((unsigned long long)fx[n].duration)<<40;

				if (fx[n].duration==9) {
					plr_map_remove(fx[n].data[2]);

					if (can_drop(m)) ;
					else if (can_drop(m+1)) m+=1;
					else if (can_drop(m-1)) m+=-1;
					else if (can_drop(m+MAPX)) m+=MAPX;
					else if (can_drop(m-MAPX)) m+=-MAPX;
					else if (can_drop(m+1+MAPX)) m+=1+MAPX;
					else if (can_drop(m+1-MAPX)) m+=1-MAPX;
					else if (can_drop(m-1+MAPX)) m+=-1+MAPX;
					else if (can_drop(m-1-MAPX)) m+=-1-MAPX;
					else if (can_drop(m+2)) m+=2;
					else if (can_drop(m-2)) m+=-2;
					else if (can_drop(m+2*MAPX)) m+=2*MAPX;
					else if (can_drop(m-2*MAPX)) m+=-2*MAPX;
					else if (can_drop(m+2+MAPX)) m+=2+MAPX;
					else if (can_drop(m+2-MAPX)) m+=2-MAPX;
					else if (can_drop(m-2+MAPX)) m+=-2+MAPX;
					else if (can_drop(m-2-MAPX)) m+=-2-MAPX;
					else if (can_drop(m+1+2*MAPX)) m+=1+2*MAPX;
					else if (can_drop(m+1-2*MAPX)) m+=1-2*MAPX;
					else if (can_drop(m-1+2*MAPX)) m+=-1+2*MAPX;
					else if (can_drop(m-1-2*MAPX)) m+=-1-2*MAPX;
					else if (can_drop(m+2+2*MAPX)) m+=2+2*MAPX;
					else if (can_drop(m+2-2*MAPX)) m+=2-2*MAPX;
					else if (can_drop(m-2+2*MAPX)) m+=-2+2*MAPX;
					else if (can_drop(m-2-2*MAPX)) m+=-2-2*MAPX;
					else {
						int temp;

						co=fx[n].data[2];
						temp=ch[co].temp;
						
						chlog(co,"could not drop grave");

						god_destroy_items(co);
						ch[co].used=USE_EMPTY;
						
						if (ch[co].flags&CF_RESPAWN)
							fx_add_effect(2,TICKS*60*5+RANDOM(TICKS*60*10),ch_temp[temp].x,ch_temp[temp].y,temp);
						m=0;
					}

					if (m) {
						co=fx[n].data[2];

						flag=0;
						for (z=0; z<40 && !flag; z++) {
							if (ch[co].item[z]) { flag=1; break; }
						}
						for (z=0; z<20 && !flag; z++) {
							if (ch[co].worn[z]) { flag=1; break; }
						}
						if (ch[co].citem) flag=1;
						if (ch[co].gold) flag=1;
						
                                                if (flag) {
							map[m].flags|=MF_MOVEBLOCK;
							fn=fx_add_effect(4,0,m%MAPX,m/MAPX,fx[n].data[2]);
							fx[fn].data[3]=fx[n].data[3];
						} else {
							int temp;

							temp=ch[co].temp;

							god_destroy_items(co);
							ch[co].used=USE_EMPTY;

							if (temp && (ch[co].flags&CF_RESPAWN)) {
                                                                if (temp==189 || temp==561) {
									fx_add_effect(2,TICKS*60*20+RANDOM(TICKS*60*5),ch_temp[temp].x,ch_temp[temp].y,temp);									
                                                                } else {
									fx_add_effect(2,TICKS*60*4+RANDOM(TICKS*60*1),ch_temp[temp].x,ch_temp[temp].y,temp);
								}
								xlog("respawn %d (%s): YES",co,ch[co].name);
                                                        } else xlog("respawn %d (%s): NO",co,ch[co].name);
						}
					}
				}
			}
		}

		if (fx[n].type==4) {	// tomb stone
			fx[n].duration++;
			if (fx[n].duration==29) {

				fx[n].used=USE_EMPTY;
				
				co=fx[n].data[2];
				
				m=fx[n].data[0]+fx[n].data[1]*MAPX;
				map[m].flags&=~MF_GFX_TOMB;
				map[m].flags&=~MF_MOVEBLOCK;								

				in=god_create_item(170);				
				it[in].data[0]=co;
				if (ch[co].data[99]) it[in].max_age[0]*=4;

				sprintf(it[in].description,"Here rests %s, killed by %s on the %d%s%s%s%s day of the Year %d.",
					ch[co].reference,
					fx[n].data[3] ? ch[fx[n].data[3]].reference : "unknown causes",
					globs->mdday,
					(globs->mdday==1 ? "st" : ""),
					(globs->mdday==2 ? "nd" : ""),
					(globs->mdday==3 ? "rd" : ""),
					(globs->mdday>3 ? "th" : ""),
					globs->mdyear);
				god_drop_item(in,fx[n].data[0],fx[n].data[1]);
				ch[co].x=it[in].x;
				ch[co].y=it[in].y;
				
				chlog(co,"grave done");
			} else {
				m=fx[n].data[0]+fx[n].data[1]*MAPX;
				map[m].flags&=~MF_GFX_TOMB;
				map[m].flags|=((unsigned long long)fx[n].duration)<<35;
			}
		}

		if (fx[n].type==5) {	// evil magic
			fx[n].duration++;
			m=fx[n].data[0]+fx[n].data[1]*MAPX;
			if (fx[n].duration==8) {

				fx[n].used=USE_EMPTY;
				map[m].flags&=~MF_GFX_EMAGIC;
			} else {
				map[m].flags&=~MF_GFX_EMAGIC;
				map[m].flags|=((unsigned long long)fx[n].duration)<<45;
			}
		}

		if (fx[n].type==6) {	// good magic
			fx[n].duration++;
			m=fx[n].data[0]+fx[n].data[1]*MAPX;
			if (fx[n].duration==8) {

				fx[n].used=USE_EMPTY;
				map[m].flags&=~MF_GFX_GMAGIC;
			} else {
				map[m].flags&=~MF_GFX_GMAGIC;
				map[m].flags|=((unsigned long long)fx[n].duration)<<48;
			}
		}

		if (fx[n].type==7) {	// caster magic
			fx[n].duration++;
			m=fx[n].data[0]+fx[n].data[1]*MAPX;
			if (fx[n].duration==8) {
				fx[n].used=USE_EMPTY;
				map[m].flags&=~MF_GFX_CMAGIC;
			} else {
				map[m].flags&=~MF_GFX_CMAGIC;
				map[m].flags|=((unsigned long long)fx[n].duration)<<51;
			}
		}

		if (fx[n].type==8) {	// repawn mist
			fx[n].duration++;
			if (fx[n].duration==19) {
				fx[n].used=0;
				m=fx[n].data[0]+fx[n].data[1]*MAPX;
				map[m].flags&=~MF_GFX_DEATH;
			} else {
				m=fx[n].data[0]+fx[n].data[1]*MAPX;
				map[m].flags&=~MF_GFX_DEATH;
				map[m].flags|=((unsigned long long)fx[n].duration)<<40;
				if (fx[n].duration==9) {
					m=fx[n].data[0]+fx[n].data[1]*MAPX;
					map[m].flags&=~MF_MOVEBLOCK;
					if (!pop_create_char(fx[n].data[2],1) && (ch_temp[fx[n].data[2]].flags&CF_RESPAWN)) {
						fx[n].type=2;
						fx[n].duration=TICKS*60*5;	// try again every 5 minutes
						map[m].flags&=~MF_GFX_DEATH;
					}
				}
			}
		}
		if (fx[n].type==9) {	// controlled item animation with optional monster creation
			fx[n].duration--;
			in=fx[n].data[0];
			if (!(fx[n].duration&1))
				it[in].status[1]++;

			if (fx[n].duration==0) {
				map[it[in].x+it[in].y*MAPX].it=0;
				if (fx[n].data[1]) {
					cn=pop_create_char(fx[n].data[1],0);
					god_drop_char(cn,it[in].x,it[in].y);
					ch[cn].dir=DX_RIGHTUP;
					plr_reset_status(cn);
				}
				fx[n].used=USE_EMPTY;
				it[in].used=USE_EMPTY;
			}
		}
		if (fx[n].type==10) { // respawn object
			if (fx[n].duration) fx[n].duration--;
			else {
				m=fx[n].data[0]+fx[n].data[1]*MAPX;

				// check if object isnt allowed to respawn (supporting beams for mine)
				if (is_beam(map[m].it) ||
				    is_beam(map[m-1].it) || is_beam(map[m+1].it) ||
				    is_beam(map[m-MAPX].it) || is_beam(map[m+MAPX].it) ||
				
				    is_beam(map[m-2].it) || is_beam(map[m+2].it) ||
				    is_beam(map[m-2*MAPX].it) || is_beam(map[m+2*MAPX].it) ||
				
				    is_beam(map[m-1+1*MAPX].it) || is_beam(map[m+1+1*MAPX].it) ||
				    is_beam(map[m-1-1*MAPX].it) || is_beam(map[m+1-1*MAPX].it) ||
				
				    is_beam(map[m-2+1*MAPX].it) || is_beam(map[m+2+1*MAPX].it) ||
				    is_beam(map[m-2-1*MAPX].it) || is_beam(map[m+2-1*MAPX].it) ||
				
				    is_beam(map[m-1+2*MAPX].it) || is_beam(map[m+1+2*MAPX].it) ||
				    is_beam(map[m-1-2*MAPX].it) || is_beam(map[m+1-2*MAPX].it) ||
				
				    is_beam(map[m-2+2*MAPX].it) || is_beam(map[m+2+2*MAPX].it) ||
				    is_beam(map[m-2-2*MAPX].it) || is_beam(map[m+2-2*MAPX].it)) {
					fx[n].duration=TICKS*60*15;
					continue;
				}
				in2=map[m].it;
				map[m].it=0;

				in=god_create_item(fx[n].data[2]);

				if (!god_drop_item(in,fx[n].data[0],fx[n].data[1])) {
					fx[n].duration=TICKS*60;
					it[in].used=USE_EMPTY;
					map[m].it=in2;
				} else {
					fx[n].used=USE_EMPTY;
					if (in2) it[in2].used=USE_EMPTY;
					reset_go(fx[n].data[0],fx[n].data[1]);
				}
			}
		}
		if (fx[n].type==11) {	// remove queued spell flags
			fx[n].duration--;
			if (fx[n].duration<1) {
				fx[n].used=USE_EMPTY;
				ch[fx[n].data[0]].data[96]&=~fx[n].data[1];
			}
		}
                if (fx[n].type==12) {	// death mist
			fx[n].duration++;
			if (fx[n].duration==19) {

				fx[n].used=0;

				m=fx[n].data[0]+fx[n].data[1]*MAPX;
				map[m].flags&=~MF_GFX_DEATH;
			} else {

				m=fx[n].data[0]+fx[n].data[1]*MAPX;
				map[m].flags&=~MF_GFX_DEATH;
				map[m].flags|=((unsigned long long)fx[n].duration)<<40;
                        }

		}
	}
	globs->effect_cnt=cnt;
}
Пример #5
0
TGarden *GardenCreate(const float pWidth, const float pHeight, const float pX, const float pY, const float pZ)
{
    /*! Create Ground Plane */
    TRenderEntity *lPlane = RenderEntityCreateQuadTextured(pWidth, pHeight, GARDEN_GROUND_TEXTURE);
    if(lPlane == NULL)
        return NULL;
        
    CLASS_CREATE(TGarden);

    Matrix4GetIdentity(&this->mModelView);
    Matrix4SetTranslate(&this->mModelView, pX, pY, pZ);

    this->mGround[0] = RenderEntityClone(lPlane);
    RenderEntityRotate(this->mGround[0], 90.0f, 1.0f, 0.0f, 0.0f);
    
    this->mGround[1] = RenderEntityClone(lPlane);
    RenderEntityRotate(this->mGround[1],-90.0f, 1.0f, 0.0f, 0.0f);
    
    RenderEntityDestroy(lPlane);
        
    /*! Dummy Grass which will be cloned as necessary */
    TGrass *lGrass = GrassCreate(0.0f, 0.0f, 0.0f, 0, GRASS_SIN_WAVE);
    if(lGrass!=NULL)
    {    
        int i,j;
        
        vec2 lOffsets[GARDEN_MAX_GRASS_RINGS] = 
        {
            {0.0f, 0.0f},
            {0.0f, 0.0f},
            {0.0f, 0.0f}
        };
        
        for(j=0;j<GARDEN_MAX_GRASS_RINGS;j++)
        for(i=0;i<GARDEN_MAX_GRASS_LINES;i++)
        {
            TGrass *lClone = GrassClone(lGrass);
            
            float lAngle = i * (2.0*M_PI/GARDEN_MAX_GRASS_LINES);
            float lX = cos(lAngle)*(15.0f - (j*5));
            float lZ = sin(lAngle)*(15.0f - (j*5));
                        
            GrassSetPosition(lClone, lX + lOffsets[j][0], 0.0f, lZ + lOffsets[j][1]);
            
            //! Random Type
            GrassSetType(lClone, RANDOM(GRASS_MAX_TYPES));
            
            //! Random Number of Segments
            GrassSetNumSegments(lClone, RANDOM(GRASS_MAX_SEGMENTS)+16);
            
            //! Inner Ring is Red
            if(j == GARDEN_MAX_GRASS_RINGS-1)
            {
                GrassSetColor(lClone, 0.8f, 0.0f, 0.0f, 1.0f);
            }
            
            this->mGrass[j][i] = lClone;
        }
        
        GrassDestroy(lGrass);
    }
    else
    {
        printf("Garden: grass couldn't be created for some reason. Crash is ahead!\n");
    }

    CLASS_INSTANCE();
}
Пример #6
0
int
main (int argc, char *argv[])
{
  gl_list_t list1, list2, list3;

  set_program_name (argv[0]);

  /* Allow the user to provide a non-default random seed on the command line.  */
  if (argc > 1)
    srand (atoi (argv[1]));

  {
    size_t initial_size = RANDOM (50);
    const void **contents =
      (const void **) malloc (initial_size * sizeof (const void *));
    size_t i;
    unsigned int repeat;

    for (i = 0; i < initial_size; i++)
      contents[i] = RANDOM_OBJECT ();

    /* Create list1.  */
    list1 = gl_list_nx_create (GL_ARRAY_LIST, NULL, NULL, NULL, true,
                               initial_size, contents);
    ASSERT (list1 != NULL);
    /* Create list2.  */
    list2 = gl_list_nx_create_empty (GL_RBTREE_LIST, NULL, NULL, NULL, true);
    ASSERT (list2 != NULL);
    for (i = 0; i < initial_size; i++)
      ASSERT (gl_list_nx_add_last (list2, contents[i]) != NULL);

    /* Create list3.  */
    list3 = gl_list_nx_create (GL_RBTREE_LIST, NULL, NULL, NULL, true,
                               initial_size, contents);
    ASSERT (list3 != NULL);

    check_all (list1, list2, list3);

    for (repeat = 0; repeat < 10000; repeat++)
      {
        unsigned int operation = RANDOM (16);
        switch (operation)
          {
          case 0:
            if (gl_list_size (list1) > 0)
              {
                size_t index = RANDOM (gl_list_size (list1));
                const char *obj = RANDOM_OBJECT ();
                gl_list_node_t node1, node2, node3;

                node1 = gl_list_nx_set_at (list1, index, obj);
                ASSERT (node1 != NULL);
                ASSERT (gl_list_get_at (list1, index) == obj);
                ASSERT (gl_list_node_value (list1, node1) == obj);

                node2 = gl_list_nx_set_at (list2, index, obj);
                ASSERT (node2 != NULL);
                ASSERT (gl_list_get_at (list2, index) == obj);
                ASSERT (gl_list_node_value (list2, node2) == obj);

                node3 = gl_list_nx_set_at (list3, index, obj);
                ASSERT (node3 != NULL);
                ASSERT (gl_list_get_at (list3, index) == obj);
                ASSERT (gl_list_node_value (list3, node3) == obj);

                if (index > 0)
                  {
                    ASSERT (gl_list_node_value (list1, gl_list_previous_node (list1, node1))
                            == gl_list_get_at (list1, index - 1));
                    ASSERT (gl_list_node_value (list2, gl_list_previous_node (list3, node3))
                            == gl_list_get_at (list2, index - 1));
                    ASSERT (gl_list_node_value (list3, gl_list_previous_node (list3, node3))
                            == gl_list_get_at (list2, index - 1));
                  }
                if (index + 1 < gl_list_size (list1))
                  {
                    ASSERT (gl_list_node_value (list1, gl_list_next_node (list1, node1))
                            == gl_list_get_at (list1, index + 1));
                    ASSERT (gl_list_node_value (list2, gl_list_next_node (list3, node3))
                            == gl_list_get_at (list2, index + 1));
                    ASSERT (gl_list_node_value (list3, gl_list_next_node (list3, node3))
                            == gl_list_get_at (list2, index + 1));
                  }
              }
            break;
          case 1:
            {
              const char *obj = RANDOM_OBJECT ();
              gl_list_node_t node1, node2, node3;
              node1 = gl_list_search (list1, obj);
              node2 = gl_list_search (list2, obj);
              node3 = gl_list_search (list3, obj);
              if (node1 == NULL)
                {
                  ASSERT (node2 == NULL);
                  ASSERT (node3 == NULL);
                }
              else
                {
                  ASSERT (node2 != NULL);
                  ASSERT (node3 != NULL);
                  ASSERT (gl_list_node_value (list1, node1) == obj);
                  ASSERT (gl_list_node_value (list2, node2) == obj);
                  ASSERT (gl_list_node_value (list3, node3) == obj);
                }
            }
            break;
          case 2:
            {
              const char *obj = RANDOM_OBJECT ();
              size_t index1, index2, index3;
              index1 = gl_list_indexof (list1, obj);
              index2 = gl_list_indexof (list2, obj);
              index3 = gl_list_indexof (list3, obj);
              if (index1 == (size_t)(-1))
                {
                  ASSERT (index2 == (size_t)(-1));
                  ASSERT (index3 == (size_t)(-1));
                }
              else
                {
                  ASSERT (index2 != (size_t)(-1));
                  ASSERT (index3 != (size_t)(-1));
                  ASSERT (gl_list_get_at (list1, index1) == obj);
                  ASSERT (gl_list_get_at (list2, index2) == obj);
                  ASSERT (gl_list_get_at (list3, index3) == obj);
                  ASSERT (index2 == index1);
                  ASSERT (index3 == index1);
                }
            }
            break;
          case 3: /* add 1 element */
            {
              const char *obj = RANDOM_OBJECT ();
              gl_list_node_t node1, node2, node3;
              node1 = gl_list_nx_add_first (list1, obj);
              ASSERT (node1 != NULL);
              node2 = gl_list_nx_add_first (list2, obj);
              ASSERT (node2 != NULL);
              node3 = gl_list_nx_add_first (list3, obj);
              ASSERT (node3 != NULL);
              ASSERT (gl_list_node_value (list1, node1) == obj);
              ASSERT (gl_list_node_value (list2, node2) == obj);
              ASSERT (gl_list_node_value (list3, node3) == obj);
              ASSERT (gl_list_get_at (list1, 0) == obj);
              ASSERT (gl_list_get_at (list2, 0) == obj);
              ASSERT (gl_list_get_at (list3, 0) == obj);
            }
            break;
          case 4: /* add 1 element */
            {
              const char *obj = RANDOM_OBJECT ();
              gl_list_node_t node1, node2, node3;
              node1 = gl_list_nx_add_last (list1, obj);
              ASSERT (node1 != NULL);
              node2 = gl_list_nx_add_last (list2, obj);
              ASSERT (node2 != NULL);
              node3 = gl_list_nx_add_last (list3, obj);
              ASSERT (node3 != NULL);
              ASSERT (gl_list_node_value (list1, node1) == obj);
              ASSERT (gl_list_node_value (list2, node2) == obj);
              ASSERT (gl_list_node_value (list3, node3) == obj);
              ASSERT (gl_list_get_at (list1, gl_list_size (list1) - 1) == obj);
              ASSERT (gl_list_get_at (list2, gl_list_size (list2) - 1) == obj);
              ASSERT (gl_list_get_at (list3, gl_list_size (list3) - 1) == obj);
            }
            break;
          case 5: /* add 3 elements */
            {
              const char *obj0 = RANDOM_OBJECT ();
              const char *obj1 = RANDOM_OBJECT ();
              const char *obj2 = RANDOM_OBJECT ();
              gl_list_node_t node1, node2, node3;
              node1 = gl_list_nx_add_first (list1, obj2);
              ASSERT (node1 != NULL);
              node1 = gl_list_nx_add_before (list1, node1, obj0);
              ASSERT (node1 != NULL);
              node1 = gl_list_nx_add_after (list1, node1, obj1);
              ASSERT (node1 != NULL);
              node2 = gl_list_nx_add_first (list2, obj2);
              ASSERT (node2 != NULL);
              node2 = gl_list_nx_add_before (list2, node2, obj0);
              ASSERT (node2 != NULL);
              node2 = gl_list_nx_add_after (list2, node2, obj1);
              ASSERT (node2 != NULL);
              node3 = gl_list_nx_add_first (list3, obj2);
              ASSERT (node3 != NULL);
              node3 = gl_list_nx_add_before (list3, node3, obj0);
              ASSERT (node3 != NULL);
              node3 = gl_list_nx_add_after (list3, node3, obj1);
              ASSERT (node3 != NULL);
              ASSERT (gl_list_node_value (list1, node1) == obj1);
              ASSERT (gl_list_node_value (list2, node2) == obj1);
              ASSERT (gl_list_node_value (list3, node3) == obj1);
              ASSERT (gl_list_get_at (list1, 0) == obj0);
              ASSERT (gl_list_get_at (list1, 1) == obj1);
              ASSERT (gl_list_get_at (list1, 2) == obj2);
              ASSERT (gl_list_get_at (list2, 0) == obj0);
              ASSERT (gl_list_get_at (list2, 1) == obj1);
              ASSERT (gl_list_get_at (list2, 2) == obj2);
              ASSERT (gl_list_get_at (list3, 0) == obj0);
              ASSERT (gl_list_get_at (list3, 1) == obj1);
              ASSERT (gl_list_get_at (list3, 2) == obj2);
            }
            break;
          case 6: /* add 1 element */
            {
              size_t index = RANDOM (gl_list_size (list1) + 1);
              const char *obj = RANDOM_OBJECT ();
              gl_list_node_t node1, node2, node3;
              node1 = gl_list_nx_add_at (list1, index, obj);
              ASSERT (node1 != NULL);
              node2 = gl_list_nx_add_at (list2, index, obj);
              ASSERT (node2 != NULL);
              node3 = gl_list_nx_add_at (list3, index, obj);
              ASSERT (node3 != NULL);
              ASSERT (gl_list_get_at (list1, index) == obj);
              ASSERT (gl_list_node_value (list1, node1) == obj);
              ASSERT (gl_list_get_at (list2, index) == obj);
              ASSERT (gl_list_node_value (list2, node2) == obj);
              ASSERT (gl_list_get_at (list3, index) == obj);
              ASSERT (gl_list_node_value (list3, node3) == obj);
              if (index > 0)
                {
                  ASSERT (gl_list_node_value (list1, gl_list_previous_node (list1, node1))
                          == gl_list_get_at (list1, index - 1));
                  ASSERT (gl_list_node_value (list2, gl_list_previous_node (list3, node3))
                          == gl_list_get_at (list2, index - 1));
                  ASSERT (gl_list_node_value (list3, gl_list_previous_node (list3, node3))
                          == gl_list_get_at (list2, index - 1));
                }
              if (index + 1 < gl_list_size (list1))
                {
                  ASSERT (gl_list_node_value (list1, gl_list_next_node (list1, node1))
                          == gl_list_get_at (list1, index + 1));
                  ASSERT (gl_list_node_value (list2, gl_list_next_node (list3, node3))
                          == gl_list_get_at (list2, index + 1));
                  ASSERT (gl_list_node_value (list3, gl_list_next_node (list3, node3))
                          == gl_list_get_at (list2, index + 1));
                }
            }
            break;
          case 7: case 8: /* remove 1 element */
            if (gl_list_size (list1) > 0)
              {
                size_t n = gl_list_size (list1);
                const char *obj = gl_list_get_at (list1, RANDOM (n));
                gl_list_node_t node1, node2, node3;
                node1 = gl_list_search (list1, obj);
                node2 = gl_list_search (list2, obj);
                node3 = gl_list_search (list3, obj);
                ASSERT (node1 != NULL);
                ASSERT (node2 != NULL);
                ASSERT (node3 != NULL);
                ASSERT (gl_list_remove_node (list1, node1));
                ASSERT (gl_list_remove_node (list2, node2));
                ASSERT (gl_list_remove_node (list3, node3));
                ASSERT (gl_list_size (list1) == n - 1);
              }
            break;
          case 9: case 10: /* remove 1 element */
            if (gl_list_size (list1) > 0)
              {
                size_t n = gl_list_size (list1);
                size_t index = RANDOM (n);
                ASSERT (gl_list_remove_at (list1, index));
                ASSERT (gl_list_remove_at (list2, index));
                ASSERT (gl_list_remove_at (list3, index));
                ASSERT (gl_list_size (list1) == n - 1);
              }
            break;
          case 11: case 12: /* remove 1 element */
            if (gl_list_size (list1) > 0)
              {
                size_t n = gl_list_size (list1);
                const char *obj = gl_list_get_at (list1, RANDOM (n));
                ASSERT (gl_list_remove (list1, obj));
                ASSERT (gl_list_remove (list2, obj));
                ASSERT (gl_list_remove (list3, obj));
                ASSERT (gl_list_size (list1) == n - 1);
              }
            break;
          case 13:
            if (gl_list_size (list1) > 0)
              {
                size_t n = gl_list_size (list1);
                const char *obj = "xyzzy";
                ASSERT (!gl_list_remove (list1, obj));
                ASSERT (!gl_list_remove (list2, obj));
                ASSERT (!gl_list_remove (list3, obj));
                ASSERT (gl_list_size (list1) == n);
              }
            break;
          case 14:
            {
              size_t n = gl_list_size (list1);
              gl_list_iterator_t iter1, iter2, iter3;
              const void *elt;
              iter1 = gl_list_iterator (list1);
              iter2 = gl_list_iterator (list2);
              iter3 = gl_list_iterator (list3);
              for (i = 0; i < n; i++)
                {
                  ASSERT (gl_list_iterator_next (&iter1, &elt, NULL));
                  ASSERT (gl_list_get_at (list1, i) == elt);
                  ASSERT (gl_list_iterator_next (&iter2, &elt, NULL));
                  ASSERT (gl_list_get_at (list2, i) == elt);
                  ASSERT (gl_list_iterator_next (&iter3, &elt, NULL));
                  ASSERT (gl_list_get_at (list3, i) == elt);
                }
              ASSERT (!gl_list_iterator_next (&iter1, &elt, NULL));
              ASSERT (!gl_list_iterator_next (&iter2, &elt, NULL));
              ASSERT (!gl_list_iterator_next (&iter3, &elt, NULL));
              gl_list_iterator_free (&iter1);
              gl_list_iterator_free (&iter2);
              gl_list_iterator_free (&iter3);
            }
            break;
          case 15:
            {
              size_t end = RANDOM (gl_list_size (list1) + 1);
              size_t start = RANDOM (end + 1);
              gl_list_iterator_t iter1, iter2, iter3;
              const void *elt;
              iter1 = gl_list_iterator_from_to (list1, start, end);
              iter2 = gl_list_iterator_from_to (list2, start, end);
              iter3 = gl_list_iterator_from_to (list3, start, end);
              for (i = start; i < end; i++)
                {
                  ASSERT (gl_list_iterator_next (&iter1, &elt, NULL));
                  ASSERT (gl_list_get_at (list1, i) == elt);
                  ASSERT (gl_list_iterator_next (&iter2, &elt, NULL));
                  ASSERT (gl_list_get_at (list2, i) == elt);
                  ASSERT (gl_list_iterator_next (&iter3, &elt, NULL));
                  ASSERT (gl_list_get_at (list3, i) == elt);
                }
              ASSERT (!gl_list_iterator_next (&iter1, &elt, NULL));
              ASSERT (!gl_list_iterator_next (&iter2, &elt, NULL));
              ASSERT (!gl_list_iterator_next (&iter3, &elt, NULL));
              gl_list_iterator_free (&iter1);
              gl_list_iterator_free (&iter2);
              gl_list_iterator_free (&iter3);
            }
            break;
          }
        check_all (list1, list2, list3);
      }

    gl_list_free (list1);
    gl_list_free (list2);
    gl_list_free (list3);
    free (contents);
  }

  return 0;
}
Пример #7
0
void minewall(int in,int cn)
{
	int in2,amount,co;
	char buf[80];

        if (!cn) {
		if (!it[in].drdata[4]) {
                        it[in].drdata[4]=1;
			switch((it[in].x+it[in].y)%3) {
				case 0:		it[in].sprite=15070; break;
				case 1:		it[in].sprite=15078; break;
				case 2:		it[in].sprite=15086; break;
			}
			
		}

                if (it[in].drdata[3]==8) {
			if ((map[it[in].x+it[in].y*MAXMAP].flags&MF_TMOVEBLOCK) || map[it[in].x+it[in].y*MAXMAP].it) {
				call_item(it[in].driver,in,0,ticker+TICKS);
				return;
			}
			it[in].sprite-=8;
			it[in].drdata[3]=0;
			it[in].flags|=IF_USE;
			it[in].flags&=~IF_VOID;
			
			remove_lights(it[in].x,it[in].y);
			map[it[in].x+it[in].y*MAXMAP].it=in;
			map[it[in].x+it[in].y*MAXMAP].flags|=MF_TSIGHTBLOCK|MF_TMOVEBLOCK;
			it[in].flags|=IF_SIGHTBLOCK;
			reset_los(it[in].x,it[in].y);
			add_lights(it[in].x,it[in].y);
                        set_sector(it[in].x,it[in].y);
		}
		return;
	}

	if (ch[cn].citem) {
		log_char(cn,LOG_SYSTEM,0,"Please empty your hand (mouse cursor) first.");
		player_driver_dig_off(cn);
		return;
	}
	
	
	if (it[in].drdata[3]<9) {
		if (ch[cn].endurance<POWERSCALE) {
			log_char(cn,LOG_SYSTEM,0,"You're too exhausted to continue digging.");
			player_driver_dig_off(cn);
			return;
		}
		ch[cn].endurance-=POWERSCALE/4-(ch[cn].prof[P_MINER]*POWERSCALE/(4*25));

                it[in].drdata[3]++;
		it[in].drdata[5]=0;
		it[in].sprite++;
		
		if (it[in].drdata[3]==8) {
                        map[it[in].x+it[in].y*MAXMAP].it=0;
			map[it[in].x+it[in].y*MAXMAP].flags&=~MF_TMOVEBLOCK;
			it[in].flags&=~IF_USE;
			it[in].flags|=IF_VOID;
			call_item(it[in].driver,in,0,ticker+TICKS*60*5+RANDOM(TICKS*60*25));

			if (!RANDOM(15)) {
				in2=create_item("silver");
				if (!in2) elog("silver not found");

				amount=RANDOM(it[in].drdata[0]*2+1)+it[in].drdata[0];
				//xlog("amount=%d",amount);
				if (ch[cn].prof[P_MINER]) amount+=amount*ch[cn].prof[P_MINER]/10;
				//xlog("amount=%d",amount);
				if (!amount && in2) {
					destroy_item(in2);
				}
			} else if (!RANDOM(50)) {
				in2=create_item("gold");
				if (!in2) elog("gold not found");

				amount=RANDOM(it[in].drdata[1]*2+1)+it[in].drdata[1];
				if (ch[cn].prof[P_MINER]) amount+=amount*ch[cn].prof[P_MINER]/10;
				if (!amount && in2) {
					destroy_item(in2);
				}
			} else amount=in2=0;

			if (amount && in2) {
				it[in2].value*=amount;
				*(unsigned int*)(it[in2].drdata+1)=amount;
				sprintf(it[in2].description,"%d units of %s.",*(unsigned int*)(it[in2].drdata+1),it[in2].name);

				if (ch[cn].flags&CF_PLAYER) dlog(cn,in2,"took from minewall");
				ch[cn].citem=in2;
				it[in2].carried=cn;
				ch[cn].flags|=CF_ITEMS;

				log_char(cn,LOG_SYSTEM,0,"You found %d units of %s.",amount,it[in2].name);

				if (it[in2].drdata[0]==1) check_military_silver(cn,amount);
			}

			if (!RANDOM(10)) {
				sprintf(buf,"miner%d",it[in].drdata[2]);
				co=create_char(buf,0);
				if (!co) elog("%s not found",buf);

				if (co) {
					if (drop_char(co,it[in].x,it[in].y,0)) {
						ch[co].tmpx=ch[co].x;
						ch[co].tmpy=ch[co].y;
						
						update_char(co);
						
						ch[co].hp=ch[co].value[0][V_HP]*POWERSCALE;
						ch[co].endurance=ch[co].value[0][V_ENDURANCE]*POWERSCALE;
						ch[co].mana=ch[co].value[0][V_MANA]*POWERSCALE;
						
						ch[co].dir=DX_RIGHTDOWN;
					} else {
						destroy_char(co);
					}
				}
			}
		}
		
		set_sector(it[in].x,it[in].y);

		if (it[in].drdata[3]==3) {
			remove_lights(it[in].x,it[in].y);
			map[it[in].x+it[in].y*MAXMAP].flags&=~MF_TSIGHTBLOCK;
			it[in].flags&=~IF_SIGHTBLOCK;
			reset_los(it[in].x,it[in].y);
			add_lights(it[in].x,it[in].y);
		}
	}
	
	if (it[in].drdata[3]<8) player_driver_dig_on(cn);
	else player_driver_dig_off(cn);
}
Пример #8
0
void
do_kill(int descr, dbref player, const char *what, int cost)
{
	dbref victim;
	char buf[BUFFER_LEN];
	struct match_data md;

	init_match(descr, player, what, TYPE_PLAYER, &md);
	match_neighbor(&md);
	match_me(&md);
	if (Wizard(OWNER(player))) {
		match_player(&md);
		match_absolute(&md);
	}
	victim = match_result(&md);

	switch (victim) {
	case NOTHING:
		notify(player, "I don't see that player here.");
		break;
	case AMBIGUOUS:
		notify(player, "I don't know who you mean!");
		break;
	default:
		if (Typeof(victim) != TYPE_PLAYER) {
			notify(player, "Sorry, you can only kill other players.");
		} else {
			/* go for it */
			/* set cost */
			if (cost < tp_kill_min_cost)
				cost = tp_kill_min_cost;

			if (FLAGS(DBFETCH(player)->location) & HAVEN) {
				notify(player, "You can't kill anyone here!");
				break;
			}

			if (tp_restrict_kill) {
				if (!(FLAGS(player) & KILL_OK)) {
					notify(player, "You have to be set Kill_OK to kill someone.");
					break;
				}
				if (!(FLAGS(victim) & KILL_OK)) {
					notify(player, "They don't want to be killed.");
					break;
				}
			}

			/* see if it works */
			if (!payfor(player, cost)) {
				notify_fmt(player, "You don't have enough %s.", tp_pennies);
			} else if ((RANDOM() % tp_kill_base_cost) < cost && !Wizard(OWNER(victim))) {
				/* you killed him */
				if (GETDROP(victim))
					/* give him the drop message */
					notify(player, GETDROP(victim));
				else {
					snprintf(buf, sizeof(buf), "You killed %s!", NAME(victim));
					notify(player, buf);
				}

				/* now notify everybody else */
				if (GETODROP(victim)) {
					snprintf(buf, sizeof(buf), "%s killed %s! ", NAME(player), NAME(victim));
					parse_oprop(descr, player, getloc(player), victim,
								   MESGPROP_ODROP, buf, "(@Odrop)");
				} else {
					snprintf(buf, sizeof(buf), "%s killed %s!", NAME(player), NAME(victim));
				}
				notify_except(DBFETCH(DBFETCH(player)->location)->contents, player, buf,
							  player);

				/* maybe pay off the bonus */
				if (GETVALUE(victim) < tp_max_pennies) {
					snprintf(buf, sizeof(buf), "Your insurance policy pays %d %s.",
							tp_kill_bonus, tp_pennies);
					notify(victim, buf);
					SETVALUE(victim, GETVALUE(victim) + tp_kill_bonus);
					DBDIRTY(victim);
				} else {
					notify(victim, "Your insurance policy has been revoked.");
				}
				/* send him home */
				send_home(descr, victim, 1);

			} else {
				/* notify player and victim only */
				notify(player, "Your murder attempt failed.");
				snprintf(buf, sizeof(buf), "%s tried to kill you!", NAME(player));
				notify(victim, buf);
			}
			break;
		}
	}
}
Пример #9
0
void mate(Individual *parent1, Individual *parent2,
          Individual *child1, Individual *child2, int wh_product)
{
  int crossover = RANDOM(wh_product - 1);
  int i;
  int y;
//#pragma omp sections //nowait // try num_threads(2), it may be faster than getting every thread to go in parallel, but then again, the nowait means they don't wait for the other one to finish. if we have 4 threads then 2 will (redundantly) do the first loop and 2 the second with an implied barrier at the end, but not if we do "nowait"
{
//*
//#pragma omp section
{
  for (i = 0; i < crossover; i++)
  {
    child1->image[i] = parent1->image[i];
    child2->image[i] = parent2->image[i];
  }
}
//#pragma omp section
{
  for (y = crossover; y < wh_product; y++)
  {
    child1->image[y] = parent2->image[y];
    child2->image[y] = parent1->image[y]; 
  }
}
//*/
///*
/*
//#pragma omp section
{
  for (i = 0; i < crossover/2; i++)
  {
    child1->image[i] = parent1->image[i];
    child2->image[i] = parent2->image[i];
  }
}
//#pragma omp section
{
  for (i = crossover/2; i < crossover; i++)
  {
    child1->image[i] = parent1->image[i];
    child2->image[i] = parent2->image[i];
  }

}
//#pragma omp section
{
  for (i = crossover; i < (wh_product-crossover)/2; i++)
  {
    child1->image[i] = parent2->image[i];
    child2->image[i] = parent1->image[i]; 
  }
}
//#pragma omp section
{
  for (i = crossover + (wh_product-crossover)/2; i < wh_product; i++)
  {
    child1->image[i] = parent2->image[i];
    child2->image[i] = parent1->image[i]; 
  }
}
*/
}
}
Пример #10
0
bool Stage::step(void)
{
    updateInput();

    menuOn = false;

    if (keys[KEYESC])
        return false;

    if (mouse[0] or (autoDumpOn and (bodyType == Random or bodyType == Box or bodyType == Circle)))
    {
        bodiesSize = smallBodiesOn ? SMALLBODYSIZE : RANDBODYSIZE;
        bodiesRadius = smallBodiesOn ? SMALLHALFSIZE : RANDHALFSIZE;

        switch (bodyType)
        {
        case Random:
            if (RANDOM(0, 1))
                world->makeBox(coordAllegToB2(Point(mouse_x, mouse_y)), bodiesSize);
            else
                world->makeCircle(coordAllegToB2(Point(mouse_x, mouse_y)), bodiesRadius);
            break;

        case Box:
            world->makeBox(coordAllegToB2(Point(mouse_x, mouse_y)), bodiesSize);
            break;

        case Circle:
            world->makeCircle(coordAllegToB2(Point(mouse_x, mouse_y)), bodiesRadius);
            break;

        case Free_Draw:
            freeDraw->takePoint(Point(mouse_x, mouse_y));
            break;

        case Custom_Polygon:
            customPolygon->takePoint(Point(mouse_x, mouse_y));
            break;

        case Custom_Box:
            customBox->takePoint(Point(mouse_x, mouse_y));
            break;

        case Custom_Circle:
            customCircle->takePoint(Point(mouse_x, mouse_y));
            break;
        }
    }
    else
    {
        if (freeDraw->On)
            freeDraw->makeBody(world);
        if (customBox->On)
            customBox->makeBody(world);
        if (customCircle->On)
            customCircle->makeBody(world);
        if (customPolygon->On)
            customPolygon->updateView(Point(mouse_x, mouse_y));
    }

    if (mouse[1])
    {
        if (customPolygon->On)
            customPolygon->makeBody(world);
        else
            world->makeBomb(coordAllegToB2(Point(mouse_x, mouse_y)));
    }

    if (keys[KEY1])
        bodyType = Random;

    if (keys[KEY2])
        bodyType = Box;

    if (keys[KEY3])
        bodyType = Circle;

    if (keys[KEY4])
    {
        bodyType = Free_Draw;
        setMouseLock(false);
    }

    if (keys[KEY5])
    {
        bodyType = Custom_Box;
        setMouseLock(false);
    }

    if (keys[KEY6])
        world->destroyLastBody();

    if (keys[KEY7])
        world->toggleStaticMode();

    if (keys[KEY8])
        world->toggleSimulation();

    if (keys[KEY9])
        if (bodyType == Random or bodyType == Box or bodyType == Circle)
            toggleMouseLock();

    if (keys[KEY0])
    {
        world->destroyAllBodies();
        createGround();
    }

    if (keys[KEYP])
        pyramidShow();

    if (keys[KEYTAB])
        menuOn = true;

    if (keys[KEYH])
        cleanModeOn = !cleanModeOn;

    if (keys[KEYA])
        autoDumpOn = !autoDumpOn;

    if (keys[KEYC])
        cursorOn = !cursorOn;

    if (keys[KEYX])
    {
        bodyType = Custom_Circle;
        setMouseLock(false);
    }

    if (keys[KEYV])
    {
        bodyType = Custom_Polygon;
        setMouseLock(true);
    }

    if (keys[KEYN])
        world->destroyLastNonStaticBody();

    if (keys[KEYM])
        world->destroyAllNonStaticBodies();

    if (keys[KEYS])
        smallBodiesOn = !smallBodiesOn;

    if (keys[KEYUP])
    {
        gravity.y += 2;
        world->setGravity(gravity);
    }

    if (keys[KEYDOWN])
    {
        gravity.y -= 2;
        world->setGravity(gravity);
    }

    if (keys[KEYLEFT])
    {
        gravity.x -= 2;
        world->setGravity(gravity);
    }

    if (keys[KEYRIGHT])
    {
        gravity.x += 2;
        world->setGravity(gravity);
    }

    if (keys[KEYD])
    {
        if (debugDrawOn)
        {
            if (bmpDrawOn)
            {
                bmpDrawOn = false;
            }
            else
            {
                bmpDrawOn = true;
                toggleDebugDraw();
            }
        }
        else
        {
            toggleDebugDraw();
        }
    }

    world->simulate();

    return true;
}
Пример #11
0
void KHMetisController::runSeqPartitioner(ParaHypergraph &hgraph,
                                          MPI_Comm comm) {
  initCoarsestHypergraph(hgraph, comm);

#ifdef DEBUG_CONTROLLER
  assert(h);
#endif

  h->setNumPartitions(1);

  khMetisOptions[1] = numSeqRuns / numProcs + 1;

  if (dispOption > 1 && myRank == 0) {
    out_stream << "[KHMETIS]: " << numSeqRuns << " " << khMetisOptions[1]
               << " | ";
  }

  int numVertices = h->getNumVertices();
  int numHedges = h->getNumHedges();
  int totWt = h->getTotWeight();

  int numHedgesCut;
  int ubFactor = static_cast<int>(floor(kWayConstraint * 100));

  int *vWeights = h->getVerWeightsArray();
  int *hOffsets = h->getHedgeOffsetArray();
  int *pinList = h->getPinListArray();
  int *hEdgeWts = h->getHedgeWeightsArray();
  int *pArray = h->getPartVectorArray();

  khMetisOptions[7] = RANDOM(1, 10000000);

  HMETIS_PartKway(numVertices, numHedges, vWeights, hOffsets, pinList, hEdgeWts,
                  numParts, ubFactor, khMetisOptions.getArray(), pArray,
                  &numHedgesCut);

  avePartWt = static_cast<double>(totWt) / numParts;
  maxPartWt = static_cast<int>(floor(avePartWt + avePartWt * kWayConstraint));

  h->initCutsizes(numParts);

  kWayRefiner->setMaxPartWt(maxPartWt);
  kWayRefiner->setAvePartWt(avePartWt);
  kWayRefiner->rebalance(*h);

#ifdef DEBUG_CONTROLLER
  MPI_Barrier(comm);
  for (int i = 0; i < numProcs; ++i) {
    if (myRank == i)
      h->checkPartitions(numParts, maxPartWt);

    MPI_Barrier(comm);
  }
#endif

  // ###
  // project partitions
  // ###

  initSeqPartitions(hgraph, comm);

#ifdef DEBUG_CONTROLLER
  hgraph.checkPartitions(numParts, maxPartWt, comm);
#endif

  DynaMem::delete_pointer<Hypergraph>(h);
}
Пример #12
0
void cmd_steal(int cn)
{
	int co,x,y,n,cnt,in=0,chance,dice,diff,m;

	if (!ch[cn].prof[P_THIEF]) {
		log_char(cn,LOG_SYSTEM,0,"You are not a thief, you cannot steal.");
		return;
	}
	if (ch[cn].action!=AC_IDLE) {
		log_char(cn,LOG_SYSTEM,0,"You can only steal when standing still.");
		return;
	}

	if (ch[cn].citem) {
		log_char(cn,LOG_SYSTEM,0,"Please free your hand (mouse cursor) first.");
		return;
	}

	dx2offset(ch[cn].dir,&x,&y,NULL);
	
	x+=ch[cn].x;
	y+=ch[cn].y;

	if (x<1 || x>=MAXMAP-1 || y<1 || y>=MAXMAP-1) {
		log_char(cn,LOG_SYSTEM,0,"Out of map.");
		return;
	}
	
	m=x+y*MAXMAP;
	co=map[m].ch;
	if (!co) {
		log_char(cn,LOG_SYSTEM,0,"There's no one to steal from.");
		return;
	}

	if (!can_attack(cn,co)) {
		log_char(cn,LOG_SYSTEM,0,"You cannot steal from someone you are not allowed to attack.");
		return;
	}
	if (map[m].flags&(MF_ARENA|MF_CLAN)) {
		log_char(cn,LOG_SYSTEM,0,"You cannot steal inside an arena.");
		return;
	}
	if (!(ch[co].flags&CF_PLAYER)) {
		log_char(cn,LOG_SYSTEM,0,"You can only steal from players.");
		return;
	}
	if (ch[co].driver==CDR_LOSTCON) {
		log_char(cn,LOG_SYSTEM,0,"You cannot steal from lagging players.");
		return;
	}
	if (areaID==20) {
		log_char(cn,LOG_SYSTEM,0,"You cannot steal in Live Quests.");
		return;
	}

	if (ch[co].action!=AC_IDLE || ticker-ch[co].regen_ticker<TICKS) {
		log_char(cn,LOG_SYSTEM,0,"You cannot steal from someone if your victim is not standing still.");
		return;
	}
	
	for (n=cnt=0; n<INVENTORYSIZE; n++) {
		if (n>=12 && n<30) continue;
		if ((in=ch[co].item[n]) && !(it[in].flags&IF_QUEST) && can_carry(cn,in,1)) cnt++;
	}
	if (!cnt) {
		log_char(cn,LOG_SYSTEM,0,"You could not find anything to steal.");
		return;
	}
	cnt=RANDOM(cnt);

	for (n=cnt=0; n<INVENTORYSIZE; n++) {
		if (n>=12 && n<30) continue;
		if ((in=ch[co].item[n]) && !(it[in].flags&IF_QUEST) && can_carry(cn,in,1)) {
			if (cnt<1) break;
			cnt--;
		}		
	}
	if (n==INVENTORYSIZE) {
		log_char(cn,LOG_SYSTEM,0,"You could not find anything to steal (2).");
		return;
	}

	diff=(ch[cn].value[0][V_STEALTH]-ch[co].value[0][V_PERCEPT])/2;
	chance=40+diff;
	if (chance<10) {
		log_char(cn,LOG_SYSTEM,0,"You'd get caught for sure. You decide not to try.");
		return;
	}
	chance=min(chance,ch[cn].prof[P_THIEF]*3);

        dice=RANDOM(100);
	diff=chance-dice;

        if (diff<-20) {
		log_char(cn,LOG_SYSTEM,0,"%s noticed your attempt and stopped you from stealing.",ch[co].name);
		ch[cn].endurance=1;
		if (ch[co].flags&CF_PLAYER) {
			log_char(co,LOG_SYSTEM,0,"°c3%s tried to steal from you!",ch[cn].name);
		} else notify_char(co,NT_GOTHIT,cn,0,0);
		return;
	}

	dlog(co,in,"dropped because %s stole it",ch[cn].name);
	remove_item_char(in);
	if (!give_char_item(cn,in)) {
		destroy_item(in);
		elog("had to destroy item in cmd_steal()!");
		return;
	}

	add_pk_steal(cn);

	if (diff<0) {
		log_char(cn,LOG_SYSTEM,0,"%s noticed your theft, but you managed to steal a %s anyway.",ch[co].name,it[in].name);
		ch[cn].endurance=1;
		if (ch[co].flags&CF_PLAYER) {
			log_char(co,LOG_SYSTEM,0,"°c3%s stole your %s!",ch[cn].name,it[in].name);
		} else notify_char(co,NT_GOTHIT,cn,0,0);
	} else log_char(cn,LOG_SYSTEM,0,"You stole a %s without %s noticing.",it[in].name,ch[co].name);
}
Пример #13
0
void
varsub(int qnum, int vnum, int flags)
{
    static char param[11][128];
    static char formats[23][128];
    static FILE *lfp = NULL;
    static int bInit = 0;
    long *lptr;
    char *ptr;
    int i = 0;
    DSS_HUGE tmp_date, tmp1, tmp2;
	
    if (!bInit)
    {
        sprintf(formats[4], "19%s-%s-01", HUGE_DATE_FORMAT, HUGE_DATE_FORMAT);
        sprintf(formats[5], "19%s-01-01", HUGE_DATE_FORMAT);
        sprintf(formats[6], "19%s-01-01", HUGE_DATE_FORMAT);
        sprintf(formats[7], "0.%s", HUGE_DATE_FORMAT); /* used by q6 */
        sprintf(formats[10], "19%s-%s-01", HUGE_DATE_FORMAT, HUGE_DATE_FORMAT);
        sprintf(formats[12], "19%s-01-01", HUGE_DATE_FORMAT);
        sprintf(formats[14], "19%s-01-01", HUGE_DATE_FORMAT);
        sprintf(formats[15], "19%s-01-01", HUGE_DATE_FORMAT);
	sprintf(formats[16], "Brand#%s%s", HUGE_FORMAT, HUGE_FORMAT);
	sprintf(formats[17], "Brand#%s%s", HUGE_FORMAT, HUGE_FORMAT);
	sprintf(formats[19], "Brand#%s%s", HUGE_FORMAT, HUGE_FORMAT);
        sprintf(formats[20], "19%s-01-01", HUGE_DATE_FORMAT);
        bInit = 1;
    }

    if (vnum == 0)
    {
		if ((flags & DFLT) == 0)
		{
			switch(qnum)
			{
			case 1:
				sprintf(param[1], HUGE_FORMAT, UnifInt((DSS_HUGE)60,(DSS_HUGE)120,qnum));
				param[2][0] = '\0';
				break;
			case 2:
				sprintf(param[1], HUGE_FORMAT,
					UnifInt((DSS_HUGE)P_SIZE_MIN, (DSS_HUGE)P_SIZE_MAX, qnum));
				pick_str(&p_types_set, qnum, param[3]);
				ptr = param[3] + strlen(param[3]);
				while (*(ptr - 1) != ' ') ptr--;
				strcpy(param[2], ptr);
				pick_str(&regions, qnum, param[3]);
				param[4][0] = '\0';
				break;
			case 3:
				pick_str(&c_mseg_set, qnum, param[1]);
				/*
				* pick a random offset within the month of march and add the
				* appropriate magic numbers to position the output functions 
				* at the start of March '95
				*/
            RANDOM(tmp_date, 0, 30, qnum);
				strcpy(param[2], *(asc_date + tmp_date + 1155));
				param[3][0] = '\0';
				break;
			case 4:
				tmp_date = UnifInt((DSS_HUGE)1,(DSS_HUGE)58,qnum);
				sprintf(param[1],formats[4],
					93 + tmp_date/12, tmp_date%12 + 1);
				param[2][0] = '\0';
				break;
			case 5:
				pick_str(&regions, qnum, param[1]);
				tmp_date = UnifInt((DSS_HUGE)93, (DSS_HUGE)97,qnum);
				sprintf(param[2], formats[5], tmp_date);
				param[3][0] = '\0';
				break;
			case 6:
				tmp_date = UnifInt((DSS_HUGE)93,(DSS_HUGE)97,qnum);
				sprintf(param[1], formats[6], tmp_date);
				sprintf(param[2], formats[7], 
                                    UnifInt((DSS_HUGE)2, (DSS_HUGE)9, qnum));
				sprintf(param[3], HUGE_FORMAT, UnifInt((DSS_HUGE)24, (DSS_HUGE)25, qnum));
				param[4][0] = '\0';
				break;
			case 7:
				tmp_date = pick_str(&nations2, qnum, param[1]);
				while (pick_str(&nations2, qnum, param[2]) == tmp_date);
				param[3][0] = '\0';
				break;
			case 8:
				tmp_date = pick_str(&nations2, qnum, param[1]);
				tmp_date = nations.list[tmp_date].weight;
				strcpy(param[2], regions.list[tmp_date].text);
				pick_str(&p_types_set, qnum, param[3]);
				param[4][0] = '\0';
				break;
			case 9:
				pick_str(&colors, qnum, param[1]);
				param[2][0] = '\0';
				break;
			case 10:
				tmp_date = UnifInt((DSS_HUGE)1,(DSS_HUGE)24,qnum);
				sprintf(param[1],formats[10],
					93 + tmp_date/12, tmp_date%12 + 1);
				param[2][0] = '\0';
				break;
			case 11:
				pick_str(&nations2, qnum, param[1]);
				sprintf(param[2], "%11.10f", Q11_FRACTION / flt_scale );
				param[3][0] = '\0';
				break;
			case 12:
				tmp_date = pick_str(&l_smode_set, qnum, param[1]);
				while (tmp_date == pick_str(&l_smode_set, qnum, param[2]));
				tmp_date = UnifInt((DSS_HUGE)93,(DSS_HUGE)97,qnum);
				sprintf(param[3], formats[12], tmp_date);
				param[4][0] = '\0';
				break;
			case 13:
				pick_str(&q13a, qnum, param[1]);
				pick_str(&q13b, qnum, param[2]);
				param[3][0] = '\0';
				break;
			case 14:
				tmp_date = UnifInt((DSS_HUGE)1,(DSS_HUGE)60,qnum);
				sprintf(param[1],formats[14],
					93 + tmp_date/12, tmp_date%12 + 1);
				param[2][0] = '\0';
				break;
			case 15:
				tmp_date = UnifInt((DSS_HUGE)1,(DSS_HUGE)58,qnum);
				sprintf(param[1],formats[15],
					93 + tmp_date/12, tmp_date%12 + 1);
				param[2][0] = '\0';
				break;
			case 16:
				tmp1 = UnifInt((DSS_HUGE)1, (DSS_HUGE)5, qnum); 
				tmp2 = UnifInt((DSS_HUGE)1, (DSS_HUGE)5, qnum);
				sprintf(param[1], formats[16], tmp1, tmp2);
				pick_str(&p_types_set, qnum, param[2]);
				ptr = param[2] + strlen(param[2]);
				while (*(--ptr) != ' ');
				*ptr = '\0';
				lptr = &sizes[0];
				for (i=3; i <= MAX_PARAM; i++)
				{
					sprintf(param[i], "%ld", *permute(lptr,50,qnum) + 1);
					lptr = (long *)NULL;
				}
					break;
			case 17:
				tmp1 = UnifInt((DSS_HUGE)1, (DSS_HUGE)5, qnum); 
				tmp2 = UnifInt((DSS_HUGE)1, (DSS_HUGE)5, qnum);
				sprintf(param[1], formats[17], tmp1, tmp2);
				pick_str(&p_cntr_set, qnum, param[2]);
				param[3][0] = '\0';
				break;
			case 18:
				sprintf(param[1], HUGE_FORMAT, UnifInt((DSS_HUGE)312, (DSS_HUGE)315, qnum));
				param[2][0] = '\0';
				break;
			case 19:
				tmp1 = UnifInt((DSS_HUGE)1, (DSS_HUGE)5, qnum); 
				tmp2 = UnifInt((DSS_HUGE)1, (DSS_HUGE)5, qnum);
				sprintf(param[1], formats[19], tmp1, tmp2);
				tmp1 = UnifInt((DSS_HUGE)1, (DSS_HUGE)5, qnum); 
				tmp2 = UnifInt((DSS_HUGE)1, (DSS_HUGE)5, qnum);
				sprintf(param[2], formats[19], tmp1, tmp2);
				tmp1 = UnifInt((DSS_HUGE)1, (DSS_HUGE)5, qnum); 
				tmp2 = UnifInt((DSS_HUGE)1, (DSS_HUGE)5, qnum);
				sprintf(param[3], formats[19], tmp1, tmp2);
				sprintf(param[4], HUGE_FORMAT, UnifInt((DSS_HUGE)1, (DSS_HUGE)10, qnum));
				sprintf(param[5], HUGE_FORMAT, UnifInt((DSS_HUGE)10, (DSS_HUGE)20, qnum));
				sprintf(param[6], HUGE_FORMAT, UnifInt((DSS_HUGE)20, (DSS_HUGE)30, qnum));
				param[7][0] = '\0';
				break;
			case 20:
				pick_str(&colors, qnum, param[1]);
				tmp_date = UnifInt((DSS_HUGE)93,(DSS_HUGE)97,qnum);
				sprintf(param[2], formats[20], tmp_date);
				pick_str(&nations2, qnum, param[3]);
				param[4][0] = '\0';
				break;
			case 21:
				pick_str(&nations2, qnum, param[1]);
				param[2][0] = '\0';
				break;
			case 22:
				lptr = &ccode[0];
				for (i=0; i <= 7; i++)
				{
					sprintf(param[i+1], "%ld", 10 + *permute(lptr,25, qnum));
					lptr = (long *)NULL;
				}
				param[8][0] = '\0';
				break;
			case 23:
			case 24:
                break;
			default:
				fprintf(stderr, 
					"No variable definitions available for query %d\n", 
                    qnum);
				return;
        }
    }
	
    if (flags & LOG)
	{
        if (lfp == NULL)
		{
            lfp = fopen(lfile, "a");
            OPEN_CHECK(lfp, lfile);
		}
        fprintf(lfp, "%d", qnum);
        for (i=1; i <= 10; i++)
            if (flags & DFLT)
			{
				if (defaults[qnum - 1][i - 1] == NULL)
					break;
				else
					fprintf(lfp, "\t%s", defaults[qnum - 1][i - 1]);
			}
            else
			{
				if (param[i][0] == '\0')
					break;
				else
					fprintf(lfp, "\t%s", param[i]);
			}
			fprintf(lfp, "\n");
	}
    }
    else
	{
        if (flags & DFLT)   
		{
            /* to allow -d to work at all scale factors */
            if (qnum == 11 && vnum == 2)
                fprintf(ofp, "%11.10f", Q11_FRACTION/flt_scale);
            else
                if (defaults[qnum - 1][vnum - 1])
                    fprintf(ofp, "%s", defaults[qnum - 1][vnum - 1]);
                else
					fprintf(stderr, 
					"Bad default request (q: %d, p: %d)\n",
					qnum, vnum);
		}
        else        
		{
            if (param[vnum] && vnum <= MAX_PARAM)
                fprintf(ofp, "%s", param[vnum]);
            else
				fprintf(stderr, "Bad parameter request (q: %d, p: %d)\n",
				qnum, vnum);
		}
	}
    return;
}
Пример #14
0
static void
semi_greedy(data *d, int start, int *tour, int *tour_length)
{
    int i, j, k;
    int dim = d->numnodes;
    int current, len, dist;
    int *visited = MALLOC(dim, int);
    /* RCL. */
    struct heapelm *candidates = MALLOC(dim, struct heapelm);
    int rclsize, rclused;
    double total_bias, rprob, racc, rpick;

    memset(visited, 0, dim * sizeof(int));

    len = 0;
    current = start;
    for (i = 0; i < dim - 1; i++) {
        visited[current] = 1;
        tour[i] = current;

        /* Define RCL size. */
        rclused = 0;
        if (RANDOM_UNIT() < 0.05) rclsize = dim - i - 2;
        else rclsize = RANDOM(((dim - i - 2) / 4) + 1);
        rclsize++;

        DEBUG("RCL size: %d\n", rclsize);

        /* Define RCL. */
        for (j = 0; j < dim; j++) {
            if (!visited[j]) {
                dist = d->dist(d, current, j);
                if (rclused < rclsize) {
                    candidates[rclused].num = j;
                    candidates[rclused].cost = dist;
                    rclused++;

                    if (rclused == rclsize) {
                        heap_build_max(candidates, rclsize);
                    }
                } else if (dist < candidates[0].cost) {
                    heap_replace_root(candidates, rclsize, j, dist);
                }
            }
        }

        DEBUG("RCL used: %d\n", rclused);
        heap_dump(candidates, rclused);

        /* Pick RCL element based on logarithmic bias. */
#define BIAS_LOG(r) (1/log((r)+1))
#define BIAS_LINEAR(r) (1./(r))
#define BIAS_EXP(r) (1/exp(r))
#define BIAS_RANDOM(r) 1
#define BIAS(r) BIAS_LOG(r)
        total_bias = 0;
        for (j = 1; j <= rclused; j++) {
            total_bias += BIAS(j);
        }
        racc = 0;
        rpick = RANDOM_UNIT();
#if DEBUGGING
        for (j = rclused; j >= 1; j--) {
            DEBUG("%f ", BIAS(j) / total_bias);
        }
        DEBUG("\nR: %f\n", rpick);
#endif
        for (j = rclused, k = 1; j >= 0; j--, k++) {
            rprob = BIAS(k) / total_bias;
            if (rprob + racc > rpick) {
                break;
            }
            racc += rprob;
        }
        DEBUG("Picked: j = %d, %d %d\n\n", j,
              candidates[j-1].num, candidates[j-1].cost);


        current = candidates[j - 1].num;
        len += candidates[j - 1].cost;
    }
    tour[i] = current;
    len += d->dist(d, current, start);
    *tour_length = len;

    free(visited);
    free(candidates);

#undef BIAS
#undef BIAS_LOG
}
Пример #15
0
int
mcp_frame_output_mesg(McpFrame * mfr, McpMesg * msg)
{
	char outbuf[BUFFER_LEN * 2];
	int bufrem = sizeof(outbuf);
	char mesgname[128];
	char datatag[32];
	McpArg *anarg = NULL;
	int mlineflag = 0;
	char *p;
	char *out;
	int flushcount = 8;

	if (!mfr->enabled && strcmp_nocase(msg->package, MCP_INIT_PKG)) {
		return EMCP_NOMCP;
	}

	/* Create the message name from the package and message subnames */
	if (msg->mesgname && *msg->mesgname) {
		snprintf(mesgname, sizeof(mesgname), "%s-%s", msg->package, msg->mesgname);
	} else {
		snprintf(mesgname, sizeof(mesgname), "%s", msg->package);
	}

	strcpyn(outbuf, sizeof(outbuf), MCP_MESG_PREFIX);
	strcatn(outbuf, sizeof(outbuf), mesgname);
	if (strcmp_nocase(mesgname, MCP_INIT_PKG)) {
		McpVer nullver = { 0, 0 };

		strcatn(outbuf, sizeof(outbuf), " ");
		strcatn(outbuf, sizeof(outbuf), mfr->authkey);
		if (strcmp_nocase(msg->package, MCP_NEGOTIATE_PKG)) {
			McpVer ver = mcp_frame_package_supported(mfr, msg->package);

			if (!mcp_version_compare(ver, nullver)) {
				return EMCP_NOPACKAGE;
			}
		}
	}

	/* If the argument lines contain newlines, split them into separate lines. */
	for (anarg = msg->args; anarg; anarg = anarg->next) {
		if (anarg->value) {
			McpArgPart *ap = anarg->value;

			while (ap) {
				p = ap->value;
				while (*p) {
					if (*p == '\n' || *p == '\r') {
						McpArgPart *nu = (McpArgPart *) malloc(sizeof(McpArgPart));

						nu->next = ap->next;
						ap->next = nu;
						*p++ = '\0';
						nu->value = string_dup(p);
						ap->value = (char *) realloc(ap->value, strlen(ap->value) + 1);
						ap = nu;
						p = nu->value;
					} else {
						p++;
					}
				}
				ap = ap->next;
			}
		}
	}

	/* Build the initial message string */
	out = outbuf;
	bufrem = outbuf + sizeof(outbuf) - out;
	for (anarg = msg->args; anarg; anarg = anarg->next) {
		out += strlen(out);
		bufrem = outbuf + sizeof(outbuf) - out;
		if (!anarg->value) {
			anarg->was_shown = 1;
			snprintf(out, bufrem, " %s: %s", anarg->name, MCP_ARG_EMPTY);
			out += strlen(out);
			bufrem = outbuf + sizeof(outbuf) - out;
		} else {
			int totlen = strlen(anarg->value->value) + strlen(anarg->name) + 5;

			if (anarg->value->next || totlen > ((BUFFER_LEN - (out - outbuf)) / 2)) {
				/* Value is multi-line or too long.  Send on separate line(s). */
				mlineflag = 1;
				anarg->was_shown = 0;
				snprintf(out, bufrem, " %s*: %s", anarg->name, MCP_ARG_EMPTY);
			} else {
				anarg->was_shown = 1;
				snprintf(out, bufrem, " %s: ", anarg->name);
				out += strlen(out);
				bufrem = outbuf + sizeof(outbuf) - out;

				msgarg_escape(out, bufrem, anarg->value->value);
				out += strlen(out);
				bufrem = outbuf + sizeof(outbuf) - out;
			}
			out += strlen(out);
			bufrem = outbuf + sizeof(outbuf) - out;
		}
	}

	/* If the message is multi-line, make sure it has a _data-tag field. */
	if (mlineflag) {
		snprintf(datatag, sizeof(datatag), "%.8lX", (unsigned long)(RANDOM() ^ RANDOM()));
		snprintf(out, bufrem, " %s: %s", MCP_DATATAG, datatag);
		out += strlen(out);
		bufrem = outbuf + sizeof(outbuf) - out;
	}

	/* Send the initial line. */
	SendText(mfr, outbuf);
	SendText(mfr, "\r\n");

	if (mlineflag) {
		/* Start sending arguments whose values weren't already sent. */
		/* This is usually just multi-line argument values. */
		for (anarg = msg->args; anarg; anarg = anarg->next) {
			if (!anarg->was_shown) {
				McpArgPart *ap = anarg->value;

				while (ap) {
					*outbuf = '\0';
					snprintf(outbuf, sizeof(outbuf), "%s* %s %s: %s", MCP_MESG_PREFIX, datatag, anarg->name, ap->value);
					SendText(mfr, outbuf);
					SendText(mfr, "\r\n");
					if (!--flushcount) {
						FlushText(mfr);
						flushcount = 8;
					}
					ap = ap->next;
				}
			}
		}

		/* Let the other side know we're done sending multi-line arg vals. */
		snprintf(outbuf, sizeof(outbuf), "%s: %s", MCP_MESG_PREFIX, datatag);
		SendText(mfr, outbuf);
		SendText(mfr, "\r\n");
	}

	return EMCP_SUCCESS;
}
Пример #16
0
/**
 * Returns a random direction (1..8) similar to a given direction.
 * @param dir The exact direction.
 * @return The randomized direction. */
int get_randomized_dir(int dir)
{
	return absdir(dir + RANDOM() % 3 + RANDOM() % 3 - 2);
}
int
main (int argc, char *argv[])
{
  gl_oset_t set1;
  gl_list_t set2;

  set_program_name (argv[0]);

  /* Allow the user to provide a non-default random seed on the command line.  */
  if (argc > 1)
    srand (atoi (argv[1]));

  {
    size_t initial_size = RANDOM (20);
    size_t i;
    unsigned int repeat;

    /* Create set1.  */
    set1 = gl_oset_nx_create_empty (GL_ARRAY_OSET, (gl_setelement_compar_fn) strcmp, NULL);
    ASSERT (set1 != NULL);

    /* Create set2.  */
    set2 = gl_list_create_empty (GL_ARRAY_LIST, NULL, NULL, NULL, false);

    check_all (set1, set2);

    /* Initialize them.  */
    for (i = 0; i < initial_size; i++)
      {
        const char *obj = RANDOM_OBJECT ();
        ASSERT (gl_oset_nx_add (set1, obj)
                == (gl_sortedlist_search (set2, (gl_listelement_compar_fn)strcmp, obj) != NULL
                    ? false
                    : (gl_sortedlist_add (set2, (gl_listelement_compar_fn)strcmp, obj), true)));
        check_all (set1, set2);
      }

    for (repeat = 0; repeat < 100000; repeat++)
      {
        unsigned int operation = RANDOM (3);
        switch (operation)
          {
          case 0:
            {
              const char *obj = RANDOM_OBJECT ();
              ASSERT (gl_oset_search (set1, obj)
                      == (gl_sortedlist_search (set2, (gl_listelement_compar_fn)strcmp, obj) != NULL));
            }
            break;
          case 1:
            {
              const char *obj = RANDOM_OBJECT ();
              ASSERT (gl_oset_nx_add (set1, obj)
                      == (gl_sortedlist_search (set2, (gl_listelement_compar_fn)strcmp, obj) != NULL
                          ? false
                          : (gl_sortedlist_add (set2, (gl_listelement_compar_fn)strcmp, obj), true)));
            }
            break;
          case 2:
            {
              const char *obj = RANDOM_OBJECT ();
              ASSERT (gl_oset_remove (set1, obj)
                      == gl_sortedlist_remove (set2, (gl_listelement_compar_fn)strcmp, obj));
            }
            break;
          }
        check_all (set1, set2);
      }

    gl_oset_free (set1);
    gl_list_free (set2);
  }

  return 0;
}
Пример #18
0
/**
 * Create a cryptographically weak pseudo-random number in the interval of 0 to 1.
 *
 * @return number between 0 and 1.
 */
static double
get_weak_random ()
{
  return ((double) RANDOM () / RAND_MAX);
}
Пример #19
0
void minedoor(int in,int cn)
{
	int in2,nr,ret;

        // gather information about door system
	if (!door_init) {
		for (in2=1; in2<MAXITEM; in2++) {
			if (!it[in2].flags) continue;
			if (it[in2].driver!=IDR_MINEDOOR) continue;

			nr=it[in2].drdata[0];
			//xlog("found something at %d,%d",it[in2].x,it[in2].y);

			if (!it[in2].drdata[1]) {	// source door
				if (it[in2].drdata[3]) {	// usable source door
					if (sdoor[nr]) xlog("confused: two source doors");
                                        sdoor[nr]=in2;
					//xlog("source %d is at %d,%d",it[in2].drdata[0],it[in2].x,it[in2].y);
				}
			} else {	// target door
				if (tdoor[nr]) xlog("confused: two target doors");
				tdoor[nr]=in2;
				//xlog("target %d is at %d,%d",it[in2].drdata[0],it[in2].x,it[in2].y);
			}
		}
		door_init=1;
	}

	nr=it[in].drdata[0];
	
	if (!cn) {	// timer call
		call_item(it[in].driver,in,0,ticker+TICKS*30);

		if (it[in].drdata[3]) return;	// we're already open, dont do anything

		// dont change it when the surrounding walls have been dug away
		if (!(map[it[in].x+it[in].y*MAXMAP+1].flags&(MF_SIGHTBLOCK|MF_TSIGHTBLOCK)) ||
		    !(map[it[in].x+it[in].y*MAXMAP-1].flags&(MF_SIGHTBLOCK|MF_TSIGHTBLOCK)) ||
		    !(map[it[in].x+it[in].y*MAXMAP+MAXMAP].flags&(MF_SIGHTBLOCK|MF_TSIGHTBLOCK)) ||
		    !(map[it[in].x+it[in].y*MAXMAP-MAXMAP].flags&(MF_SIGHTBLOCK|MF_TSIGHTBLOCK)) ||
		    !(map[it[in].x+it[in].y*MAXMAP+1+MAXMAP].flags&(MF_SIGHTBLOCK|MF_TSIGHTBLOCK)) ||
		    !(map[it[in].x+it[in].y*MAXMAP+1-MAXMAP].flags&(MF_SIGHTBLOCK|MF_TSIGHTBLOCK)) ||
		    !(map[it[in].x+it[in].y*MAXMAP-1+MAXMAP].flags&(MF_SIGHTBLOCK|MF_TSIGHTBLOCK)) ||
		    !(map[it[in].x+it[in].y*MAXMAP-1-MAXMAP].flags&(MF_SIGHTBLOCK|MF_TSIGHTBLOCK))) {
			//xlog("dug out 1");
                        return;
		}
                if ((in2=sdoor[nr])) {	// there is a source door already, close it
			if (!(map[it[in2].x+it[in2].y*MAXMAP+1].flags&(MF_MOVEBLOCK|MF_TMOVEBLOCK)) ||
			    !(map[it[in2].x+it[in2].y*MAXMAP-1].flags&(MF_MOVEBLOCK|MF_TMOVEBLOCK)) ||
			    !(map[it[in2].x+it[in2].y*MAXMAP+MAXMAP].flags&(MF_MOVEBLOCK|MF_TMOVEBLOCK)) ||
			    !(map[it[in2].x+it[in2].y*MAXMAP-MAXMAP].flags&(MF_MOVEBLOCK|MF_TMOVEBLOCK)) ||
			    !(map[it[in2].x+it[in2].y*MAXMAP+1+MAXMAP].flags&(MF_MOVEBLOCK|MF_TMOVEBLOCK)) ||
			    !(map[it[in2].x+it[in2].y*MAXMAP+1-MAXMAP].flags&(MF_MOVEBLOCK|MF_TMOVEBLOCK)) ||
			    !(map[it[in2].x+it[in2].y*MAXMAP-1+MAXMAP].flags&(MF_MOVEBLOCK|MF_TMOVEBLOCK)) ||
			    !(map[it[in2].x+it[in2].y*MAXMAP-1-MAXMAP].flags&(MF_MOVEBLOCK|MF_TMOVEBLOCK))) {
				//xlog("dug out 2");
				return;
			}
			if (RANDOM(20)) return;	// some randomness

			it[in2].sprite=15000;
			it[in2].flags&=~IF_USE;
			it[in2].drdata[3]=0;
			set_sector(it[in2].x,it[in2].y);
			//xlog("closed source door %d at %d,%d",nr,it[in2].x,it[in2].y);
		}

		switch(it[in].drdata[2]) {
			case DX_UP:
			case DX_DOWN:	it[in].sprite=20124; break;
			case DX_RIGHT:
			case DX_LEFT:	it[in].sprite=20122; break;
		}
		it[in].flags|=IF_USE;
		it[in].drdata[3]=1;
		set_sector(it[in].x,it[in].y);
		sdoor[nr]=in;
		//xlog("opened source door %d at %d,%d",nr,it[in].x,it[in].y);

		return;
	}
	
	// find target
	if (it[in].drdata[1]) in2=sdoor[nr];
	else in2=tdoor[nr];

	// teleport character to target
	ret=0;
	switch(it[in2].drdata[2]) {
		case DX_UP:	ret=teleport_char_driver(cn,it[in2].x,it[in2].y-1); break;
		case DX_DOWN:	ret=teleport_char_driver(cn,it[in2].x,it[in2].y+1); break;
		case DX_RIGHT:	ret=teleport_char_driver(cn,it[in2].x-1,it[in2].y); break;
		case DX_LEFT:	ret=teleport_char_driver(cn,it[in2].x+1,it[in2].y); break;
	}
	if (!ret) {
		log_char(cn,LOG_SYSTEM,0,"The mine has collapsed behind this door. Some friendly spirit grabs you and teleports you somewhere else.");
		if (areaID!=31) teleport_char_driver(cn,230,240);
		else teleport_char_driver(cn,211,231);
	}
}
Пример #20
0
int	grepr_addline(ematrix *ex, ematrix *ed, int tr, int xpfd, ematrix ***lout) {
	ematrix		*ee,*ef, **el=NULL,**elo=NULL, **x;
	int		i,j,k,p,r, ro,co, xp=-1;
	
	if (!ed)  {PROGERROR("the matrix ed must be given!"); return -1;}
	ro = ROWSM(ed);  co = COLSM(ed);
	if (tr<0)  tr = ((ex? ROWSM(ex)<ro: ro<=1)? 0:1);	/* (tr need not be given - determining from matrix sizes) */
	if (ex? (ro!=ROWSM(ex)+(!tr) || co!=COLSM(ex)+(!!tr)): (ro!=1 && co!=1))
		{PROGERROR("the matrices ex, ed have wrong sizes! tr=%d; ro=%d, co=%d - %d, %d",tr,ro,co,ROWSM(ex),COLSM(ex)); return -1;}
	if ((ex?ISREFMAT(ex):0) || ISREFMAT(ed))  {PROGERROR("do not give refering matrices here"); return -1;}
	if (lout?*lout:0)  {PROGERROR("the list lout must be given empty (null)"); return -1;}
	DEBUG(CURDLEV+1,"Adding a %s to matrix %p to (%dx%d), pf=%d\n",tr?"column":"row",ex,ro,co,xpfd);
	if (ex && lout)  EMATDEBUGS(CURDLEV+2,ex,"\t\t-\t");
	
			/**
			 * We first try the easy extensions:
			 * If ed is 1xC or Rx1, then ex has entries 0 or 1 depending on ed.
			 * If some other line of ed is parallel (and nonzero) to the added line,
			 * then we make ex by copying the corresponding line to append.
			 * (We have to use the proper pfield xpfd for ed!)
			**/
	xp = pfield_curindex();
	if (xpfd>=0) pfield_switchto_fast(xpfd);
	if (lout)  EMATDEBUGS(CURDLEV+2,ed,"\t\t~\t");
	p = tr? ematrix_parallel_col(ed,co-1): ematrix_parallel_row(ed,ro-1);
	if (p>=0) if (ematrix_linezero(ed,tr,p)>0)  p = -1;
	if (xpfd>=0 && xp>=0) pfield_switchto_fast(xp);
	if (!ex) {
		ee = new_ematrix(ro,co,ro,co);
		for (i=0; i<ro; i++) for (j=0; j<co; j++) {
			SETEXSIGMZERO(ee,i,j);
			if (SIGNM(ed,i,j)!=0)  SIGNM(ee,i,j) = 1;
		}
		elo = alist_append(elo,ee);  k = 1;
		DEBUG(CURDLEV+1,"Creating a %s matrix with %s.\n",tr?"1xC":"Rx1",gener_extprintline(0,ee,tr));
	} else if (p>=0 && ro+co>=3) {
		ef = ematrix_copy_to(ex,ro,co);
		ef = ematrix_append_rc(ef,tr);
		if (tr) { for (i=0; i<ro; i++)
			if (SIGNM(ed,i,co-1))  COPYEXSIGM(ef,i,co-1,ef,i,p);
		} else { for (i=0; i<co; i++)
			if (SIGNM(ed,ro-1,i))  COPYEXSIGM(ef,ro-1,i,ef,p,i);
		}
		elo = alist_append(elo,ef);  k = 1;
		DEBUG(CURDLEV+1,"Appending a parallel %s %s.\n",tr?"column":"row",gener_extprintline(0,ef,tr));
	} else {
			/**
			 * In all other cases we use the next routine:
			 * We generate all one-line extensions of ex which have the same
			 * zero pattern in the appended line as ed.
			 * Then we check the subdeterminants of each extension against
			 * the matrix ed, and store copies of isomorphic ones.
			**/
		r = gener_matextens_zeros(ex,tr,ed,&el);
		DEBUG(CURDLEV+1,"Filtering %d (zero-respecting) extension lines...\n",alist_getlength(el));
		if (r<0)  return r;
		for (x=el, k=0; x?*x:0; x++)
			if (ematrix_havesamedets_repres(*x,ed,xpfd,tr)) {
				k++;
				elo = alist_append(elo,ematrix_copy(*x));
				DEBUG(CURDLEV+1+2*(k>2),"Appending a #%d(%d) %s %s.\n",k,alist_getlength(elo),tr?"column":"row",gener_extprintline(0,*x,tr));
			}
		if (el)  dispose_alist_mats(el);
	}
#ifndef FASTPROG	
	if (IFRANDDEBUGLESS(222) && k>0) {
		x = elo+RANDOM()%k;
		if (!ematrix_havesamedets(*x,ed,xpfd))  {PROGERROR("the extended matrix has not same subdeterminants!");}
	}
	if (IFRANDDEBUGLESS(222) && ro>2 && co>2 && lout) {
		ee = ematrix_copydual(ex);  ef = ematrix_copydual(ed);
		ematrix_swaprows(ee,0,co-2);  ematrix_swaprows(ef,0,co-2);
		DEBUG(CURDLEV+1,"Recursive testing the number of added lines...\n");
		r = grepr_addline(ee,ef,(tr<0?-1:!tr),xpfd,NULL);
		if (r!=k && (r>=0 || k>=0))  {PROGERROR("wrong result of a recursive call %d!=%d",r,k);}
	}
#endif
	if (lout)  *lout = (*lout? alist_applist(*lout,elo): elo);
	else if (elo)  dispose_alist_mats(elo);
	return k;
}
Пример #21
0
Файл: egp.c Проект: kelixin/t50
                    sizeof(struct egp_hdr)  +
                    sizeof(struct egp_acq_hdr));

  /*
   * @nbrito -- Tue Jan 18 11:09:34 BRST 2011
   * XXX Have to work a little bit more deeply in packet building.
   * XXX Checking EGP Type and building appropriate header.
   */
  /* EGP Header structure making a pointer to Packet. */
  egp           = (struct egp_hdr *)((void *)(ip + 1) + greoptlen);
  egp->version  = EGPVERSION;
  egp->type     = co->egp.type;
  egp->code     = co->egp.code;
  egp->status   = co->egp.status;
  egp->as       = __RND(co->egp.as);
  egp->sequence = __RND(co->egp.sequence);
  egp->check    = 0;

  /* EGP Acquire Header structure. */
  egp_acq        = (struct egp_acq_hdr *)(egp + 1);
  egp_acq->hello = __RND(co->egp.hello);
  egp_acq->poll  = __RND(co->egp.poll);

  /* Computing the checksum. */
  egp->check    = co->bogus_csum ? RANDOM() :
                  cksum(egp, (void *)(egp_acq + 1) - (void *)egp);

  /* GRE Encapsulation takes place. */
  gre_checksum(packet, co, *size);
}
Пример #22
0
/**
 * Generate a message detailing the properties of 1-6 artifacts drawn
 * sequentially from the artifact list.
 * @param level Level of the book
 * @param buf Buffer to contain the description.
 * @param booksize Length of the book.
 * @return 'buf'. */
static char *artifact_msg(int level, char *buf, size_t booksize)
{
	artifactlist *al;
	artifact *art;
	int chance, i, type, index;
	int book_entries = level > 5 ? RANDOM () % 3 + RANDOM () % 3 + 2 : RANDOM () % level + 1;
	char *final, *ch;
	object *tmp = NULL;
	StringBuffer *desc;

	/* Values greater than 5 create msg buffers that are too big! */
	if (book_entries > 5)
	{
		book_entries = 5;
	}

	/* Let's determine what kind of artifact type randomly.
	 * Right now legal artifacts only come from those listed
	 * in art_name_array. Also, we check to be sure an artifactlist
	 * for that type exists! */
	i = 0;

	do
	{
		index = rndm(1, arraysize(art_name_array)) - 1;
		type = art_name_array[index].type;
		al = find_artifactlist(type);
		i++;
	}
	while (al == NULL && i < 10);

	/* Unable to find a message */
	if (i == 10)
	{
		snprintf(buf, booksize, "None");
		return buf;
	}

	/* There is no reason to start on the artifact list at the begining. Lets
	 * take our starting position randomly... */
	art = al->items;

	for (i = rndm(1, level) + rndm(0, 1); i > 0; i--)
	{
		/* Out of stuff, loop back around */
		if (art == NULL)
		{
			art = al->items;
		}

		art = art->next;
	}

	/* Ok, let's print out the contents */
	snprintf(buf, booksize, "<t t=\"Magical %s\">Herein %s detailed %s...\n", art_name_array[index].name, book_entries > 1 ? "are" : "is", book_entries > 1 ? "some artifacts" : "an artifact");

	/* Artifact msg attributes loop. Let's keep adding entries to the 'book'
	 * as long as we have space up to the allowed max # (book_entires) */
	while (book_entries > 0)
	{
		if (art == NULL)
		{
			art = al->items;
		}

		desc = stringbuffer_new();
		tmp = get_archetype(art->def_at_name);
		give_artifact_abilities(tmp, art);
		SET_FLAG(tmp, FLAG_IDENTIFIED);

		stringbuffer_append_printf(desc, "\n<t t=\"%s %s\">It is ", tmp->name, tmp->title ? tmp->title : "");

		/* Chance of finding. */
		chance = 100 * ((float) art->chance / al->total_chance);

		if (chance >= 20)
		{
			stringbuffer_append_string(desc, "an uncommon");
		}
		else if (chance >= 10)
		{
			stringbuffer_append_string(desc, "an unusual");
		}
		else if (chance >= 5)
		{
			stringbuffer_append_string(desc, "a rare");
		}
		else
		{
			stringbuffer_append_string(desc, "a very rare");
		}

		/* Value of artifact. */
		stringbuffer_append_printf(desc, " item with a value of %s.", cost_string_from_value(tmp->value));

		if ((ch = describe_item(tmp)) && strlen(ch) > 1)
		{
			stringbuffer_append_printf(desc, "\nProperties of this artifact include:\n %s", ch);
		}

		final = stringbuffer_finish(desc);

		/* Add the buf if it will fit. */
		if (book_overflow(buf, final, booksize))
		{
			free(final);
			break;
		}

		snprintf(buf + strlen(buf), booksize - strlen(buf), "%s", final);
		free(final);

		art = art->next;
		book_entries--;
	}
Пример #23
0
void
malloc_test(struct thread_st *st)
{
	int b, i, j, actions, pid = 1;
	struct bin_info p;
	struct lran2_st ld; /* data for random number generator */

	lran2_init(&ld, st->u.seed);
#if TEST_FORK>0
	if(RANDOM(&ld, TEST_FORK) == 0) {
		int status;

#if !USE_THR
		pid = fork();
#else
		pid = fork1();
#endif
		if(pid > 0) {
		    /*printf("forked, waiting for %d...\n", pid);*/
			waitpid(pid, &status, 0);
			printf("done with %d...\n", pid);
			if(!WIFEXITED(status)) {
				printf("child term with signal %d\n", WTERMSIG(status));
				exit(1);
			}
			return;
		}
		exit(0);
	}
#endif
	p.m = (struct bin *)malloc(st->u.bins*sizeof(*p.m));
	p.bins = st->u.bins;
	p.size = st->u.size;
	for(b=0; b<p.bins; b++) {
		p.m[b].size = 0;
		p.m[b].ptr = NULL;
		if(RANDOM(&ld, 2) == 0)
			bin_alloc(&p.m[b], RANDOM(&ld, p.size) + 1, lran2(&ld));
	}
	for(i=0; i<=st->u.max;) {
#if TEST > 1
		bin_test(&p);
#endif
		actions = RANDOM(&ld, ACTIONS_MAX);
#if USE_MALLOC && MALLOC_DEBUG
		if(actions < 2) { mallinfo(); }
#endif
		for(j=0; j<actions; j++) {
			b = RANDOM(&ld, p.bins);
			bin_free(&p.m[b]);
		}
		i += actions;
		actions = RANDOM(&ld, ACTIONS_MAX);
		for(j=0; j<actions; j++) {
			b = RANDOM(&ld, p.bins);
			bin_alloc(&p.m[b], RANDOM(&ld, p.size) + 1, lran2(&ld));
#if TEST > 2
			bin_test(&p);
#endif
		}
#if 0 /* Test illegal free()s while setting MALLOC_CHECK_ */
		for(j=0; j<8; j++) {
			b = RANDOM(&ld, p.bins);
			if(p.m[b].ptr) {
			  int offset = (RANDOM(&ld, 11) - 5)*8;
			  char *rogue = (char*)(p.m[b].ptr) + offset;
			  /*printf("p=%p rogue=%p\n", p.m[b].ptr, rogue);*/
			  free(rogue);
			}
		}
#endif
		i += actions;
	}
	for(b=0; b<p.bins; b++)
		bin_free(&p.m[b]);
	free(p.m);
	if(pid == 0)
		exit(0);
}
Пример #24
0
/**
 * Apply a potion.
 * @param op Object applying the potion.
 * @param tmp The potion.
 * @return 1 if the potion was successfully applied, 0 otherwise. */
int apply_potion(object *op, object *tmp)
{
	int i;

	/* some sanity checks */
	if (!op || !tmp || (op->type == PLAYER && (!CONTR(op) || !CONTR(op)->exp_ptr[EXP_MAGICAL] || !CONTR(op)->exp_ptr[EXP_WISDOM])))
	{
		LOG(llevBug,"apply_potion() called with invalid objects! obj: %s (%s - %s) tmp:%s\n", query_name(op, NULL), CONTR(op) ? query_name(CONTR(op)->exp_ptr[EXP_MAGICAL], NULL) : "<no contr>", CONTR(op) ? query_name(CONTR(op)->exp_ptr[EXP_WISDOM], NULL) : "<no contr>", query_name(tmp, NULL));
		return 0;
	}

	if (op->type == PLAYER)
	{
		/* set chosen_skill to "magic device" - thats used when we "use" a potion */
		if (!change_skill(op, SK_USE_MAGIC_ITEM))
		{
			/* no skill, no potion use (dust & balm too!) */
			return 0;
		}

		if (!QUERY_FLAG(tmp, FLAG_IDENTIFIED))
		{
			identify(tmp);
		}

		/* special potions. Only players get this */
		if (tmp->last_eat == -1)
		{
			/* create a force and copy the effects in */
			object *force = get_archetype("force");

			if (!force)
			{
				LOG(llevBug, "apply_potion: Can't create force object?\n");
				return 0;
			}

			force->type = POTION_EFFECT;
			/* or it will auto destroy with first tick */
			SET_FLAG(force, FLAG_IS_USED_UP);
			/* how long this force will stay */
			force->stats.food += tmp->stats.food;

			if (force->stats.food <= 0)
			{
				force->stats.food = 1;
			}

			/* negative effects because cursed or damned */
			if (QUERY_FLAG(tmp, FLAG_CURSED) || QUERY_FLAG(tmp, FLAG_DAMNED))
			{
				/* now we have a bit work because we change (multiply,...) the
				 * base values of the potion - that can invoke out of bounce
				 * values we must catch here. */

				/* effects stays 3 times longer */
				force->stats.food *= 3;

				for (i = 0; i < NROFATTACKS; i++)
				{
					int tmp_a;
					int tmp_p;

					tmp_a = tmp->attack[i] > 0 ? -tmp->attack[i] : tmp->attack[i];
					tmp_p = tmp->protection[i] > 0 ? -tmp->protection[i] : tmp->protection[i];

					/* double bad effect when damned */
					if (QUERY_FLAG(tmp, FLAG_DAMNED))
					{
						tmp_a *= 2;
						tmp_p *= 2;
					}

					/* we don't want out of bound values ... */
					if ((int) force->protection[i] + tmp_p > 100)
					{
						force->protection[i] = 100;
					}
					else if ((int) force->protection[i] + tmp_p < -100)
					{
						force->protection[i] = -100;
					}
					else
					{
						force->protection[i] += (sint8) tmp_p;
					}

					if ((int) force->attack[i] + tmp_a > 100)
					{
						force->attack[i] = 100;
					}
					else if ((int) force->attack[i] + tmp_a < 0)
					{
						force->attack[i] = 0;
					}
					else
					{
						force->attack[i] += tmp_a;
					}
				}

				insert_spell_effect("meffect_purple", op->map, op->x, op->y);
				play_sound_map(op->map, CMD_SOUND_EFFECT, "poison.ogg", op->x, op->y, 0, 0);
			}
			/* all positive (when not on default negative) */
			else
			{
				/* we don't must do the hard way like cursed/damned (no multiplication or
				 * sign change). */
				memcpy(force->protection, tmp->protection, sizeof(tmp->protection));
				memcpy(force->attack, tmp->attack, sizeof(tmp->attack));
				insert_spell_effect("meffect_green", op->map, op->x, op->y);
				play_sound_map(op->map, CMD_SOUND_EFFECT, "magic_default.ogg", op->x, op->y, 0, 0);
			}

			/* now copy stats values */
			force->stats.Str = QUERY_FLAG(tmp, FLAG_CURSED) ? (tmp->stats.Str > 0 ? -tmp->stats.Str : tmp->stats.Str) : (QUERY_FLAG(tmp, FLAG_DAMNED) ? (tmp->stats.Str > 0 ? (-tmp->stats.Str) * 2 : tmp->stats.Str * 2) : tmp->stats.Str);
			force->stats.Con = QUERY_FLAG(tmp, FLAG_CURSED) ? (tmp->stats.Con > 0 ? -tmp->stats.Con : tmp->stats.Con) : (QUERY_FLAG(tmp, FLAG_DAMNED) ? (tmp->stats.Con > 0 ? (-tmp->stats.Con) * 2 : tmp->stats.Con * 2) : tmp->stats.Con);
			force->stats.Dex = QUERY_FLAG(tmp, FLAG_CURSED) ? (tmp->stats.Dex > 0 ? -tmp->stats.Dex : tmp->stats.Dex) : (QUERY_FLAG(tmp, FLAG_DAMNED) ? (tmp->stats.Dex > 0 ? (-tmp->stats.Dex) * 2 : tmp->stats.Dex * 2) : tmp->stats.Dex);
			force->stats.Int = QUERY_FLAG(tmp, FLAG_CURSED) ? (tmp->stats.Int > 0 ? -tmp->stats.Int : tmp->stats.Int) : (QUERY_FLAG(tmp, FLAG_DAMNED) ? (tmp->stats.Int > 0 ? (-tmp->stats.Int) * 2 : tmp->stats.Int * 2) : tmp->stats.Int);
			force->stats.Wis = QUERY_FLAG(tmp, FLAG_CURSED) ? (tmp->stats.Wis > 0 ? -tmp->stats.Wis : tmp->stats.Wis) : (QUERY_FLAG(tmp, FLAG_DAMNED) ? (tmp->stats.Wis > 0 ? (-tmp->stats.Wis) * 2 : tmp->stats.Wis * 2) : tmp->stats.Wis);
			force->stats.Pow = QUERY_FLAG(tmp, FLAG_CURSED) ? (tmp->stats.Pow > 0 ? -tmp->stats.Pow : tmp->stats.Pow) : (QUERY_FLAG(tmp, FLAG_DAMNED) ? (tmp->stats.Pow > 0 ? (-tmp->stats.Pow) * 2 : tmp->stats.Pow * 2) : tmp->stats.Pow);
			force->stats.Cha = QUERY_FLAG(tmp, FLAG_CURSED) ? (tmp->stats.Cha > 0 ? -tmp->stats.Cha : tmp->stats.Cha) : (QUERY_FLAG(tmp, FLAG_DAMNED) ? (tmp->stats.Cha > 0 ? (-tmp->stats.Cha) * 2 : tmp->stats.Cha * 2) : tmp->stats.Cha);

			/* kick the force in, and apply it to player */
			force->speed_left = -1;
			force = insert_ob_in_ob(force, op);
			CLEAR_FLAG(tmp, FLAG_APPLIED);
			SET_FLAG(force, FLAG_APPLIED);

			/* implicit fix_player() here */
			if (!change_abil(op, force))
			{
				new_draw_info(NDI_UNIQUE, op, "Nothing happened.");
			}

			decrease_ob(tmp);
			return 1;
		}

		/* Potion of minor restoration */
		if (tmp->last_eat == 1)
		{
			object *depl;
			archetype *at;

			if (QUERY_FLAG(tmp, FLAG_CURSED) || QUERY_FLAG(tmp, FLAG_DAMNED))
			{
				if (QUERY_FLAG(tmp, FLAG_DAMNED))
				{
					drain_stat(op);
					drain_stat(op);
					drain_stat(op);
					drain_stat(op);
				}
				else
				{
					drain_stat(op);
					drain_stat(op);
				}

				fix_player(op);
				decrease_ob(tmp);
				insert_spell_effect("meffect_purple", op->map, op->x, op->y);
				play_sound_map(op->map, CMD_SOUND_EFFECT, "poison.ogg", op->x, op->y, 0, 0);
				return 1;
			}

			if ((at = find_archetype("depletion")) == NULL)
			{
				LOG(llevBug, "BUG: Could not find archetype depletion.");
				return 0;
			}

			depl = present_arch_in_ob(at, op);

			if (depl != NULL)
			{
				for (i = 0; i < NUM_STATS; i++)
				{
					if (get_attr_value(&depl->stats, i))
					{
						new_draw_info(NDI_UNIQUE, op, restore_msg[i]);
					}
				}

				/* in inventory of ... */
				remove_ob(depl);
				fix_player(op);
			}
			else
			{
				new_draw_info(NDI_UNIQUE, op, "You feel a great loss...");
			}

			decrease_ob(tmp);
			insert_spell_effect("meffect_green", op->map, op->x, op->y);
			play_sound_map(op->map, CMD_SOUND_EFFECT, "magic_default.ogg", op->x, op->y, 0, 0);
			return 1;
		}
		/* improvement potion */
		else if (tmp->last_eat == 2)
		{
			int success_flag = 0, hp_flag = 0, sp_flag = 0, grace_flag = 0;

			if (QUERY_FLAG(tmp, FLAG_CURSED) || QUERY_FLAG(tmp, FLAG_DAMNED))
			{
				/* jump in by random - goto power */
				if (RANDOM() % 2)
				{
					goto hp_jump;
				}
				else if (RANDOM() % 2)
				{
					goto sp_jump;
				}
				else
				{
					goto grace_jump;
				}

				while (!hp_flag || !sp_flag || !grace_flag)
				{
hp_jump:
					/* mark we have checked hp chain */
					hp_flag = 1;

					for (i = 2; i <= op->level; i++)
					{
						/* move one value to max */
						if (CONTR(op)->levhp[i] != 1)
						{
							CONTR(op)->levhp[i] = 1;
							success_flag = 2;
							goto improve_done;
						}
					}
sp_jump:
					/* mark we have checked sp chain */
					sp_flag = 1;

					for (i = 2; i <= CONTR(op)->exp_ptr[EXP_MAGICAL]->level; i++)
					{
						/* move one value to max */
						if (CONTR(op)->levsp[i] != 1)
						{
							CONTR(op)->levsp[i] = 1;
							success_flag = 2;
							goto improve_done;
						}
					}
grace_jump:
					/* mark we have checked grace chain */
					grace_flag = 1;

					for (i = 2; i <= CONTR(op)->exp_ptr[EXP_WISDOM]->level; i++)
					{
						/* move one value to max */
						if (CONTR(op)->levgrace[i] != 1)
						{
							CONTR(op)->levgrace[i] = 1;
							success_flag = 2;
							goto improve_done;
						}
					}
				}

				success_flag = 3;
			}
			else
			{
				/* jump in by random - goto power */
				if (RANDOM() % 2)
				{
					goto hp_jump2;
				}
				else if (RANDOM() % 2)
				{
					goto sp_jump2;
				}
				else
				{
					goto grace_jump2;
				}

				while (!hp_flag || !sp_flag || !grace_flag)
				{
hp_jump2:
					/* mark we have checked hp chain */
					hp_flag = 1;

					for (i = 1; i <= op->level; i++)
					{
						/* move one value to max */
						if (CONTR(op)->levhp[i] != (char) op->arch->clone.stats.maxhp)
						{
							CONTR(op)->levhp[i] = (char) op->arch->clone.stats.maxhp;
							success_flag = 1;
							goto improve_done;
						}
					}
sp_jump2:
					/* mark we have checked sp chain */
					sp_flag = 1;

					for (i = 1; i <= CONTR(op)->exp_ptr[EXP_MAGICAL]->level; i++)
					{
						/* move one value to max */
						if (CONTR(op)->levsp[i] != (char) op->arch->clone.stats.maxsp)
						{
							CONTR(op)->levsp[i] = (char) op->arch->clone.stats.maxsp;
							success_flag = 1;
							goto improve_done;
						}
					}
grace_jump2:
					/* mark we have checked grace chain */
					grace_flag = 1;

					for (i = 1; i <= CONTR(op)->exp_ptr[EXP_WISDOM]->level; i++)
					{
						/* move one value to max */
						if (CONTR(op)->levgrace[i] != (char) op->arch->clone.stats.maxgrace)
						{
							CONTR(op)->levgrace[i] = (char) op->arch->clone.stats.maxgrace;
							success_flag = 1;
							goto improve_done;
						}

					}
				}
			}

improve_done:
			CLEAR_FLAG(tmp, FLAG_APPLIED);

			if (!success_flag)
			{
				new_draw_info(NDI_UNIQUE, op, "The potion had no effect - you are already perfect.");
				play_sound_map(op->map, CMD_SOUND_EFFECT, "magic_default.ogg", op->x, op->y, 0, 0);
			}
			else if (success_flag == 1)
			{
				fix_player(op);
				insert_spell_effect("meffect_yellow", op->map, op->x, op->y);
				play_sound_map(op->map, CMD_SOUND_EFFECT, "magic_default.ogg", op->x, op->y, 0, 0);
				new_draw_info(NDI_UNIQUE, op, "You feel a little more perfect!");
			}
			else if (success_flag == 2)
			{
				fix_player(op);
				insert_spell_effect("meffect_purple", op->map, op->x, op->y);
				play_sound_map(op->map, CMD_SOUND_EFFECT, "poison.ogg", op->x, op->y, 0, 0);
				new_draw_info(NDI_UNIQUE, op, "The foul potion burns like fire in you!");
			}
			/* bad potion but all values of this player are 1! poor poor guy.... */
			else
			{
				insert_spell_effect("meffect_purple", op->map, op->x, op->y);
				play_sound_map(op->map, CMD_SOUND_EFFECT, "poison.ogg", op->x, op->y, 0, 0);
				new_draw_info(NDI_UNIQUE, op, "The potion was foul but had no effect on your tortured body.");
			}

			decrease_ob(tmp);
			return 1;
		}
	}

	if (tmp->stats.sp == SP_NO_SPELL)
	{
		new_draw_info(NDI_UNIQUE, op, "Nothing happens as you apply it.");
		decrease_ob(tmp);
		return 0;
	}

	/* A potion that casts a spell.  Healing, restore spellpoint (power
	 * potion) and heroism all fit into this category. */
	if (tmp->stats.sp != SP_NO_SPELL)
	{
		/* apply potion fires in player's facing direction, unless the spell is SELF one, ie, healing or cure ilness. */
		cast_spell(op, tmp, spells[tmp->stats.sp].flags & SPELL_DESC_SELF ? 0 : op->facing, tmp->stats.sp, 1, spellPotion, NULL);
		decrease_ob(tmp);

		/* if you're dead, no point in doing this... */
		if (!QUERY_FLAG(op, FLAG_REMOVED))
		{
			fix_player(op);
		}

		return 1;
	}

	/* CLEAR_FLAG is so that if the character has other potions
	 * that were grouped with the one consumed, his
	 * stat will not be raised by them.  fix_player just clears
	 * up all the stats. */
	CLEAR_FLAG(tmp, FLAG_APPLIED);
	fix_player(op);
	decrease_ob(tmp);
	return 1;
}
Пример #25
0
static
void
internal_adjust_next_event(struct NetKeepAlive *nka, int got_reply, int ct) {
	/* if we are in the comfort zone, 
	   apply minor_fuzz.
	   Otherwise, apply major_fuzz

	   If we are in the comfort zone and got no
	   reply, force us out of it.
	*/

	int i;
	struct timeval tv;
	float minor_minimum, major_minimum;

	i = RANDOM()&0x01;      /* positive or negative shift? */

	minor_minimum = KA_INITIAL_KEEPALIVE;
	major_minimum = (float) nka->maximal_keepalive * 0.75f;

	/* next_event = current_event * +/- factor */

	if (nka->current_keepalive >= major_minimum) {
			// we are in the comfort zone
			// did we get any reply?
			// if not, bump down outside the zone
			// also ensure that if we
		    // are stuck at either ends of the
		    // spectrum, we get out fast
#ifdef FAST_HANDOVER
		if (got_reply == 0 && ct > 1) 
				nka->current_keepalive = major_minimum - 1;
		else
#endif
		{
			float fuzz_factor;
			if (nka->current_keepalive == nka->maximal_keepalive)
				fuzz_factor = 1 - nka->minor_fuzz;
			else if (nka->current_keepalive == major_minimum)
				    fuzz_factor = 1 + nka->minor_fuzz; 
			else fuzz_factor = i ? (1 - nka->minor_fuzz) : (1 + nka->minor_fuzz);
			
			nka->current_keepalive = internal_trim((float)nka->current_keepalive * fuzz_factor,
				major_minimum, (float) nka->maximal_keepalive);
		}
	}

	/* else we are NOT in the comfort zone */
	if (nka->current_keepalive < major_minimum) {
		/* if we got_reply we go up, otherwise
		   we go down */
#ifdef FAST_HANDOVER
		float fuzz_factor;
		fuzz_factor = (ct < 2) ? (1 + nka->major_fuzz) : ( 1 - nka->major_fuzz);
#else
		float fuzz_factor = 1;
		if (ct < 2)
			fuzz_factor = 1 + nka->major_fuzz;
#endif
		nka->current_keepalive = internal_trim((float)nka->current_keepalive * fuzz_factor,
		minor_minimum, (float) nka->maximal_keepalive);
	}

	/* then put the next event in the timeval */

	GETTIMEOFDAY(&tv, NULL);

	nka->next_event.tv_sec  = tv.tv_sec + (int) nka->current_keepalive;
	nka->next_event.tv_usec = (long)( nka->current_keepalive - (int) nka->current_keepalive ) * 1000000;

	Display(LOG_LEVEL_3, ELInfo, "internal_adjust_next_event", HEX_STR_NEXT_KA_IN, nka->current_keepalive);

	return;
}
Пример #26
0
void clubmaster_driver(int cn,int ret,int lastact)
{
	struct clubmaster_driver_data *dat;
        int co,in,n,rank,cc,val;
        struct msg *msg,*next;
	char *ptr,tmp[80],name[80];

        dat=set_data(cn,DRD_CLUBMASTERDRIVER,sizeof(struct clubmaster_driver_data));
	if (!dat) return;	// oops...

        if (ch[cn].arg) {
                clubmaster_driver_parse(cn,dat);
		ch[cn].arg=NULL;
	}

        // loop through our messages
	for (msg=ch[cn].msg; msg; msg=next) {
		next=msg->next;

		// did we see someone?
		if (msg->type==NT_CHAR) {
			
                        co=msg->dat1;

			// dont talk to someone we cant see, and dont talk to ourself
			if (!char_see_char(cn,co) || cn==co) { remove_message(cn,msg); continue; }

			// dont talk to someone far away
			if (char_dist(cn,co)>10) { remove_message(cn,msg); continue; }

			// dont talk to the same person twice
			if (mem_check_driver(cn,co,7)) { remove_message(cn,msg); continue; }

			if (!get_char_club(cn) && !get_char_clan(cn)) quiet_say(cn,"Hello %s! Would you like to found a °c4club°c0?",ch[co].name);
			mem_add_driver(cn,co,7);
		}

                // talk back
		if (msg->type==NT_TEXT) {
			analyse_text_driver(cn,msg->dat1,(char*)msg->dat2,msg->dat3);

                        if ((msg->dat1==1 || msg->dat1==2) && (co=msg->dat3)!=cn) {	// talk, and not our talk				
                                if ((ptr=strcasestr((char*)msg->dat2,"found:"))) {
					if (!(ch[co].flags&CF_PAID)) {
						quiet_say(cn,"I'm sorry, %s, but only paying players may found clubs.",ch[co].name);
					} else if (!get_char_clan(co) && !get_char_club(co)) {
						if (ch[co].gold>=10000*100) {
							ptr+=6;
							while (isspace(*ptr)) ptr++;
							for (n=0; n<79; n++) {
								if (!(isalpha(*ptr) || *ptr==' ')) break;
								name[n]=*ptr++;
							}
							name[n]=0;
							
							if ((n=create_club(name))) {
								take_money(co,10000*100);
								ch[co].clan=n+CLUBOFFSET;
								ch[co].clan_serial=club[n].serial;
								ch[co].clan_rank=2;
								quiet_say(cn,"Congratulations, %s, you are now the leader of the club %s.",ch[co].name,club[n].name);
								dlog(co,0,"created club %d %s",n,club[n].name);
							} else quiet_say(cn,"Something's wrong with the name.");
						} else quiet_say(cn,"You cannot pay the fee of 10,000 gold.");
					} else quiet_say(cn,"You are already a member of a clan or club. You cannot found a new one.");
				}
				if ((ptr=strcasestr((char*)msg->dat2,"accept:"))) {
					if (!get_char_club(co) || ch[co].clan_rank<1) {
                                                quiet_say(cn,"You are not a club leader, %s.",ch[co].name);
					} else {
						ptr+=7;
						while (isspace(*ptr)) ptr++;
						for (n=0; n<79; n++) {
							if (!*ptr || *ptr=='"') break;
							dat->accept[n]=*ptr++;
						}
						dat->accept[n]=0;
						strcpy(dat->join,ch[co].name);
						dat->accept_clan=get_char_club(co);
						dat->accept_cn=co;

						quiet_say(cn,"To join %s's club %s, say: 'join: %s'",dat->join,dat->accept,dat->join);
					}
				}
				if ((ptr=strcasestr((char*)msg->dat2,"join:"))) {
					if (get_char_clan(co) || get_char_club(co)) {
                                                quiet_say(cn,"You are already a clan or club member, %s.",ch[co].name);
					} else {
						ptr+=5;
						while (isspace(*ptr)) ptr++;
						for (n=0; n<79; n++) {
							if (!*ptr || *ptr=='"') break;
							tmp[n]=*ptr++;
						}
						tmp[n]=0;
                                                if (strcasecmp(dat->accept,ch[co].name)) {
							quiet_say(cn,"You have not been invited, %s.",ch[co].name);
						} else if (strcasecmp(dat->join,tmp)) {
							quiet_say(cn,"%s has not invited you, %s.",tmp,ch[co].name);
						} else {
                                                        //add_member(co,dat->accept_clan,dat->join);
							ch[co].clan=dat->accept_clan+CLUBOFFSET;
							ch[co].clan_serial=club[dat->accept_clan].serial;
							ch[co].clan_rank=0;
							quiet_say(cn,"%s, you are now a member of %s's club.",ch[co].name,dat->join);
							dat->accept[0]=0;
							dat->accept_clan=0;
							dat->join[0]=0;
						}
						
					}
				}
				if ((ptr=strcasestr((char*)msg->dat2,"leave!"))) {
					if (!get_char_club(co)) {
                                                quiet_say(cn,"You are not a club member, %s.",ch[co].name);
					} else {
						remove_member(co,co);
						quiet_say(cn,"You are no longer a member of any club, %s",ch[co].name);
					}
				}
				if ((ptr=strcasestr((char*)msg->dat2,"rank:"))) {
					if (!get_char_club(co) || ch[co].clan_rank<2) {
                                                quiet_say(cn,"You are not a club founder, %s.",ch[co].name);
					} else {
						ptr+=6;
						while (isspace(*ptr)) ptr++;
						for (n=0; n<79; n++) {
							if (!*ptr || *ptr=='"' || isspace(*ptr)) break;
							tmp[n]=*ptr++;
						}
						tmp[n]=0;
						
						rank=atoi(ptr);

						if (rank<0 || rank>1) {
							quiet_say(cn,"You must use a rank between 0 and 1.");
							remove_message(cn,msg);
							continue;
						}

						for (cc=getfirst_char(); cc; cc=getnext_char(cc)) {
							if (!strcasecmp(tmp,ch[cc].name) && (ch[cc].flags&CF_PLAYER)) break;
						}
						if (cc) {
							if (!(ch[cc].flags&CF_PAID) && rank>0) {
                                                                quiet_say(cn,"%s is not a paying player, you cannot set the rank higher than 0.",ch[cc].name);
							} else if (ch[cc].clan_rank==2) {
								quiet_say(cn,"%s is the club's founder, cannot change rank.",ch[cc].name);
							} else if (get_char_club(cc)==get_char_club(co)) {
								ch[cc].clan_rank=rank;
								quiet_say(cn,"Set %s's rank to %d.",ch[cc].name,rank);
							} else quiet_say(cn,"You cannot change the rank of those not belonging to your club.");
						} else {
							int uID;

							uID=lookup_name(tmp,NULL);
							if (uID==0) continue;
							if (uID==-1) {
								quiet_say(cn,"Sorry, no player by the name %s found.",tmp);
							} else {
								task_set_clan_rank(uID,ch[co].ID,get_char_club(co)+CLUBOFFSET,rank,ch[co].name);
								quiet_say(cn,"Update scheduled (%s,%d).",tmp,rank);
							}
						}
					}
				}
				if ((ptr=strcasestr((char*)msg->dat2,"fire:"))) {
					if (!get_char_club(co) || ch[co].clan_rank<1) {
                                                quiet_say(cn,"You are not a club leader, %s.",ch[co].name);
					} else {
						ptr+=6;
						while (isspace(*ptr)) ptr++;
						for (n=0; n<79; n++) {
							if (!*ptr || *ptr=='"' || isspace(*ptr)) break;
							tmp[n]=*ptr++;
						}
						tmp[n]=0;
						
                                                for (cc=getfirst_char(); cc; cc=getnext_char(cc)) {
							if (!strcasecmp(tmp,ch[cc].name) && (ch[cc].flags&CF_PLAYER)) break;
						}
						if (cc) {
							if (get_char_club(cc)==get_char_club(co)) {
								if (ch[cc].clan_rank<2) {
									remove_member(cc,co);
									quiet_say(cn,"Fired: %s.",ch[cc].name);
								} else quiet_say(cn,"You cannot fire the founder of the club.");
							} else quiet_say(cn,"You cannot fire those not belonging to your club.");
						} else {
							int uID;

							uID=lookup_name(tmp,NULL);
							if (uID==0) continue;
							if (uID==-1) {
								quiet_say(cn,"Sorry, no player by the name %s found.",tmp);
							} else {
								task_fire_from_clan(uID,ch[co].ID,get_char_club(co)+CLUBOFFSET,ch[co].name);
								quiet_say(cn,"Update scheduled (%s).",tmp);
							}
						}
					}
				}

				if ((ptr=strcasestr((char*)msg->dat2,"deposit:"))) {
					if (!(n=get_char_club(co))) {
                                                quiet_say(cn,"You are not a club member, %s.",ch[co].name);
					} else {
						val=atoi(ptr+8)*100;

						if (val>0 && ch[co].gold>=val) {
							club[n].money+=val;
							take_money(co,val);
							quiet_say(cn,"You have deposited %dG, for a total of %dG, %s.",val/100,club[n].money/100,ch[co].name);
							dlog(co,0,"Deposited %dG into club %d, for a new total of %dG",val/100,n,club[n].money/100);
							db_update_club(n);
						} else quiet_say(cn,"You do not have that much gold, %s.",ch[co].name);
					}
				}
				if ((ptr=strcasestr((char*)msg->dat2,"withdraw:"))) {
					if (!(n=get_char_club(co)) || ch[co].clan_rank<2) {
                                                quiet_say(cn,"You are not a club founder, %s.",ch[co].name);
					} else {
						val=atoi(ptr+9)*100;

						if (val>0 && club[n].money>=val) {
							club[n].money-=val;
							give_money(co,val,"club withdrawal");
							quiet_say(cn,"You have withdrawn %dG, money left in club %dG, %s.",val/100,club[n].money/100,ch[co].name);
							dlog(co,0,"Withdrew %dG from club %d, for a new total of %dG",val/100,n,club[n].money/100);
							db_update_club(n);
						} else quiet_say(cn,"The club does not have that much gold, %s.",ch[co].name);
					}
				}
			}			
		}

		// got an item?
		if (msg->type==NT_GIVE) {
			co=msg->dat1;

                        if ((in=ch[cn].citem)) {	// we still have it
				// try to give it back
                                if (give_char_item(cn,co)) return;
				
				// didnt work, let it vanish, then
				destroy_item(ch[cn].citem);
				ch[cn].citem=0;
			}
		}
                remove_message(cn,msg);
	}

        // do something. whenever possible, call do_idle with as high a tick count
	// as reasonable when doing nothing.

	if (secure_move_driver(cn,ch[cn].tmpx,ch[cn].tmpy,dat->dir,ret,lastact)) return;

        if (ticker>dat->last_talk+TICKS*60 && !RANDOM(25)) {
		switch(RANDOM(8)) {
			case 0:		murmur(cn,"My back itches."); break;
			case 1:		whisper(cn,"There's something stuck between your teeth."); break;
			case 2:		murmur(cn,"Oh yeah, those were the days."); break;
			case 3:		murmur(cn,"Now where did I put it?"); break;
			case 4:		murmur(cn,"Oh my, life is hard but unfair."); break;
                        case 5:		murmur(cn,"Beware of the fire snails!"); break;
			case 6:         murmur(cn,"I love the clicking of coins."); break;
			case 7:		murmur(cn,"Gold and Silver, Silver and Gold."); break;
			default:	break;
		}
		
		dat->last_talk=ticker;
	}

	if (ticker>dat->memcleartimer) {
		mem_erase_driver(cn,7);
		dat->memcleartimer=ticker+TICKS*60*60*12;
	}

        do_idle(cn,TICKS*2);
}
Пример #27
0
/**
 * Op throws any object toss_item.
 * @param op Living thing throwing something.
 * @param toss_item Item thrown.
 * @param dir Direction to throw. */
void do_throw(object *op, object *toss_item, int dir)
{
	object *left_cont, *throw_ob = toss_item, *left = NULL, *tmp_op;
	tag_t left_tag;
	rv_vector range_vector;

	if (!throw_ob)
	{
		if (op->type == PLAYER)
		{
			new_draw_info(NDI_UNIQUE, op, "You have nothing to throw.");
		}

		return;
	}

	if (QUERY_FLAG(throw_ob, FLAG_STARTEQUIP))
	{
		if (op->type == PLAYER)
		{
			new_draw_info(NDI_UNIQUE, op, "The gods won't let you throw that.");
		}

		return;
	}

	if (throw_ob->weight <= 0)
	{
		new_draw_info_format(NDI_UNIQUE, op, "You can't throw %s.\n", query_base_name(throw_ob, NULL));
		return;
	}

	/* These are throwing objects left to the player */
	left = throw_ob;
	left_cont = left->env;
	left_tag = left->count;

	/* Sometimes get_split_ob can't split an object (because op->nrof==0?)
	 * and returns NULL. We must use 'left' then */
	if ((throw_ob = get_split_ob(throw_ob, 1, NULL, 0)) == NULL)
	{
		throw_ob = left;
		remove_ob(left);
		check_walk_off(left, NULL, MOVE_APPLY_VANISHED);

		if (op->type == PLAYER)
		{
			esrv_del_item(CONTR(op), left->count, left->env);
		}
	}
	else if (op->type == PLAYER)
	{
		if (was_destroyed(left, left_tag))
		{
			esrv_del_item(CONTR(op), left_tag, left_cont);
		}
		else
		{
			esrv_update_item(UPD_NROF, op, left);
		}
	}

	/* Special case: throwing powdery substances like dust, dirt */
	if (QUERY_FLAG(throw_ob, FLAG_DUST))
	{
		cast_dust(op, throw_ob, dir);

		/* update the shooting speed for the player action timer.
		 * We init the used skill with it - its not calculated here.
		 * cast_dust() can change the used skill... */
		if (op->type == PLAYER)
		{
			op->chosen_skill->stats.maxsp = throw_ob->last_grace;
		}

		return;
	}

	/* Targetting throwing */
	if (!dir && op->type == PLAYER && OBJECT_VALID(CONTR(op)->target_object, CONTR(op)->target_object_count))
	{
		dir = get_dir_to_target(op, CONTR(op)->target_object, &range_vector);
	}

	/* Three things here prevent a throw, you aimed at your feet, you
	 * have no effective throwing strength, or you threw at a wall */
	if (!dir || wall(op->map, op->x + freearr_x[dir], op->y + freearr_y[dir]))
	{
		/* Bounces off 'wall', and drops to feet */
		if (!QUERY_FLAG(throw_ob, FLAG_REMOVED))
		{
			remove_ob(throw_ob);

			if (check_walk_off(throw_ob, NULL, MOVE_APPLY_MOVE) != CHECK_WALK_OK)
			{
				return;
			}
		}

		throw_ob->x = op->x;
		throw_ob->y = op->y;

		if (!insert_ob_in_map(throw_ob, op->map, op, 0))
		{
			return;
		}

		if (op->type == PLAYER)
		{
			if (!dir)
			{
				new_draw_info_format(NDI_UNIQUE, op, "You drop %s at the ground.", query_name(throw_ob, NULL));
			}
			else
			{
				new_draw_info(NDI_UNIQUE, op, "Something is in the way.");
			}
		}

		return;
	}

	set_owner(throw_ob, op);
	set_owner(throw_ob->inv, op);
	throw_ob->direction = dir;
	throw_ob->x = op->x;
	throw_ob->y = op->y;

	/* Save original wc and dam */
	throw_ob->last_heal = throw_ob->stats.wc;
	throw_ob->stats.hp = throw_ob->stats.dam;

	/* Speed */
	throw_ob->speed = MIN(1.0f, (speed_bonus[op->stats.Str] + 1.0f) / 1.5f);

	/* Now we get the wc from the used skill. */
	if ((tmp_op = SK_skill(op)))
	{
		throw_ob->stats.wc += tmp_op->last_heal;
	}
	/* Monsters */
	else
	{
		throw_ob->stats.wc += 10;
	}

	throw_ob->stats.wc_range = op->stats.wc_range;

	if (QUERY_FLAG(throw_ob, FLAG_IS_THROWN))
	{
		throw_ob->stats.dam += throw_ob->magic;
		throw_ob->stats.wc += throw_ob->magic;

		/* Adjust for players */
		if (op->type == PLAYER)
		{
			op->chosen_skill->stats.maxsp = throw_ob->last_grace;
			throw_ob->stats.dam = FABS((int) ((float) (throw_ob->stats.dam + dam_bonus[op->stats.Str] / 2) * LEVEL_DAMAGE(SK_level(op))));
			throw_ob->stats.wc += thaco_bonus[op->stats.Dex] + SK_level(op);
		}
		else
		{
			throw_ob->stats.dam = FABS((int) ((float) (throw_ob->stats.dam) * LEVEL_DAMAGE(op->level)));
			throw_ob->stats.wc += 10 + op->level;
		}

		throw_ob->stats.grace = throw_ob->last_sp;
		throw_ob->stats.maxgrace = 60 + (RANDOM() % 12);

		/* Only throw objects get directional faces */
		if (GET_ANIM_ID(throw_ob) && NUM_ANIMATIONS(throw_ob))
		{
			SET_ANIMATION(throw_ob, (NUM_ANIMATIONS(throw_ob) / NUM_FACINGS(throw_ob)) * dir);
		}

		/* Adjust damage with item condition */
		throw_ob->stats.dam = (sint16) (((float) throw_ob->stats.dam / 100.0f) * (float) throw_ob->item_condition);
	}

	if (throw_ob->stats.dam < 0)
	{
		throw_ob->stats.dam = 0;
	}

	update_ob_speed(throw_ob);
	throw_ob->speed_left = 0;

	SET_MULTI_FLAG(throw_ob, FLAG_FLYING);
	SET_FLAG(throw_ob, FLAG_FLY_ON);
	SET_FLAG(throw_ob, FLAG_WALK_ON);

	play_sound_map(op->map, CMD_SOUND_EFFECT, "throw.ogg", op->x, op->y, 0, 0);

	/* Trigger the THROW event */
	trigger_event(EVENT_THROW, op, throw_ob, NULL, NULL, 0, 0, 0, SCRIPT_FIX_ACTIVATOR);

	if (insert_ob_in_map(throw_ob, op->map, op, 0))
	{
		move_arrow(throw_ob);
	}
}
Пример #28
0
void
mcp_basic_handler(McpFrame * mfr, McpMesg * mesg, void *dummy)
{
	McpVer myminver = { 2, 1 };
	McpVer mymaxver = { 2, 1 };
	McpVer minver = { 0, 0 };
	McpVer maxver = { 0, 0 };
	McpVer nullver = { 0, 0 };
	const char *ptr;
	const char *auth;

	if (!*mesg->mesgname) {
		auth = mcp_mesg_arg_getline(mesg, "authentication-key", 0);
		if (auth) {
			mfr->authkey = string_dup(auth);
		} else {
			McpMesg reply;
			char authval[128];

			mcp_mesg_init(&reply, MCP_INIT_PKG, "");
			mcp_mesg_arg_append(&reply, "version", "2.1");
			mcp_mesg_arg_append(&reply, "to", "2.1");
			snprintf(authval, sizeof(authval), "%.8lX", (unsigned long)(RANDOM() ^ RANDOM()));
			mcp_mesg_arg_append(&reply, "authentication-key", authval);
			mfr->authkey = string_dup(authval);
			mcp_frame_output_mesg(mfr, &reply);
			mcp_mesg_clear(&reply);
		}

		ptr = mcp_mesg_arg_getline(mesg, "version", 0);
		if (!ptr)
			return;
		while (isdigit(*ptr))
			minver.vermajor = (minver.vermajor * 10) + (*ptr++ - '0');
		if (*ptr++ != '.')
			return;
		while (isdigit(*ptr))
			minver.verminor = (minver.verminor * 10) + (*ptr++ - '0');

		ptr = mcp_mesg_arg_getline(mesg, "to", 0);
		if (!ptr) {
			maxver = minver;
		} else {
			while (isdigit(*ptr))
				maxver.vermajor = (maxver.vermajor * 10) + (*ptr++ - '0');
			if (*ptr++ != '.')
				return;
			while (isdigit(*ptr))
				maxver.verminor = (maxver.verminor * 10) + (*ptr++ - '0');
		}

		mfr->version = mcp_version_select(myminver, mymaxver, minver, maxver);
		if (mcp_version_compare(mfr->version, nullver)) {
			McpMesg cando;
			char verbuf[32];
			McpPkg *p = mcp_PackageList;

			mfr->enabled = 1;
			while (p) {
				if (strcmp_nocase(p->pkgname, MCP_INIT_PKG)) {
					mcp_mesg_init(&cando, MCP_NEGOTIATE_PKG, "can");
					mcp_mesg_arg_append(&cando, "package", p->pkgname);
					snprintf(verbuf, sizeof(verbuf), "%d.%d", p->minver.vermajor, p->minver.verminor);
					mcp_mesg_arg_append(&cando, "min-version", verbuf);
					snprintf(verbuf, sizeof(verbuf), "%d.%d", p->maxver.vermajor, p->maxver.verminor);
					mcp_mesg_arg_append(&cando, "max-version", verbuf);
					mcp_frame_output_mesg(mfr, &cando);
					mcp_mesg_clear(&cando);
				}
				p = p->next;
			}
			mcp_mesg_init(&cando, MCP_NEGOTIATE_PKG, "end");
			mcp_frame_output_mesg(mfr, &cando);
			mcp_mesg_clear(&cando);
		}
	}
}
Пример #29
0
float RandomFloat()
{
    float Max = RAND_MAX;
    return ((float)RANDOM() / Max);
}
Пример #30
0
long	ematrix_printmore_ext(ematrix *e, int lev, char *bto, int mx) {
	ematrix		**bas,**flt,**sep, **x, *ee,*xe;
	int		i,ii, j,jj,k,kk, a,ro,co, *li,*basi,**basii,
			 *orb=NULL,*orbx, *ses=NULL, bbm,bbl;
	long		hash = 0, *flts=NULL;
	
	if (bto)  bto[0] = 0;
	bbm = mx;  bbl=0;
	if (!e)  return -1;
	if (lev>0) if (ROWSM(e)*COLSM(e)>EM_MAXTOPRINTSQ || ROWSM(e)>EM_MAXTOPRINT || COLSM(e)>EM_MAXTOPRINT) {
		OUTPUT("Too big matroid for extended printing, sorry.\n");  return -1;
	}
	ee = ematrix_copy(e);
	ro = ROWSM(ee);  co = COLSM(ee);
	basi = MMALLOC(2*(ro+co+2)*sizeof(basi[0]));  li = basi+ro+co;
	basii = malloc_twodim(sizeof(basii[0][0]),ro+co,ro+co);
	for (i=0; i<ro+co; i++)  basi[i] = 0;
	for (i=0; i<ro+co; i++) for (ii=0; ii<ro+co; ii++)  basii[i][ii] = 0;
	flts = MMALLOC((ro+co+2)*sizeof(flts[0]));
	if (lev>0 && !bto)  SOUTPUT("\n");
	hash = ro+10*co;
	hash = 90909l*hash+111l*hash*hash*hash;

		/**
		 * Here we collect and print all bases - their total number, and numbers
		 * per elements (basi[]) and per element pairs (basii[][]).
		 * The bases are given as refering square submatrices of ee (not pivoted!).
		 * We add the numbers to the matroid hash value in a symmetric way.
		 *   ....... more to be added to the hash value - small flatlines???
		 * 
		 * The bases are also used later, and they are freed at the end.
		**/
	bas = ematrix_getbases_sq(ee);
	hash += alist_getlength(bas)*10101l;
	for (x=bas; x?*x:0; x++) {
		xe = ematrix_refextract_xrow(ee,*x);
		if (ROWSM(xe)+COLSM(xe)!=ro)  {PROGERROR("Something wrong with the basis size!");}
		for (i=0; i<ROWSM(xe); i++)
			li[i] = GETREFMROW(xe,i);
		for (i=0; i<COLSM(xe); i++)
			li[i+ROWSM(xe)] = GETREFMCOL(xe,i)+ro;
		for (i=0; i<ro; i++) {
			basi[li[i]]++;
			for (ii=0; ii<ro; ii++)  basii[li[i]][li[ii]]++;
		}
		dispose_ematrix(xe);
	}
	for (i=0; i<ro+co; i++) {
		hash += 505l*basi[i]+7l*basi[i]*basi[i];
		for (ii=0; ii<i; ii++)  hash += 13l*basii[i][ii]+1l*basii[i][ii]*basii[i][ii];
		if (basii[i][ii]!=basii[ii][i])  {PROGERROR("Something wrong - nonsymmetric basis pairs!");}
	}
	//************* adding small flatlines to the hash value? - here, not below, since the element
	//		magic below is slow to compute and not computed always(!)
	
	if (lev>=0) {
		if (!bto)  OUTPUT("Number of matroid [%.25s] bases:  %d\n",EMNAME(e)?EMNAME(e):"",alist_getlength(bas));
		else  SNPRINTF(bto,bbl,bbm,"Matroid  %d x %d [%.25s],  %d bases.\n",ro,co,EMNAME(e)?EMNAME(e):"",alist_getlength(bas));
	}
	if (lev>0 && !bto) {
		OUTPUT("  - per elements ");
		for (i=0; i<ro+co; i++)  SOUTPUT(" [%d: %d]%s",LIID(ee,i),basi[i],i%6==5?"\n\t\t\t":"");
		SOUTPUT("\n");
	}
	if (lev>4 && !bto) {
		SOUTPUT("\n");  OUTPUT("  - per element pairs\n");
		for (i=0,a=1; i<ro+co; i++) {
			if (a)  SOUTPUT("    ~\t ");  a = 0;
			for (ii=0; ii<ro+co; ii++)  if (basii[i][ii]>0) {
				a = 1;
				SOUTPUT("[%2d'%2d: %-3d]",LIID(ee,i),LIID(ee,ii),basii[i][ii]);
			}
			if (a)  SOUTPUT("\n");
		}
	}
		/**
		 * Here we (try to) distinguish matroid elements up to isomorphism.
		 * We either compute "magic values" for the elements - faster,
		 * or we rigorously compute the orbits of the automorphism group.
		 * For the orbits, we use the numbers of bases in basi[] and the
		 * flatline values flts[] for rough distinction, and then we use
		 * strmag_isautmap() to see which pairs of elements are really
		 * mapped to each other by the aut group.
		**/
	if (lev>0) {
		strmag_flatlines_pr(ee,flts);	/* (flts[] is globally allocated) */
		for (i=0; i<ro+co; i++)  flts[i] += 7*basi[i];
	}
	if (lev>0 && lev<=2 && !bto) {
		OUTPUT("  - elem magic ");
		for (i=0; i<ro+co; i++)  SOUTPUT(" [%d: %ld]%s",LIID(ee,i),flts[i],i%6==5?"\n\t\t\t":"");
		SOUTPUT("\n");
	}	
	if (lev>2 && ro>0) {
		if (ro+co>6)  DEBUG(CURDLEV-3,"Warning - aut orbit computation may take very long.\n");
		if (!bto)  OUTPUT("Aut group orbits of [%.25s] are (via first elem id):\n",EMNAME(e)?EMNAME(e):"");
		else  SNPRINTF(bto,bbl,bbm,"Aut group orbits ");
		if (ematrix_checkid(ee)<0 && !bto) {
			ematrix_resetid(ee);  SOUTPUT("\t\tResetting line id's in the matrix!!!\n");
		}
		orb = MMALLOC(2*(ro+co+2)*sizeof(orb[0]));
		orbx = orb+(ro+co+1);
		for (i=0; i<ro+co; i++)  orbx[i] = 1;
		if (!bto) {
			for (i=0; i<ro; i++)  orb[i] = ROWSID(ee,i);
			for (i=ro; i<ro+co; i++)  orb[i] = COLSID(ee,i-ro);
		} else  for (i=0; i<ro+co; i++)  orb[i] = i;
			/* (we print elem ids on output, but their indices to bto...) */
		if (!bto)  SOUTPUT("\t\t(%d",orb[0]);
		else  SNPRINTF(bto,bbl,bbm,"[%d",orb[0]);
		kk = ro+co;
		for (i=1; i<ro+co; i++) {
			for (j=0; j<i; j++) if (orbx[j]) {
				if (basi[i]!=basi[j] || flts[i]!=flts[j])  continue;
				//********** may we efficiently use basii[][] here???
				if (!strmag_isautmap_h(e,i,j,flts))  continue;
				orb[i] = orb[j];  orbx[i] = 0;  kk--;
			}
			if (!bto)  SOUTPUT(",%s %d",i==ro?" ":"",orb[i]);
			else  SNPRINTF(bto,bbl,bbm,",%s %d",i==ro?" ":"",orb[i]);
		}
		if (!bto)  SOUTPUT(") =%d\n",kk);
		else  SNPRINTF(bto,bbl,bbm,"] %d.\n",kk);
		FREE(orb);
	}
		/**
		 * Here we list all nontrivial flats of the matroid up to rank
		 * depending on lev, or up to the first flats found.
		 * See also ematrix_printmore_flats() below.
		 * (We currently do not use information about the printed flats
		 * in the matroid hash-value since the flats are expensive to compute.
		 * Also, the flat comp implementation works only for bounded size!)
		**/
	ematrix_printmore_flats(NULL,0,1);
	if (lev>0)
	  for (k=0,a=1; k<lev+a && k<ro; k++) {
		flt = ematrix_submatrices_sub(ee,k);
		for (x=flt,i=0; x?*x:0; x++) {
			xe = ematrix_closure(ee,*x);
			kk = ematrix_setrank(ee,xe);
			if (kk>k)  {PROGERROR("something wrong with the flat rank %d>%d",kk,k);}
			if (ROWSM(xe)+COLSM(xe)>k && k==kk)
			  if (ematrix_printmore_flats(xe,k,0)>=0) {
				if (i==0 && lev>1 && !bto)  SOUTPUT("\n");
				if (i==0 && !bto)  OUTPUT("Listing all (nontrivial) flats in [%.25s] of rank %d:\n",
							EMNAME(e)?EMNAME(e):"",k);
				if (i==0 && bto)  SNPRINTF(bto,bbl,bbm,"Flats of rank %d:",k);
				i++;
				if (i%5==0 && bto)  SNPRINTF(bto,bbl,bbm,"\n");
				if (!bto) {
				  SOUTPUT("    ~\t - rank-%d flat (%d)\t{",k,i);
				  for (j=0; j<ROWSM(xe); j++)  SOUTPUT(" %d,",ROWSID(xe,j));
				  for (j=0; j<COLSM(xe); j++)  SOUTPUT("%c %d",!j?' ':',',COLSID(xe,j));
				  SOUTPUT(" }\n");
				} else {
				  SNPRINTF(bto,bbl,bbm,"  %df{",i);
				  for (j=0; j<ROWSM(xe); j++)  SNPRINTF(bto,bbl,bbm,"%d,",GETREFMROW(xe,j));
				  for (j=0; j<COLSM(xe); j++)  SNPRINTF(bto,bbl,bbm,"%c%d",!j?' ':',',GETREFMCOL(xe,j)+ro);
				  SNPRINTF(bto,bbl,bbm,"}");
				}
			}
			dispose_ematrix(xe);
		}
		if (i==0 && k==0 && lev>1 && !bto)  SOUTPUT("\n");
		if (i==0 && !bto)  OUTPUT("There are -NO- (nontrivial) flats in [%.25s] of rank %d.\n",EMNAME(e)?EMNAME(e):"",k);
		if (i>0 && bto)  SNPRINTF(bto,bbl,bbm,"\n");
		if (flt)  dispose_alist_mats(flt);
		if (i!=0 && bto && k>=3)  break;
		if (i==0 && k>0)  a++;
	}
	ematrix_printmore_flats(NULL,0,-1);
	
		/**
		 * Here we list all nontrivial separations of the matroid up to lambda
		 * depending on lev, or up to the first separations found.
		 * (We currently do not use these information in the hash-value.)
		**/
	if (lev>1 && !bto) {
		sep = ematrix_submatrices_all(ee);
		ii = sep? alist_getlength(sep):0;
		ses = MMALLOC((ii+2)*sizeof(ses[0]));
		for (x=sep; x?*x:0; x++)
			ses[x-sep] = ematrix_whatsep(ee,*x);
		for (k=0,a=-1; k<lev+a && k<ro; k++) {
			for (jj=i=0; jj<ii; jj++) if (ses[jj]==k) {
				xe = sep[jj];
				if (ROWSM(xe)+COLSM(xe)<=k || ROWSM(xe)+COLSM(xe)>(ro+co)/2)
					continue;
				if (i==0 && lev>1)  SOUTPUT("\n");
				if (i==0)  OUTPUT("Listing all exact separations in [%.25s] of lambda %d:\n",
							EMNAME(e)?EMNAME(e):"",k+1);
				SOUTPUT("    ~\t - %d-separation (%d)\t(",k+1,++i);
				for (j=0; j<ROWSM(xe); j++)  SOUTPUT(" %d,",ROWSID(xe,j));
				SOUTPUT(" ");
				for (j=0; j<COLSM(xe); j++)  SOUTPUT(" %d,",COLSID(xe,j));
				SOUTPUT(" )\n");
			}
			if (i==0 && k==0)  SOUTPUT("\n");
			if (i==0)  OUTPUT("There are -NO- exact separations in [%.25s] of lambda %d.\n",EMNAME(e)?EMNAME(e):"",k+1);
			if (i==0 && k>0)  a++;
		}
		if (sep)  dispose_alist_mats(sep);
		FREE(ses);
	}
	
#ifndef FASTPROG		/* paranoic testing of the hash-value computation: */
	if (lev>=0 && IFRANDDEBUGLESS(111)) {
		for (ii=0; ii<4; ii++) {	/* extra testing hash with pivoted matrix */
			i = RANDOM()%ROWSM(ee);  j = RANDOM()%COLSM(ee);
			if (SIGNM(ee,i,j)!=0)  ematrix_pivot(ee,i,j);
		}
		if (hash!=ematrix_printmore_ext(ee,-1,NULL,0))  {PROGERROR("incorrect computation of matroid hash, ret=%ld",hash);}
	}		/* (ee is modified here !!!) */
#endif
	if (bas)  dispose_alist_mats(bas);
	if (flts)  FREE(flts);
	if (basi)  FREE(basi);	if (basii)  FREE(basii);
	
		/**
		 * Some other final characteristics are printed here.
		 * Representability is surveyed for some basic fields, depending on lev.
		 * Among them the matroid hash-value is printed out and always returned.
		 * So far, the matroid hash-value collects information about rank,
		 * number of bases, numbers of bases per each element and each pair of elements.
		 * You must update the version number if you change the collected information!
		**/
	if (lev>0 && !bto) {
		SOUTPUT("\n");  k = 0;
		OUTPUT("Matroid [%.25s] connectivity is %d",
				EMNAME(e)?EMNAME(e):"",kk=struct_iconnectivity(e,&k));
		if (kk==3 && k)  SOUTPUT(" (internally %d-connected).\n",kk+1);
		else  SOUTPUT(".\n");
		OUTPUT("Matroid [%.25s] girth (shortest cycle) is %d.\n",
				EMNAME(e)?EMNAME(e):"",struct_matgirth(e));
	}
	if (lev>0 && bto) {
		SNPRINTF(bto,bbl,bbm,"Connectivity  %d, girth (shortest cycle)  %d.\n",
				struct_connectivity(e),struct_matgirth(e));
	}
	if (lev>2) {
		char	*xx_fields[] = {"GF(2)","GF(3)","GF(4)","GF(5)","GF(7)","GF(8)","GF(9)"};
		if (!bto)  OUTPUT("Matroid [%.25s] representability:",EMNAME(e)?EMNAME(e):"");
		else  SNPRINTF(bto,bbl,bbm,"Representability over:");
		for (j=0; j<(int)(sizeof(xx_fields)/sizeof(xx_fields[0])); j++) {
			ii = pfield_curindex();
			pfield_switchto(xx_fields[j]);	/* (we expect all the fields defined!) */
			a = grepr_isrepresented(ee,ii)>0;
			if (!bto)  SOUTPUT(" %c%s%c",a?'+':'-',xx_fields[j],a?'+':'-');
			else  SNPRINTF(bto,bbl,bbm," %c%s%c",a?'+':'-',xx_fields[j],a?'+':'-');
			pfield_switchto_fast(ii);
		}
		if (!bto)  SOUTPUT("\n\n");  else  SNPRINTF(bto,bbl,bbm,"\n");
	}
	if (lev>=0 && !bto)  OUTPUT("Overall matroid [%.25s] hash-value (version %s):  %ld\n",
					EMNAME(e)?EMNAME(e):"",EM_HASHVER,hash);
	dispose_ematrix(ee);
	return hash;
}