Exemplo n.º 1
0
void do_meta_infect(int who, planettype *p)
{
    int owner, x, y;

    getsmap(Smap, p);
    PermuteSects(p);
    bzero((char *)Sectinfo, sizeof(Sectinfo));
    x = int_rand(0, p->Maxx-1);
    y = int_rand(0, p->Maxy-1);
    owner = Sector(*p, x, y).owner;
    if(!owner || (who!=owner && (double)int_rand(1,100) >
                  100.0*(1.0-exp(-((double)(Sector(*p,x,y).troops*
                                            races[owner-1]->fighters/50.0)))))) {
        p->info[who-1].explored = 1;
        p->info[who-1].numsectsowned += 1;
        Sector(*p, x, y).troops = 0;
        Sector(*p, x, y).popn = races[who-1]->number_sexes;
        Sector(*p, x, y).owner = who;
        Sector(*p, x, y).condition = Sector(*p, x, y).type;
#ifdef POD_TERRAFORM
        Sector(*p, x, y).condition = races[who-1]->likesbest;
#endif
        putsmap(Smap, p);
    }
}
Exemplo n.º 2
0
int seleccionar_valor_parametro(int parametro)
{
  int valor_parametro;
  int valor_minimo, valor_maximo;
  int pos = int_rand(0, N); //entre 0 y N-1
  
  rangos(&valor_minimo, &valor_maximo, pos, parametro);
  valor_parametro = int_rand(valor_minimo, (valor_maximo+1));
  return valor_parametro;
}
Exemplo n.º 3
0
/* Make a random list of sectors. */
void PermuteSects(planettype *planet)
{
    int i;
    int j;
    int x;
    int y;
    int t;
    struct map sw;

    t = planet->Maxy * planet->Maxx;

    y = 0;
    x = 0;

    for (i = x; i < t; ++i) {
        xymap[i].x = x;
        xymap[i].y = y;
        ++x;

        if (x >= planet->Maxx) {
            x = 0;
            ++y;
        }
    }

    for (i = 0; i < t; ++i) {
        sw = xymap[i];
        j = int_rand(0, t - 1);
        xymap[i] = xymap[j];
        xymap[j] = sw;
    }
}
Exemplo n.º 4
0
void do_pod(shiptype *ship)
{
    reg int i;

    if(ship->whatorbits==LEVEL_STAR) {
        if (ship->special.pod.temperature >= POD_THRESHOLD) {
            i = int_rand(0,(int)Stars[ship->storbits]->numplanets - 1);
            sprintf(telegram_buf, "%s has warmed and exploded at %s\n",
                    Ship(ship), prin_ship_orbits(ship));
            if(infect_planet((int)ship->owner, (int)ship->storbits, i)) {
                sprintf(buf,"\tmeta-colony established on %s.",
                        Stars[ship->storbits]->pnames[i]);
            } else
                sprintf(buf,"\tno spores have survived.");
            strcat(telegram_buf, buf);
            push_telegram((int)(ship->owner), (int)ship->governor, telegram_buf);
            kill_ship((int)(ship->owner), ship);
        } else
            ship->special.pod.temperature +=
                round_rand((double)Stars[ship->storbits]->temperature/
                           (double)segments);
    } else if(ship->whatorbits==LEVEL_PLAN) {
        if(ship->special.pod.decay >= POD_DECAY) {
            sprintf(telegram_buf, "%s has decayed at %s\n", Ship(ship),
                    prin_ship_orbits(ship));
            push_telegram((int)ship->owner, (int)ship->governor, telegram_buf);
            kill_ship((int)ship->owner, ship);
        } else {
            ship->special.pod.decay += round_rand(1.0/(double)segments);
        }
    }
}
Exemplo n.º 5
0
Arquivo: xaw_c.c Projeto: 1c0n/xbmc
static void shuffle(int n,int *a) {
  int i,j,tmp;

  for (i=0;i<n;i++) {
    j=int_rand(n);
    tmp=a[i];
    a[i]=a[j];
    a[j]=tmp;
  }
}
Exemplo n.º 6
0
void place_star(startype *star)
{
    int found = 0;
    int i;
    int j;
    /*
     * -mfw
     */
    /*
     * double xfac;
     * double yfac;
     * double zfac;
     */

    while (!found) {
        star->xpos = (double)int_rand(-UNIVSIZE, UNIVSIZE);
        star->ypos = (double)int_rand(-UNIVSIZE, UNIVSIZE);

        /*
         * Let's try a more interesting algorithm -mfw
         */
        /*
         * xfac = M_PI / UNIVSIZE;
         * star->xpos = (double)int_rand(-UNIV_SIZE, UNIVSIZE);
         * yfac = xfac * star->xpos;
         * zfac = sin(yfac);
         * star->ypos = zfac * UNIVSIZE;
         * printf("x: %lf, y: %lf, z: %lf\n", xfac, yfac, zfac);
         */

        /*
         * Check to see if another star is nearby
         */
        i = 100 * ((int)star->xpos + UNIVSIZE) / (2 * UNIVSIZE);
        j = 100 * ((int)star->ypos + UNIVSIZE) / (2 * UNIVSIZE);

        if (!occupied[i][j]) {
            found = 1;
            occupied[i][j] = found;
        }
    }
}
Exemplo n.º 7
0
void randomize_string_list(char **strlist, int n)
{
    int i, j;
    char *tmp;
    for(i = 0; i < n; i++)
    {
	j = int_rand(n - i);
	tmp = strlist[j];
	strlist[j] = strlist[n - i - 1];
	strlist[n - i - 1] = tmp;
    }
}
Exemplo n.º 8
0
int w32g_random_playlist(int skip_invalid_file)
{
	int old_selected_index = playlist.selected;
	int select;
	int err = 0;
	for(;;) {
		if ( playlist.nfiles == 1) {
			select = old_selected_index;
		} else {
			if ( playlist.nfiles <= 1 )
				select = 0;
			else if ( playlist.nfiles == 2 )
				select = 1;
			else
				select = int_rand(playlist.nfiles - 1);
			select += old_selected_index;
			if ( select >= playlist.nfiles )
				select -= playlist.nfiles;
			if ( select < 0 )
				select = 0;
		}
		playlist.selected = select; 
		if(!skip_invalid_file ||
			playlist.list[playlist.selected].info->file_type != IS_ERROR_FILE) {
			w32g_update_playlist();
			return 1;
		}
		if ( playlist.nfiles == 2 ) {
			playlist.selected = old_selected_index; 
			if(!skip_invalid_file ||
				playlist.list[playlist.selected].info->file_type != IS_ERROR_FILE) {
				w32g_update_playlist();
				return 1;
			}
		}
		// for safety.
		if (playlist.selected == old_selected_index)
			break;
		err++;
		if (err > playlist.nfiles + 10)
			break;
	}
  return 0;
}
Exemplo n.º 9
0
void crear_conjunto_calibraciones_inicial(int tamano)
{
  int nacimiento = 0;
  for(int i=0; i < tamano; i++)
    {
      calibracion calibracion_temp;
      calibracion_temp.parametro = new (int[cantidad_parametros]);
      cout<<"(calibracion "<<i<<") ";
      for(int i = 0; i< cantidad_parametros; i++)
	{
	  calibracion_temp.parametro[i] = int_rand(configuracion_parametros[i].limite_minimo, (configuracion_parametros[i].limite_maximo+1));//Incluyendo el valor de limite maximo
	  cout<<calibracion_temp.parametro[i]<< " ";
	}
      cout<<endl;
      calibracion_temp.nacimiento = nacimiento;
      calcular_aptitud_calibracion(&calibracion_temp);
      //Se agrega al conjunto de calibraciones
      conjunto_calibraciones.push_back(calibracion_temp);
    }
  return;
}
Exemplo n.º 10
0
int w32g_shuffle_playlist_next(int skip_invalid_file)
{
	if ( !playlist_shuffle_init ) {
		if ( !w32g_shuffle_playlist_reset(0) )
			return 0;
	}
	for ( playlist_shuffle.cur ++ ; playlist_shuffle.cur < playlist_shuffle.max; playlist_shuffle.cur ++ ) {
		int n = int_rand(playlist_shuffle.max - playlist_shuffle.cur) + playlist_shuffle.cur;
		int temp = playlist_shuffle.list[playlist_shuffle.cur];
		if ( n > playlist_shuffle.max ) n = playlist_shuffle.max;
		playlist_shuffle.list[playlist_shuffle.cur] = playlist_shuffle.list[n];
		playlist_shuffle.list[n] = temp;
		if ( playlist_shuffle.list[playlist_shuffle.cur] < playlist.nfiles ) {
			playlist.selected = playlist_shuffle.list[playlist_shuffle.cur];
			if(!skip_invalid_file ||
				playlist.list[playlist.selected].info->file_type != IS_ERROR_FILE) {
				w32g_update_playlist();
				return 1;
			}
		}
	}
    return 0;
}
Exemplo n.º 11
0
/* Función del proceso productor */
void
producer(void)
{
	int item;
	int items = ITEMS;

	/* Ciclo para escritura de cada elemento */
	while (items--)
	{
		/* Genero el item */
		item = int_rand(ITEM_MAX, ITEM_MIN);
		/* Decremento la cantidad de casilleros vacios.
		 * Si lo logro es porque habia espacio. */
		sem_wait(&s_empty);

		printf("PRODUCTOR: Creo item.\n");
		sleep(P_BETWEEN);

		/* Incremento la cantidad de casilleros llenos */
		sem_post(&s_full);
	}
	
	printf("PRODUCTOR: Me muero\n");
}
Exemplo n.º 12
0
void do_meta_infect(int who, planettype *p)
{
    int owner;
    int x;
    int y;
    double military;
    int converted_civilians;
    int unconverted_civilians;

    getsmap(Smap, p);
    PermuteSects(p);
    memset((char *)Sectinfo, 0, sizeof(Sectinfo));
    x = int_rand(0, p->Maxx - 1);
    y = int_rand(0, p->Maxy - 1);
    owner = Sector(*p, x, y).owner;

    /*
     * HUTm Kharush converting existing civilians are back! Constants are in
     * hdrs/tweakables.h
     */
    if (!owner) {
        p->info[who - 1].explored = 1;
        p->info[who - 1].numsectsowned += 1;
        Sector(*p, x, y).popn = races[who - 1]->number_sexes;
        Sector(*p, x, y).owner = who;
        Sector(*p, x, y).condition = sector(*p, x, y).type;

#ifdef POD_TERRAFORM
        Sector(*p, x, y).condition = races[who - 1]->likesbest;
#endif

        putsmap(Smap, p);
    } else if (who != owner) {
        military = (double)Sector(*p, x, y).troops;

        converted_civilians = races[who - 1]->number_sexes + ((int)((double)Sector(*p, x, y).popn) * ABSORB_RATE * pow((MILITARY_PROPORTION * military) / ((MILITARY_PROPORTION * military) + (double)Sector(*p, x, y).popn), MILITARY_WEIGHT));

        unconverted_civilians = Sector(*p, x, y).popn - converted_civilians + races[who - 1]->number_sexes;

        if ((military * (double)races[owner - 1]->fighters * 10.0) >= ((double)converted_civilians * (double)races[who - 1]->fighters)) {
            /* Military wins */
            military -= (((double)converted_civilians * (double)races[who - 1]->fighters) / ((double)races[owner - 1]->fighters * 10.0));

            if (military < 1.0) {
                military = 0.0;
            }

            Sector(*p, x, y).troops = (int)military;
            Sector(*p, x, y).popn = unconverted_civilians;

            /* No survivors */
            if (!military && !unconverted_civilians) {
                Sector(*p, x, y).owner = 0;

                if (p->info[owner - 1].numsectsowned) {
                    p->info[owner - 1].numsectsowned -= 1;
                }
            }

            putsmap(Smap, p);
        } else {
            /* Podder wins */
            converted_civilians -= (int)((military * (double)races[owner - 1]->fighters * 10.0) / (double)races[who - 1]->fighters);

            if (converted_civilians < 1) {
                converted_civilians = 0;
            }

            Sector(*p, x, y).troops = 0;
            Sector(*p, x, y).popn = converted_civilians;

            if (p->info[owner - 1].numsectsowned) {
                p->info[owner - 1].numsectsowned -= 1;
            }

            /* No survivors */
            if (!converted_civilians) {
                Sector(*p, x, y).owner = 0;
            } else {
                p->info[who - 1].explored = 1;
                p->info[who - 1].numsectsowned += 1;
                Sector(*p, x, y).owner = who;
                Sector(*p, x, y).condition = Sector(*p, x, y).type;

#ifdef POD_TERRAFORM
                Sector(*p, x, y).condition = races[who - 1]->likesbest;

#endif
            }

            putsmap(Smap, p);
        }
    }

    /*
     * Old code starts
     *
     *     if (!owner
     *         || ((who != owner)
     *             && ((double)int_rand(1, 100) > (100.0 * (1.0 - exp(-(double)((Sector(*p, x, y).troops * races[owner - 1]->fighters) / 50.0))))))) {
     *         p->info[who - 1].explored = 1;
     *         p->info[who - 1].numsectsowned += 1;
     *         Sector(*p, x, y).troops = 0;
     *         Sector(*p, x, y).popn = races[who - 1]->number_sexes;
     *         Sector(*p, x, y).owner = who;
     *         Sector(*p, x, y).condition = Sector(*p, x, y).type;

     * #ifdef POD_TERRAFORM
     *         Sector(*p, x, y).condition = races[who - 1]->likesbest;
     * #endif

     *         putsmap(Smap, p);
     *     }
     *
     * Old code ends
     */
}
Exemplo n.º 13
0
/*
  Creates a file containing iterat * numPatterns patterns.
  Patterns from       0 <= i < numPatterns are not repeated 
  				numPatterns	<= i < 2*numPatterns		...are not repeated 
*/
void generateFile(int iterat, int numPatterns, char *preffix ) {
		unsigned int *chosenPos;

		unsigned int i,z;
		unsigned int pos;
		unsigned int iterActual =1;
				
		FILE *fout;
		char outFile[100];
		char tmp[10];

		chosenPos = (unsigned int *) malloc(1*4*numPatterns);

		outFile[0]='\0';
		strcat(outFile,"./tmp/");
		strcat(outFile,preffix);
		strcat(outFile,"_");
		sprintf(tmp,"Iter%ld_",(long)iterat);
		strcat(outFile,tmp);
		sprintf(tmp,"Pats%ld", (long)numPatterns);
		strcat(outFile,tmp);
		
		remove(outFile);
		
		if ((fout = fopen(outFile,"w")) == NULL){
		  fprintf(stderr,
			  "Error en la apertura del fichero %s\n",
			  "frequencias,txt");
		  exit(0);
		}		

		outputNumPatterns(fout, iterat);

		// MAIN LOOP OF CHOOSNING RND PATTERNS******************
		
		fprintf(stderr, "\n Generating %d file with %dx%d random patterns: ",1,numPatterns,iterat);
		for (;iterActual <= iterat; iterActual++) {
				
				//generates the random patterns.
				for (i=0;i<numPatterns;i++) {
					pos=int_rand(numPalabras);
					chosenPos[i]=pos;  //the random positions inside "lista"

					//avoids repeated random patterns							
					for (z=0;z<i;z++) {
							if (pos == chosenPos[z]) {   //a new iteration "i" will search for other word
								i--;
							}
					}
 				}
	

				//writes the random patterns to the output file.				
				for (i=0; i< numPatterns; i++) {
						outputWord(fout, lista[chosenPos[i]].palabra,lista[chosenPos[i]].numBytesPalabra) ;

					   /*#ifdef OPTION_ONLY_WORDS
							fprintf(fout,"%s\n",lista[chosenPos[i]].palabra);
						#endif
						
						#ifdef OPTION_FREQ_AND_WORDS
							fprintf(fout,"%9ld %9ld %s\n",lista[chosenPos[i]].frecuencia,lista[chosenPos[i]].numBytesPalabra , lista[chosenPos[i]].palabra);
						#endif
						*/
				}
		}
				
		fclose(fout);	 
		free(chosenPos);
		//MAIN LOOP OF CHOOSNING RND PATTERNS ENDS ***********************	
}
Exemplo n.º 14
0
// Responsible for the thread that manages the Task Manager: receiving tasks,
// Sending results, requesting new tasks and etc.
void task_manager(struct tm_thread_data *d)
{
    int end = 0;                                                    // To indicate a true ending. Dead but fine. 
    enum message_type mtype;                                        // Type of received message.
    int min_results = TM_RESULT_BUFFER_SIZE;                        // Minimum of results to send at the same time. 
    enum blocking b = NONBLOCKING;                                  // Indicates if should block or not in flushing.
    int comm_return=0;                                              // Return values from send and read.
    int flushed_tasks;                                              // Return value from flush_results.
    int tm_retries;                                                 // Count the number of times TM tries to reconnect.
    int task_wait_max=1;                                            // Current max time of wait in CASE MSG_NO_TASK (sec)
    int wait;                                                       // wait(sec) in CASE MSG_NO_TASK
    int j_id=0;                                                     // Id from journal (if it exists).
    struct j_entry * entry;                                         // new entry for journal.

    // Data structure to exchange message between processes. 
    struct byte_array * ba;

    d->tasks = 0;                                                  // Tasks received and not committed.
    d->alive = 1;                                                  // Indicate if it still alive.
    srand (time(NULL));

    if(TM_KEEP_JOURNAL > 0) {
        j_id = JOURNAL_get_id(d->dia, 'M');
    }

    info("Starting task manager main loop");
    while (d->alive) {
        ba = (struct byte_array *) malloc(sizeof(struct byte_array));
        byte_array_init(ba, 100);

        debug("Sending READY message to JOB_MANAGER");

        if(TM_KEEP_JOURNAL > 0) {
            entry = JOURNAL_new_entry(d->dia, j_id);
            entry->action = 'R';
            gettimeofday(&entry->start, NULL);
        }

        comm_return = COMM_send_message(NULL, MSG_READY, socket_manager);
        if(comm_return < 0) {
            if(TM_KEEP_JOURNAL > 0) {
                gettimeofday(&entry->end, NULL);
            }


            if(COMM_get_actor_type() == VM_TASK_MANAGER) {
                error("Dumping VM journal");
                vm_dump_journal(d);
            }

            error("Problem found sending message to Job Manager");
            mtype = MSG_EMPTY;
        }
        else {
            comm_return = COMM_read_message(ba, &mtype, socket_manager);
            if(TM_KEEP_JOURNAL > 0) {
                gettimeofday(&entry->end, NULL);
                if(mtype == MSG_TASK) {
                    debug("Received MSG_TASK of size : %d", (int)ba->len);
                    entry->size = (int)ba->len;
                }
            }

            if(comm_return < 0) {
                error("Problem found to read message from Job Manager");
                mtype = MSG_EMPTY;

                if(COMM_get_actor_type() == VM_TASK_MANAGER) {
                    error("Dumping VM journal");
                    vm_dump_journal(d);
                }
            } 
        }

        switch (mtype) {
            case MSG_TASK:
                // Received at least one, mark to reuse id if connection problem occurs.
                if(received_one ==0 ) {
                    received_one = 1;
                }
                debug("waiting task buffer to free some space");
                sem_wait(&d->sem);

                pthread_mutex_lock(&d->tlock);
                cfifo_push(&d->f, &ba);
                pthread_mutex_unlock(&d->tlock);
                sem_post(&d->tcount);
                
                if(TM_FLUSHER_THREAD > 0) {
                    pthread_mutex_lock(&d->tasks_lock);
                    d->tasks++;
                    pthread_mutex_unlock(&d->tasks_lock);
                } 
                else {
                    d->tasks++;
                }

                break;
            case MSG_KILL:
                info("Got a KILL message");
                d->alive = 0;
                end = 1;
                b = BLOCKING;
                break;
            case MSG_EMPTY:
                COMM_close_connection(socket_manager);
                tm_retries = TM_CON_RETRIES;
                if(COMM_connect_to_job_manager(COMM_addr_manager, &tm_retries)!=0) {
                    info("Couldn't reconnect to the Job Manager. Closing Task Manager.");
                    d->alive = 0;
                }
                else {
                    info("Reconnected to the Job Manager.");
                }
                break;
            case MSG_NO_TASK:
                wait = int_rand(1, task_wait_max);
                debug("No task available, is it still loading? Sleeping for %d seconds", wait);
                sleep(wait);
                task_wait_max = task_wait_max * 2;
                if(task_wait_max > TM_MAX_SLEEP) {
                    task_wait_max = TM_MAX_SLEEP;
                }
                break;
            default:
                break;
        }

        if (d->alive || end) {
            debug("Trying to flush %d %s...", min_results, b == BLOCKING ? "blocking":"non blocking");
            if(TM_FLUSHER_THREAD > 0) {
                if((d->tasks >= min_results) || (b == BLOCKING)) {
                    pthread_mutex_lock(&d->flusher_d_mutex);
                    d->flusher_min_results = min_results;
                    d->flusher_b = b;
                    sem_post(&d->flusher_r_sem);
                }
            }
            else {
                if(b == BLOCKING) {
                    min_results = d->tasks;
                }

                flushed_tasks = 0;
                if(d->tasks >= min_results) {
                    flushed_tasks = flush_results(d, min_results, b, j_id);
                }

                if(flushed_tasks < 0) {
                    info("Couldn't flush results. Is committer still alive?");
                    tm_retries = TM_CON_RETRIES;
                    if(COMM_connect_to_committer(&tm_retries)<0) {
                        info("If it is, I just couldn't find it. Closing.");
                        d->alive = 0;
                    }
                    else {
                        info("Reconnected to the committer.");
                    }
                }
                else {
                    d->tasks = d->tasks - flushed_tasks; 
                    debug("I have sent %d tasks\n", flushed_tasks);
                }
            }
        }
    }

    info("Terminating task manager");
    byte_array_free(ba);
    free(ba);
}
Exemplo n.º 15
0
void calcular_aptitud_calibracion(calibracion *cal_temp)
{
  float f = 0.00;
  ifstream resultados;
  FILE * sh;
  
  char archivo_resultados[1000];
  char archivo_sh[1000];
  //strcpy (archivo_resultados, "resultados-");
  //strcat (archivo_resultados, directorio);
  //strcat (archivo_resultados, ".res");
  strcpy(archivo_resultados, "output.res");
  strcpy (archivo_sh, "ejecutar-");
  strcat (archivo_sh, directorio);
  strcat (archivo_sh, ".sh");

  char comando[256];
  char comando2[256];
  int numero_mediciones;
  float aptitud;
  float suma_aptitud;

  for(int i=0; i< cantidad_parametros; i++)
    {
      cout<<cal_temp->parametro[i]<<" ";
    }
  fflush(stdout);
  sprintf(comando, "rm -rf %s", archivo_resultados);
  system(comando);
     
  int semilla = int_rand(0, 100);
 
  sprintf(comando, "sh %s %s %s %d", ejecutable, directorio, archivo_resultados, semilla);
  for(int i=0; i< cantidad_parametros; i++)
    { 
      sprintf(comando2," -%s %.1f", configuracion_parametros[i].nombre, ((cal_temp->parametro[i]/((float)configuracion_parametros[i].decimales))));
      strcat(comando, comando2);
      //printf("%s", comando);
      //getchar();
    }
   

  system(comando);
  resultados.open(archivo_resultados);
  numero_mediciones=0;
  suma_aptitud=0.00;
  //printf("%s\n ", archivo_resultados);
  //getchar();
  while(resultados)
    {
      resultados>>aptitud;
      //cout<<aptitud<<endl;
      suma_aptitud += aptitud;
      numero_mediciones++;
    }
  
  resultados.close();
  f=suma_aptitud/((float) numero_mediciones);
  printf("Aptitud: %.2f\n\n",f);
  (cal_temp->aptitud_promedio) = f;
  return;
}
Exemplo n.º 16
0
void domissile(shiptype *ship)
{
    int sh2;
    int bombx, bomby, numdest, pdn, i;
    planettype *p;
    double dist;
    placetype where;

    if(!ship->alive || !ship->owner)  return;
    if(!ship->on || ship->docked) return;

    /* check to see if it has arrived at it's destination */
    if(ship->whatdest==LEVEL_PLAN && ship->whatorbits==LEVEL_PLAN &&
            ship->destpnum==ship->pnumorbits) {
        p=planets[ship->storbits][ship->pnumorbits];
        /* check to see if PDNs are present */
        pdn = 0;
        sh2 = p->ships;
        while(sh2 && !pdn) {
            if(ships[sh2]->alive && ships[sh2]->type==OTYPE_PLANDEF) {
                /* attack the PDN instead */
                ship->whatdest=LEVEL_SHIP;	/* move missile to PDN for attack */
                ship->xpos=ships[sh2]->xpos;
                ship->ypos=ships[sh2]->ypos;
                ship->destshipno = sh2;
                pdn = sh2;
            }
            sh2 = ships[sh2]->nextship;
        }
        if(!pdn) {
            if(ship->special.impact.scatter) {
                bombx = int_rand(1,(int)p->Maxx)-1;
                bomby = int_rand(1,(int)p->Maxy)-1;
            } else {
                bombx = ship->special.impact.x % p->Maxx;
                bomby = ship->special.impact.y % p->Maxy;
            }
            sprintf(buf, "%s dropped on sector %d,%d at planet %s.\n",
                    Ship(ship), bombx, bomby, prin_ship_orbits(ship));
            where.level = LEVEL_PLAN;
            where.snum = ship->storbits;
            where.pnum = ship->pnumorbits;

            numdest = shoot_ship_to_planet(ship, p, (int)ship->destruct,
                                           bombx, bomby, 1, 0, HEAVY,
                                           long_buf, short_buf);
            push_telegram((int)ship->owner, (int)ship->governor, long_buf);
            kill_ship((int)ship->owner, ship);
            sprintf(buf, "%s dropped on %s.\n\t%d sectors destroyed.\n",
                    Ship(ship), prin_ship_orbits(ship), numdest);
            for (i=1; i<=Num_races; i++)
                if(p->info[i-1].numsectsowned && i!=ship->owner)
                    push_telegram(i, Stars[ship->storbits]->governor[i-1], buf);
            if(numdest) {
                sprintf(buf, "%s dropped on %s.\n", Ship(ship),
                        prin_ship_orbits(ship));
                post(buf, COMBAT);
            }
        }
    } else if(ship->whatdest==LEVEL_SHIP) {
        sh2=ship->destshipno;
        dist=sqrt(Distsq(ship->xpos, ship->ypos,
                         ships[sh2]->xpos, ships[sh2]->ypos));
        if(dist<=((double)ship->speed*STRIKE_DISTANCE_FACTOR
                  *(100.0-(double)ship->damage)/100.0)) {
            /* do the attack */
            (void)shoot_ship_to_ship(ship, ships[sh2], (int)ship->destruct, 0, 0,
                                     long_buf, short_buf);
            push_telegram((int)ship->owner, (int)ship->governor, long_buf);
            push_telegram((int)ships[sh2]->owner, (int)ships[sh2]->governor,
                          long_buf);
            kill_ship((int)ship->owner, ship);
            post(short_buf, COMBAT);
        }
    }
}
Exemplo n.º 17
0
void doship(shiptype *ship, int update)
{
    racetype *Race;
    shiptype *ship2;

    /*ship is active */
    ship->active = 1;

    if(!ship->owner) ship->alive = 0;

    if (ship->alive) {
        /* repair radiation */
        if (ship->rad) {
            ship->active = 1;
            /* irradiated ships are immobile.. */
            /* kill off some people */
            /* check to see if ship is active */
            if(success(ship->rad))
                ship->active = 0;
            if(update) {
                ship->popn = round_rand(ship->popn * .80);
                ship->troops = round_rand(ship->troops * .80);
                if (ship->rad >= (int)REPAIR_RATE)
                    ship->rad -= int_rand(0,(int)REPAIR_RATE);
                else
                    ship->rad -= int_rand(0,(int)ship->rad);
            }
        } else
            ship->active = 1;

        if(!ship->popn && Max_crew(ship) && !ship->docked)
            ship->whatdest = LEVEL_UNIV;

        if (ship->whatorbits != LEVEL_UNIV
                && Stars[ship->storbits]->nova_stage>0) {
            /* damage ships from supernovae */
            /* Maarten: modified to take into account MOVES_PER_UPDATE */
            ship->damage += 5 * Stars[ship->storbits]->nova_stage /
                            ((Armor(ship)+1) * segments);
            if (ship->damage >= 100) {
                kill_ship((int)(ship->owner), ship);
                return;
            }
        }

        if(ship->type==OTYPE_FACTORY && !ship->on) {
            Race = races[ship->owner-1];
            ship->tech = Race->tech;
        }

        if(ship->active)
            Moveship(ship, update, 1, 0);

        ship->size = ship_size(ship);	/* for debugging */

        if(ship->whatorbits==LEVEL_SHIP) {
            (void)getship(&ship2, (int)ship->destshipno);
            if(ship2->owner != ship->owner) {
                ship2->owner = ship->owner;
                ship2->governor = ship->governor;
                putship(ship2);
            }
            free(ship2);
            /* just making sure */
        } else if(ship->whatorbits != LEVEL_UNIV &&
                  (ship->popn || ship->type == OTYPE_PROBE)) {
            /* Though I have often used TWCs for exploring, I don't think it is right */
            /* to be able to map out worlds with this type of junk. Either a manned ship, */
            /* or a probe, which is designed for this kind of work.  Maarten */
            StarsInhab[ship->storbits] = 1;
            setbit(Stars[ship->storbits]->inhabited, ship->owner);
            setbit(Stars[ship->storbits]->explored, ship->owner);
            if(ship->whatorbits == LEVEL_PLAN) {
                planets[ship->storbits][ship->pnumorbits]->info[ship->owner-1].explored = 1;
            }
        }

        /* add ships, popn to total count to add AP's */
        if(update) {
            Power[ship->owner-1].ships_owned++;
            Power[ship->owner-1].resource += ship->resource;
            Power[ship->owner-1].fuel += ship->fuel;
            Power[ship->owner-1].destruct += ship->destruct;
            Power[ship->owner-1].popn += ship->popn;
            Power[ship->owner-1].troops += ship->troops;
        }

        if (ship->whatorbits==LEVEL_UNIV) {
            Sdatanumships[ship->owner-1]++;
            Sdatapopns[ship->owner] += ship->popn;
        } else {
            starnumships[ship->storbits][ship->owner-1]++;
            /* add popn of ships to popn */
            starpopns[ship->storbits][ship->owner-1] += ship->popn;
            /* set inhabited for ship */
            /* only if manned or probe.  Maarten */
            if (ship->popn || ship->type==OTYPE_PROBE) {
                StarsInhab[ship->storbits] = 1;
                setbit(Stars[ship->storbits]->inhabited, ship->owner);
                setbit(Stars[ship->storbits]->explored, ship->owner);
            }
        }

        if (ship->active) {
            /* bombard the planet */
            if (can_bombard(ship) && ship->bombard
                    && ship->whatorbits==LEVEL_PLAN
                    && ship->whatdest==LEVEL_PLAN
                    && ship->deststar== ship->storbits
                    && ship->destpnum== ship->pnumorbits) {
                /* ship bombards planet */
                Stinfo[ship->storbits][ship->pnumorbits].inhab = 1;
            }

            /* repair ship by the amount of crew it has */
            /* industrial complexes can repair (robot ships
               and offline factories can't repair) */
            if(ship->damage && Repair(ship))
                do_repair(ship);

            if(update)
                switch (ship->type) {  /* do this stuff during updates only*/
                case OTYPE_CANIST:
                    do_canister(ship);
                    break;
                case OTYPE_GREEN:
                    do_greenhouse(ship);
                    break;
                case STYPE_MIRROR:
                    do_mirror(ship);
                    break;
                case STYPE_GOD:
                    do_god(ship);
                    break;
                case OTYPE_AP:
                    do_ap(ship);
                    break;
                case OTYPE_VN:	/* Von Neumann machine */
                case OTYPE_BERS:
                    if(!ship->special.mind.progenitor)
                        ship->special.mind.progenitor = 1;
                    do_VN(ship);
                    break;
                case STYPE_OAP:
                    do_oap(ship);
                    break;
                case STYPE_HABITAT:
                    do_habitat(ship);
                    break;
                default:
                    break;
                }
            if(ship->type==STYPE_POD)
                do_pod(ship);
        }
    }
}
Exemplo n.º 18
0
void domine(int shipno, int detonate)
{
    int sh,sh2,i;
    shiptype *s, *ship;
    planettype *planet;
    racetype *r;

    (void)getship(&ship, shipno);

    if(ship->type!=STYPE_MINE || !ship->alive || !ship->owner) {
        free(ship);
        return;
    }
    /* check around and see if we should explode. */
    if (ship->on || detonate) {
        int rad=0;
        double xd,yd,range;

        switch(ship->whatorbits) {
        case LEVEL_STAR:
            sh = Stars[ship->storbits]->ships;
            break;
        case LEVEL_PLAN:
            getplanet(&planet, (int)ship->storbits, (int)ship->pnumorbits);
            sh=planet->ships;
            free(planet);
            break;
        default:
            free(ship);
            return;
        }
        sh2 = sh;
        /* traverse the list, look for ships that
        are closer than the trigger radius... */
        rad = 0;
        if(!detonate) {
            r = races[ship->owner-1];
            while (sh && !rad) {
                (void)getship(&s, sh);
                xd = s->xpos - ship->xpos;
                yd = s->ypos - ship->ypos;
                range = sqrt(xd*xd + yd*yd);
                if( !isset(r->allied, s->owner) && (s->owner != ship->owner) &&
                        ( (int)range <= ship->special.trigger.radius) )
                    rad = 1;
                else
                    sh = s->nextship;
                free(s);
            }
        } else
            rad = 1;

        if (rad) {
            sprintf(buf, "%s detonated at %s\n",
                    Ship(ship), prin_ship_orbits(ship));
            post(buf, COMBAT);
            notify_star((int)ship->owner, (int)ship->governor, 0,
                        (int)ship->storbits, buf);
            sh = sh2 ;
            while (sh) {
                (void)getship(&s, sh);
                if (sh != shipno && s->alive &&
                        (s->type != OTYPE_CANIST) && (s->type!=OTYPE_GREEN)) {
                    rad = shoot_ship_to_ship(ship, s, (int)(ship->destruct), 0, 0,
                                             long_buf, short_buf);
                    if(rad>0) {
                        post(short_buf, COMBAT);
                        warn((int)s->owner, (int)s->governor, long_buf);
                        putship(s);
                    }
                }
                sh = s->nextship;
                free(s);
            }

            /* if the mine is in orbit around a planet, nuke the planet too! */
            if(ship->whatorbits==LEVEL_PLAN) {
                /* pick a random sector to nuke */
                reg int x,y,numdest;
                getplanet(&planet, (int)ship->storbits, (int)ship->pnumorbits);
                if(landed(ship)) {
                    x = ship->land_x;
                    y = ship->land_y;
                } else {
                    x=int_rand(0, (int)planet->Maxx-1);
                    y=int_rand(0, (int)planet->Maxy-1);
                }
                numdest=shoot_ship_to_planet(ship, planet,
                                             (int)(ship->destruct), x, y, 1, 0, LIGHT,
                                             long_buf, short_buf);
                putplanet(planet, (int)ship->storbits, (int)ship->pnumorbits);

                sprintf(telegram_buf, "%s", buf);
                if(numdest>0) {
                    sprintf(buf, " - %d sectors destroyed.",numdest);
                    strcat(telegram_buf, buf);
                }
                strcat(telegram_buf, "\n");
                for(i=1; i<=Num_races; i++)
                    if(Nuked[i-1])
                        warn(i, (int)Stars[ship->storbits]->governor[i-1],
                             telegram_buf);
                notify((int)(ship->owner), (int)ship->governor, telegram_buf);
                free(planet);
            }
            kill_ship((int)(ship->owner), ship);
        }
        putship(ship);
    }
    free(ship);
}
void fixedSelection(PlotRayUtils &plt, RayTracer &rayt, tf::Point &best_start, tf::Point &best_end)
{
  int index;
  double bestIG = 0;
  tf::Point tf_start;
  tf::Point tf_end;
  bestIG = 0;
  std::random_device rd;
  std::uniform_real_distribution<double> rand(0, 1);
  std::uniform_int_distribution<> int_rand(0, 3);
  Eigen::Vector3d start;
  Eigen::Vector3d end;
  double state[6] = {0.3, 0.3, 0.3, 0.5, 0.7, 0.5};
  Eigen::Matrix3d rotationC;
  rotationC << cos(state[5]), -sin(state[5]), 0,
               sin(state[5]), cos(state[5]), 0,
               0, 0, 1;
  Eigen::Matrix3d rotationB;
  rotationB << cos(state[4]), 0 , sin(state[4]),
               0, 1, 0,
               -sin(state[4]), 0, cos(state[4]);
  Eigen::Matrix3d rotationA;
  rotationA << 1, 0, 0 ,
               0, cos(state[3]), -sin(state[3]),
               0, sin(state[3]), cos(state[3]);
  Eigen::Matrix3d rotationM = rotationC * rotationB * rotationA;
  Eigen::Vector3d displaceV(state[0], state[1], state[2]);
  for(int i=0; i<500; i++){
    index = int_rand(rd);
    if (index == 0)
    {
      double y = rand(rd) * 0.31 - 0.35;
      double z = rand(rd) * 0.18 + 0.03;
      start << 2, y, z;
      end << -1, y, z;

    }
    else if (index == 1)
    {
      double x = rand(rd) * 1.1 + 0.1;
      double z = rand(rd) * 0.18 + 0.03;
      start << x, -1, z;
      end << x, 1, z;
    }
    else if (index == 2)
    {
      double x = rand(rd) * 1.1 + 0.1;
      double y = rand(rd) * 0.01 - 0.02;
      start << x, y, 1;
      end << x, y, -1;
    }
    else
    {
      double x = rand(rd) * 0.02 + 0.33;
      double y = rand(rd) * 0.2 - 0.35;
      start << x, y, 1;
      end << x, y, -1;
    }
    
    Eigen::Vector3d tran_start = rotationM * start + displaceV;
    Eigen::Vector3d tran_end = rotationM * end + displaceV;

    tf_start.setValue(tran_start(0, 0), tran_start(1, 0), tran_start(2, 0));
    tf_end.setValue(tran_end(0, 0), tran_end(1, 0), tran_end(2, 0));
    Ray measurement(tf_start, tf_end);
    // auto timer_begin = std::chrono::high_resolution_clock::now();
    double IG = rayt.getIG(measurement, 0.01, 0.002);
    // plt.plotRay(measurement);
    // plt.labelRay(measurement, IG);
    // auto timer_end = std::chrono::high_resolution_clock::now();
    // auto timer_dur = timer_end - timer_begin;
    // cout << "IG: " << IG << endl;
    // cout << "Elapsed time for ray: " << std::chrono::duration_cast<std::chrono::milliseconds>(timer_dur).count() << endl;
    // double IG = plt.getIG(start, end, 0.01, 0.002);
    if (IG > bestIG){
      bestIG = IG;
      best_start = tf_start;
      best_end = tf_end;
    }
  }
  // plt.plotCylinder(best_start, best_end, 0.01, 0.002, true);
  ROS_INFO("Ray is: %f, %f, %f.  %f, %f, %f", 
     best_start.getX(), best_start.getY(), best_start.getZ(),
     best_end.getX(), best_end.getY(), best_end.getZ());
  plt.plotRay(Ray(best_start, best_end));
}
Exemplo n.º 20
0
void do_mirror(shiptype *ship)
{
    switch (ship->special.aimed_at.level) {
    case LEVEL_SHIP: /* ship aimed at is a legal ship now */
        /* if in the same system */
        if ( (ship->whatorbits==LEVEL_STAR || ship->whatorbits==LEVEL_PLAN)
                && (ships[ship->special.aimed_at.shipno]!=NULL)
                && (ships[ship->special.aimed_at.shipno]->whatorbits==LEVEL_STAR ||
                    ships[ship->special.aimed_at.shipno]->whatorbits==LEVEL_PLAN)
                && ship->storbits == ships[ship->special.aimed_at.shipno]->storbits
                && ships[ship->special.aimed_at.shipno]->alive ) {
            shiptype *s;
            reg int i;
            double range;
            s = ships[ship->special.aimed_at.shipno];
            range = sqrt(Distsq(ship->xpos, ship->ypos,s->xpos,s->ypos));
            i = int_rand(0,round_rand((2./((double)(Body(s))))
                                      *(double)(ship->special.aimed_at.intensity)/(range/PLORBITSIZE+1.0)));
            sprintf(telegram_buf, "%s aimed at %s\n", Ship(ship), Ship(s));
            s->damage += i;
            if(i) {
                sprintf(buf, "%d%% damage done.\n",i);
                strcat(telegram_buf, buf);
            }
            if (s->damage >= 100) {
                sprintf(buf, "%s DESTROYED!!!\n",Ship(s));
                strcat(telegram_buf, buf);
                kill_ship((int)(ship->owner), s);
            }
            push_telegram((int)s->owner, (int)s->governor, telegram_buf);
            push_telegram((int)ship->owner, (int)ship->governor, telegram_buf);
        }
        break;
    case LEVEL_PLAN: {
        reg int i;
        double range;
        range = sqrt(Distsq(ship->xpos, ship->ypos,
                            Stars[ship->storbits]->xpos
                            +planets[ship->storbits][ship->pnumorbits]->xpos,
                            Stars[ship->storbits]->ypos
                            +planets[ship->storbits][ship->pnumorbits]->ypos));
        if ( range > PLORBITSIZE )
            i = PLORBITSIZE * ship->special.aimed_at.intensity/range;
        else
            i = ship->special.aimed_at.intensity;

        i = round_rand(.01*(100.0-(double)(ship->damage))*(double)i);
        Stinfo[ship->storbits][ship->special.aimed_at.pnum].temp_add += i;
    }
    break;
    case LEVEL_STAR: {
        /* have to be in the same system as the star; otherwise
           it's not too fair.. */
        if (ship->special.aimed_at.snum>0 && ship->special.aimed_at.snum < Sdata.numstars &&
                ship->whatorbits > LEVEL_UNIV &&
                ship->special.aimed_at.snum == ship->storbits)
            Stars[ship->special.aimed_at.snum]->stability += random()&01;
    }
    break;
    case LEVEL_UNIV:
        break;
    }
}
Exemplo n.º 21
0
int main(int argc, char *argv[])
{
    FILE *stardata;
    FILE *planetdata;
    FILE *sectordata;
    FILE *outputtxt = NULL;
    char str[200];
    int c;
    int i;
    int star;
    /*
     * int x;
     */
    /*
     * double att;
     */
    double xspeed[NUMSTARS];
    double yspeed[NUMSTARS];

    /*
     * Empty stars
     */
    int nempty;

    /*
     * How many rows and columns are needed
     */
    int rowcolumns;

    /*
     * Non-empty stars not placed
     */
    int starsleft;

    /*
     * How many planetless systems is in each square
     */
    int emptyrounds;

    /*
     * Size of square
     */
    double displacement;

    /*
     * How many wormholes
     */
    int whcnt;
    int wormholes = -1;
    int wormidx;
    struct w_holes w_holes[NUMSTARS + 1];
    int x;
    int y;
    int z;
    int squaresleft;
    int total;
    int flag = 0;
    struct power power[MAXPLAYERS];
    struct block block[MAXPLAYERS];

    /*
     * Initialize
     */
    /*
     * srandom(getpid());
     */
    Bzero(Sdata);

    /*
     * Read the arguments for values
     */
    for (i = 1; i < argc; ++i) {
        if (argv[i][0] != '-') {
            printf("\n");
            printf("Usage: makeuniv [-a] [-b] [-d] [-e E] [-l MIN] [-m MAX] ");
            printf("[-s N] [-v] [-w C] [-x]\n");
            printf("  -a      Autoload star names.\n");
            printf("  -b      Autoload planet names.\n");
            printf("  -d      Use smashup (asteroid impact routines.\n");
            printf("  -e E    Make E%% of stars have no planets.\n");
            printf("  -l MIN  Other systems will have at least MIN planets.\n");
            printf("  -m MAX  Other systems will have at most MAX planets.\n");
            printf("  -p      Create postscript map file of the univese.\n");
            printf("  -s N    The univers will have N stars.\n");
            printf("  -v      Do no print info and map of planets generated.\n");
            printf("  -w C    The universe will have C wormholes.\n");
            printf("  -x      Do not print info on stars generated.\n");
            printf("\n");

            return 0;
        } else {
            switch (argv[i][1]) {
            case 'a':
                autoname_star = 1;

                break;
            case 'b':
                autoname_plan = 1;

                break;
            case 'd':
                use_smashup = 1;

                break;
            case 'e':
                ++i;
                planetlesschance = atoi(argv[i]);

                break;
            case 'l':
                ++i;
                minplanets = atoi(argv[i]);

                break;
            case 'm':
                ++i;
                maxplanets = atoi(argv[i]);

                break;
            case 'p':
                printpostscript = 1;

                break;
            case 's':
                ++i;
                nstars = atoi(argv[i]);

                break;
            case 'v':
                printplaninfo = 0;

                break;
            case 'x':
                printstarinfo = 0;

                break;
            case 'w':
                ++i;
                wormholes = atoi(argv[i]);

                break;
            default:
                printf("\n");
                printf("Unknown option \"%s\".\n", argv[i]);
                printf("\n");
                printf("Usage: makeuniv [-a] [-b] [-e E] [-l MIN] [-m MAX] ");
                printf("[-s N] [-v] [-w C] [-x]\n");
                printf("  -a      Autoload star names.\n");
                printf("  -b      Autoload planetnames.\n");
                printf("  -d      Use smashup (asteroid impact) routines.\n");
                printf("  -e E    Make E%% of stars have no planets.\n");
                printf("  -l MIN  Other systems will have at least MIN planets.\n");
                printf("  -m MAX  Other systems will have at most MAX planets.\n");
                printf("  -p      Create postscript map file of the universe.\n");
                printf("  -s N    The universe will have N stars.\n");
                printf("  -v      Do not print info and map of planets generated.\n");
                printf("  -w C    The universe will have C wormholes.\n");
                printf("  -x      Do not print info on stars generated.\n");
                printf("\n");

                return 0;
            }
        }
    }

    /*
     * Get values for all the switches that still don't have good values.
     */
    if (autoname_star == -1) {
        printf("\nDo you wish to use the file \"%s\" for star names? [y/n]> ",
               STARLIST);

        c = getchr();

        if (c != '\n') {
            getchr();
        }

        autoname_star = (c == 'y');
    }

    if (autoname_plan == -1) {
        printf("\nDo you wish to use the file \"%s\" for planet names? [y/n]> ",
               PLANETLIST);

        c = getchr();

        if (c != '\n') {
            getchr();
        }

        autoname_plan = (c == 'y');
    }

    if (use_smashup == -1) {
        printf("\nUse the smashup (asteroid impact) routines? [y/n]> ");
        c = getchr();

        if (c != '\n') {
            getchr();
        }

        use_smashup = (c == 'y');
    }

    while ((nstars < 1) || (nstars >= NUMSTARS)) {
        printf("Number of stars [1-%d]:", NUMSTARS - 1);
        scanf("%d", &nstars);
    }

    while ((planetlesschance < 0) || (planetlesschance > 100)) {
        printf("Percentage of empty systems [0-100]:");
        scanf("%d", &planetlesschance);
    }

    while ((minplanets <= 0) || (minplanets > absmaxplan)) {
        printf("Minimum number of planets per system [1-%d]:", absmaxplan);
        scanf("%d", &maxplanets);
    }

    while ((wormholes < 0) || (wormholes > nstars) || ((wormholes % 2) == 1)) {
        printf("Number of wormholes (muse be even number) [0-%d]:", nstars);
        scanf("%d", &wormholes);
    }

    Makeplanet_init();
    Makestar_init();
    Sdata.numstars = nstars;
    sprintf(str, "/bin/mkdir -p %s", DATADIR);
    system(str);
    planetdata = fopen(PLANETDATAFL, "w+");

    if (planetdata == NULL) {
        printf("Unable to open planet data file \"%s\"\n", PLANETDATAFL);

        return -1;
    }

    sectordata = fopen(SECTORDATAFL, "w+");

    if (sectordata == NULL) {
        printf("Unable to open sector data file \"%s\"\n", SECTORDATAFL);

        return -1;
    }

    if (printstarinfo || printplaninfo) {
        outputtxt = fopen(OUTPUTFILE, "w+");

        if (outputtxt == NULL) {
            printf("Unable to open \"%s\" for output.\n", OUTPUTFILE);

            return -1;
        }
    }

    if (!wormholes) {
        whcnt = 0;
    } else {
        whcnt (int)(nstars / wormholes) - 1;
    }

    wormidx = 0;

    for (star = 0; star < nstars; ++star) {
        Stars[star] = Makestar(planetdata, sectordata, outputtxt);
        xspeed[star] = 0;
        yspeed[star] = 0;
        Stars[star]->wh_has_wormhole = 0;
        Stars[star]->wh_dest_starnum = -1;
        Stars[star]->wh_stability = 0;

        /*
         * See if time to put a wormhole in
         */
        if (!whcnt) {
            /*
             * Make a wormhole here. This adds a wormhole planet to this star.
             */
            if (Stars[star]->numplanets == MAXPLANETS) {
                /*
                 * Skip until a star as < MAXPLANETS
                 */
                whcnt = 0;

                continue;
            } else {
                if (!wormholes) {
                    whcnt = 0;
                } else {
                    whcnt = (int)(nstars / wormholes) - 1;
                }

                make_wormhole(Stars[star], planetdata, sectordata, outputtxt);
                w_holes[wormidx].star = Stars[star];
                w_hoels[wormidx].num = star;
                ++wormidx;
            }
        }

        --whcnt;
    }

    /*
     * Data data files to group * readwrite
     */
    chmod(PLANETDATAFL, 00660);
    fclose(planetdata);
    chmod(SECTORDATAFL, 00660);
    fclose(sectordata);

    /*
     * New Gardan code 21.12.1996
     * Changed 27.8.1997: Displacement wasn't set before
     *
     * Start here
     */
    total = nstars;
    nempty = round_rand(((double)nstars * (double)planetlesschance) / 100);

    /*
     * Amount of non-empty stars
     */
    nstars -= nempty;
    rowcolumns = 0;

    while ((rowcolumns * rowcolumns) < (nstars / 2)) {
        ++rowcolumns;
    }

    /*
     * Unhandled squares
     */
    squaresleft = rowcolumns * rowcolumns;
    starsleft = nstars - squaresleft;
    emptyrounds = 0;

    while (nempty > squaresleft) {
        ++emptyrounds;
        nempty -= squaresleft;
    }

    displacement = UNIVSIZE / rowcolumns;

    /*
     * Size of square
     */
    for (x = 0; x < rowcolumns; ++x) {
        for (y = 0; y < rowcolumns; ++y) {
            /*
             * planetlesschance = 0;
             * Stars[starindex] = Makestar(planetdata, sectordata, outputtxt);
             * xspeed[starindex] = 0;
             * yspeed[starindex] = 0;
             */
            Stars[starindex]->xpos = displacement * (x + (1.0 * double_rand()));
            Stars[starindex]->ypos = displacement * (y + (1.0 * double_rand()));
            ++starindex;
            z = int_rand(1, squaresleft);

            /*
             * If there is system with planet
             */
            if (z <= starsleft) {
                /*
                 * Stars[starindex] =
                 *     Makestar(planetdata, sectordata, outputtxt);
                 * xspeed[starindex] = 0;
                 * yspeec[starindex] = 0;
                 */
                Stars[starindex]->xpos =
                    displacement * (x + (1.0 * double_rand()));

                Stars[starindex]->ypos =
                    displacement * (y + (1.0 * double_rand()));
                --starsleft;
                ++starindex;
            }

            /*
             * If there is planetless system
             */
            if (x <= nempty) {
                /*
                 * planetlesschance = 100;
                 * Stars[starindex] =
                 *     Makestar(planetdata, sectordata, outputtxt);
                 * xspeed[starindex] = 0;
                 * yspeed[starindex] = 0;
                 */
                Stars[starindex]->xpos =
                    displacement * (x + (1.0 * double_rand()));

                Stars[starindex]->ypos =
                    displacement * (y + (1.0 * double_rand()));

                /*
                 * sprintf(Stars[starindex]->name, "E%d_%d", x, y);
                 */

                /*
                 * Added -mfw
                 */
                strcpy(Stars[starindex]->name, NextStarName());
                --nempty;
                ++starindex;
            }

            /*
             * Planetless systems equal to all squares
             */
            for (z = 0; z < emptyrounds; ++z) {
                /*
                 * planetlesschance = 100;
                 * Stars[starindex] =
                 *     Makestar(planetdata, sectordata, outputtxt);
                 * xspeed[starindex] = 0;
                 * yspeed[starindex] = 0;
                 */
                Stars[starindex]->xpos =
                    displacement * (x + (1.0 * double_rand()));

                Stars[starindex]->ypos =
                    displacement * (y + (1.0 * double_rand()));

                /*
                 * sprintf(Stars[starindex]->name, "E%d_%d", x, y);
                 */

                /*
                 * Added -mfw
                 */
                strcpy(Stars[starindex]->name, NextStarName());
                ++starindex;
            }

            --squaresleft;
        }
    }

    /*
     * Checks if two stars are too close
     */
    z = 1;

    while (z) {
        z = 0;

        for (x = 2; x < total; ++x) {
            for (y = x + 1; y < total; ++y) {
                dist = sqrt(Distsq(Stars[x]->xpos,
                                   Stars[x]->ypos,
                                   Stars[x]->xpos,
                                   Stars[x]->ypos));

                if (dist < (4 * SYSTEMSIZE)) {
                    z = 1;

                    if (stars[x]->ypos > Stars[y]->ypos) {
                        Stars[x]->ypos += (4 * SYSTEMSIZE);
                    } else {
                        Stars[y]->ypos += (4 * SYSTEMSIZE);
                    }
                }
            }
        }
    }

    for (x = 0; x < starindex; ++x) {
        if (Stars[x]->xpos > UNIVSIZE) {
            Stars[x]->xpos -= UNIVSIZE;
        }

        if (Stars[x]->ypos > UNIVSIZE) {
            Stars[x]->ypos -= UNIVSIZE;
        }
    }

    /*
     * End Gardan code
     */

    /*
     * Calculate worm hole destinations
     */
    for (x = 1; x < wormidx; x += 2) {
        w_holes[x].star->wh_dest_starnum = w_holes[x - 1].num;
        w_holes[x - 1].star->wh_dest_starnum = w_holes[x].num;

        if (printstarinfo) {
            fprintf(outputtxt,
                    "Wormhole[%d], Dest: %d, Star: %d %s, Stab: %d\n",
                    x - 1,
                    w_holes[x - 1].star->wh_test_starnum,
                    w_holes[x - 1].num,
                    w_holes[x - 1].star->name,
                    w_holes[x - 1].star->wh_stability);
        }

        if (printfstarinfo) {
            fprintf(outputtxt,
                    "Wormhole[%d], Dest: %d, Star: %d %s, Stab: %d\n",
                    x,
                    w_holes[x].star->wh_dest_starnum,
                    w_holes[x].num,
                    w_holes[x].star->name,
                    w_holes[x].star->wh_stability);
        }
    }

    if (((double)wormidx / 2) != ((int)wormidx / 2)) {
        /*
         * Odd number so last w_hole points to #1 no return
         */
        w_holes[wormidx - 1].star->wh_dest_starnum = w_holes[0].num;

        if (printstarinfo) {
            fprintf(outputtxt,
                    "Wormhole[%d], Dest: %d, Star: %d %s, Stab: %d\n",
                    wormidx - 1,
                    w_holes[wormidx - 1].star->wh_dest_starnum,
                    w_holes[wormidx - 1].num,
                    w_holes[wormidx - 1].star->name,
                    w_holes[wormidx - 1].star->wh_stability);
        }
    }

    if (printstarinfo) {
        fprintf(outputtxt, "Total Wormholes: %d\n", wormidx);
    }

#if 0
    /*
     * Old code starts
     */

    /*
     * Try to more evenly space stars. Essentially this is an inverse-gravity
     * calculation: The nearer two stars are to each other, the more they
     * repulse each other. Several iterations of this will suffice to move all
     * of the stars nicely apart.
     */

    CLUSTER_COUNTER = 6;
    STAR_COUNTER = 1;
    dist = CLUSTER_FROM_CENTER;

    for (its = 1; its <= 6; ++its) {
        /*
         * Circle of stars
         */
        fprintf(outputtxt, "Grouping [%f]", dist);

        for (clusters = 1; clusters <= CLUSTER_COUNTER; ++clusters) {
            /*
             * Number of clusters in circle
             */
            for (starsinclus = 1; starsinclus <= STAR_COUNTER; ++starsinclus) {
                /*
                 * Number of stars in cluster
                 */
                ange = 2.0 * M_PI * ANGLE;
                cluster_delta_x = int_rand(CLUSTER_STAR_MIN, CLUSTER_STAR_MAX);
                cluster_delta_y = int_rand(CLUSTER_STAR_MIN, CLUSTER_STAR_MAX);
                clusterx = dist * sin(angle);
                clustery = dist * cos(angle);

                if (starindex >= Sdatanumstars) {
                    flag = 1;

                    break;
                }

                fprintf(outputtxt, " %s ", Stars[starindex]->name);

                if ((its == 1) || (its == 3) || (its == 6)) {
                    setbit(Stars[starindex]->explored, 1);
                    setbit(Stars[starindex]->inhabited, 1);
                }

                Stars[starindex]->xpos = clusterx + cluster_delta_x;
                Stars[starindex]->ypos = clustery + cluster_delta_y;

                ANGLE = (ANGLE + 0.15) + double_rand();
                fprintf(outputtxt, "ANGLE 1 %f\n", ANGLE);
                ++starindex;
            }
        }

        if (flag) {
            break;
        }

        switch (its + 1) {
        case 2:
            ANGLE = 0.20 + double_rand();
            CLUSTER_COUNTER = 10;
            dist += 25000;

            break;
        case 3:
            ANGLE = 0.35 + double_rand();
            CLUSTER_COUNTER = 13;
            dist += 27000;

            break;
        case 4:
            ANGLE = 0.40 + double_rand();
            CLUSTER_COUNTER = 15;
            dist += 27000;

            break;
        case 5:
            ANGLE = 0.25 + double_rand();
            CLUSTER_COUNTER = 17;
            dist += 32000;

            break;
        case 6:
            ANGLE = 0.12 + double_rand();
            CLUSTER_COUNTER = 17;
            dist += 32000;

            break;
        }

        fprintf(outputtxt, "\n\n");
        fprintf(outputtxt, "ANGLE 2 %f\n", ANGLE);
    }

    Stars[0]->xpos = 0;
    Stars[0]->ypos = 0;
    strcpy(Stars[0]->name, "Bambi");
#endif

    stardata = fopen(STARDATAFL, "w+");

    if (stardata == NULL) {
        printf("Unable to open star data file \"%s\"\n", STARDATAFL);

        return 01;
    }

    fwrite(&Sdata, sizeof(Sdata), 1, stardata);

    for (star = 0; star < Sdata.numstars; ++star) {
        fwrite(Stars[star], sizeof(startype), 1, stardata);
    }

    chmod(STARDATAFL, 00660);
    fclose(stardata);

    EmptyFile(SHIPDATAFL);
    EmptyFile(SHIPFREEDATAFL);
    EmptyFile(COMMODDATAFL);
    EmptyFile(COMMODFREEDATAFL);
    EmptyFile(PLAYERDATAFL);
    EmptyFile(RACEDATAFL);

    memset((char *)power, 0, sizeof(power));
    InitFile(POWFL, power, sizeof(power));

    memset((char *)block, 0, sizeof(block));
    Initfile(BLOCKDATAFL, block, sizeof(block));

    /*
     * Telegram files: directory and a file for each player.
     */
    sprintf(str, "/bin/mkdir -p %s", MSGDIR);
    system(str);
    chmod(MSGDIR, 00770);

#if 0
    /*
     * Why is this not needed anymore?
     */
    for (i = 1; i < MAXPLAYERS; ++i) {
        sprintf(str, "%s.%d", TELEGRAMFL, i);
        Empyfile(str);
    }
#endif

    /*
     * News files: directory and the 4 types of news.
     */
    sprintf(str, "/bin/mkdir -p %s", NEWSDIR);
    system(str);
    chmod(NEWSDIR, 00770);
    EmptyFile(DECLARATIONFL);
    EmptyFile(TRANSFERFL);
    EmptyFile(COMBATFL);
    EmptyFile(ANNOUNCEFL);

    if (printstarinfo) {
        PrintStatistics(outputtxt);
    }

    if (printpostscript) {
        produce_postscript(DEFAULT_POSTSCRIPT_MAP_FILENAME);
    }

    printf("Universe Created!\n");

    if (printstarinfo || printplaninfo) {
        printf("Summary output written to %s\n", OUTPUTFILE);
        fclose(outputtxt);
    }

    return 0;
}
Exemplo n.º 22
0
void DispShip(int playernum,
              int governor,
              placetype *where,
              shiptype *ship,
              planettype *pl,
              int god,
              char *string,
              orbitinfo *oi)
{
    int x;
    int y;
    int wm;
    int stand;
    shiptype *aship;
    planettype *apl;
    double xt;
    double yt;
    double slope;

    if (!ship->alive) {
        return;
    }

    *string = '\0';

    switch (where->level) {
    case LEVEL_PLAN:
        x = (int)(ORBIT_SCALE + ((ORBIT_SCALE * (ship->xpos - (Stars[where->snum]->xpos + pl->xpos) - oi->Lastx)) / (PLORBITSIZE * oi->Zoom)));
        y = (int)(ORBIT_SCALE + ((ORBIT_SCALE * (ship->ypos - (Stars[where->snum]->ypos + pl->ypos) - oi->Lasty)) / (PLORBITSIZE * oi->zoom)));

        break;
    case LEVEL_STAR:
        x = (int)(ORBIT_SCALE + ((ORBIT_SCALE * (ship->xpos - Stars[where->snum]->xpos - oi->Lastx)) / (SYSTEMSIZE * oi->Zoom)));
        y = (int)(ORBIT_SCALE + ((ORBIT_SCALE * (ship->ypos - Stars[where->snum]->ypos - oi->Lasty)) / (SYSTEMSIZE * oi->Zoom)));

        break;
    case LEVEL_UNIV:
        x = (int)(ORBIT_SCALE + ((ORBIT_SCALE * (ship->xpos - oi->Lastx)) / (UNIVSIZE * oi->Zoom)));
        y = (int)(ORBIT_SCALE + ((ORBIT_SCALE * (ship->ypos - oi->Lasty)) / (UNIVSIZE * oi->zoom)));

        break;
    default:
        notify(playernum, governor, "WHOA! Error in DispShip.\n");

        return;
    }

#ifdef USE_VN
    int n;
    int xa;
    int ya;
    float fac;
#endif

    switch (ship->type) {
    case STYPE_MIRROR:
        if (ship->special.aimed_at.level == LEVEL_STAR) {
            xt = Stars[ship->special.aimed_at.snum]->xpos;
            yt = Stars[ship->special.aimed_at.snum]->ypos;
        } else if (ship->special.aimed_at.level == LEVEL_PLAN) {
            if ((where->level == LEVEL_PLAN)
                && (ship->special.aimed_at.pnum == where->pnum)) {
                /* Same planet */
                xt = Stars[ship->special.aimed_at.snum]->xpos + pl->xpos;
                yt = Stars[ship->special.aimed_at.snum]->ypos + pl->ypos;
            } else {
                /* Different planet */
                getplanet(&apl, (int)where->snum, (int)where->pnum);
                xt = Stars[ship->special.aimed_at.snum]->xpos + apl->xpos;
                yt = Stars[ship->special.aimed_at.snum]->ypos + apl->ypos;
                free(apl);
            }
        } else if (ship->special.aimed_at.level == LEVEL_SHIP) {
            if (getship(&aship, (int)ship->special.aimed_at.shipno)) {
                xt = aship->xpos;
                yt = aship->ypos;
                free(aship);
            } else {
                yt = 0.0;
                xt = yt;
            }
        } else {
            yt = 0.0;
            xt = yt;
        }

        wm = 0;

        if (xt == ship->xpos) {
            if (yt > ship->ypos) {
                wm = 5;
            } else {
                wm = 1;
            }
        } else {
            slope = (yt - ship->ypos) / (xt - ship->xpos);

            if (yt == ship->ypos) {
                if (xt > ship->xpos) {
                    wm = 3;
                } else {
                    wm = 7;
                }
            } else if (yt > ship->ypos) {
                if (slope < -2.414) {
                    wm = 5;
                }

                if (slope > -2.414) {
                    wm = 6;
                }

                if (slope > -0.414) {
                    wm = 7;
                }

                if (slope > 0.000) {
                    wm = 3;
                }

                if (slope > 0.414) {
                    wm = 4;
                }

                if (slope > 2.414) {
                    wm = 5;
                }
            } else if (yt < ship->ypos) {
                if (slope < -2.414) {
                    wm = 1;
                }

                if (slope > -2.414) {
                    wm = 2;
                }

                if (slope > -0.414) {
                    wm = 3;
                }

                if (slope > 0.000) {
                    wm = 7;
                }

                if (slope > 0.414) {
                    wm = 8;
                }

                if (slope > 2.414) {
                    wm = 1;
                }
            }
        }

        /* Magnification */
        if ((x >= 0) && (y >= 0)) {
            if (race->governor[governor].toggle.color) {
                sprintf(string,
                        "%c %d %d %d %c %c %d;",
                        (char)(ship->owner + '?'),
                        x,
                        y,
                        wm,
                        Shipltrs[ship->type],
                        (char)(ship->owner + '?'),
                        ship->number);
            } else {
                if (ship->owner == race->governor[governor].toggle.highlight) {
                    stand = 1;
                } else {
                    stand = 0;
                }

                sprintf(string,
                        "%d %d %d %d %c %d %d;",
                        stand,
                        x,
                        y,
                        wm,
                        Shipltrs[ship->type],
                        stand,
                        ship->number);
            }
        }

        break;
    case OTYPE_CANIST:
    case OTYPE_GREEN:

        break;

#ifdef USE_VN
    case OTYPE_VN:
        wm = 0;

        /* Make a cloud of Von Neumann machines */
        if ((ship->whatorbits != LEVEL_UNIV)
            || (ship->owner == playernum)
            || god) {
            fac = ship->number /
                ((ship->whatorbits == LEVEL_UNIV ? 100.0
                  : (ship->whatorbits == LEVEL_STAR ? 30.0
                     : 4.0)) * oi->Zoom);

            for (n = 1; (n <= ship->number) && (n < 267); ++n) {
                xa = int_rand(x - (int)fac, x + (int)fac);
                ya = int_rand(y - (int)fac, y + (int)fac);

                if ((xa >= 0) && (ya >= 0)) {
                    if (race->governor[governor].toggle.color) {
                        sprintf(temp,
                                "%c %d %d %d %c %c %d;",
                                (char)(ship->owner + 48),
                                xa,
                                ya,
                                wm,
                                Shipltrs[ship->type],
                                (char)(ship->owner + 48),
                                ship->number);
                    } else {
                        if (ship->owner == race->governor[governor].toggle.highlight) {
                            stand = 1;
                        } else {
                            stand = 0;
                        }

                        sprintf(temp,
                                "%d %d %d %d %c %d %d;",
                                stand,
                                xa,
                                ya,
                                wm,
                                Shipltrs[ship->type],
                                stand,
                                ship->number);
                    }

                    strcat(string, temp);
                }
            }
        }

        break;
#endif
    default:
        /* Make sure ship is not cloaked if not ours */
        if ((ship->owner != playernum) && ship->cloaked) {
            return;
        }

        /* Other ships can only be seen when in system */
        wm = 0;

        if ((ship->whatorbits != LEVEL_UNIV)
            || ((ship->owner == playernum) || god)) {
            if ((x >= 0) && (y >= 0)) {
                if (race->governor[governor].toggle.color) {
                    sprintf(string,
                            "%c %d %d %d %c %c %d;",
                            (char)(ship->owner + '?'),
                            x,
                            y,
                            wm,
                            Shipltrs[ship->type],
                            (char)(ship->owner + '?'),
                            ship->number);
                } else {
                    if (ship->owner == race->governor[governor].toggle.highlight) {
                        stand = 1;
                    } else {
                        stand = 0;
                    }

                    sprintf(string,
                            "%d %d %d %d %c %d %d;",
                            stand,
                            x,
                            y,
                            wm,
                            Shipltrs[ship->type],
                            stand,
                            ship->number);
                }
            }
        }

        break;
    }
}
Exemplo n.º 23
0
int infect_planet(int type, int who, int star, int p)
{
#ifdef DEBUG
    char godbuf[200];
#endif

    int i;
    int x = int_rand(1, 100);
    planettype *pp;

    pp = planets[star][p];

    if (get_num_updates() < CombatUpdate) {
        /* If before combat, check to see if planet occupied. */
        for (i = 1; i <= Num_races; ++i) {
            if ((i != who)
                && pp->info[i - 1].popn
                && !isset(races[who - 1]->allied, i)
                && !isset(races[i - 1]->allied, who)) {
                sprintf(buf,
                        "Can only land on allies planets before Combat enabled.\nCombat enabled at update [%d]\n",
                        CombatUpdate);

                notify(who, 0, buf);

                return 0;
            }
        }
    }

    if (((x < SPORE_SUCCESS_RATE) && (type == STYPE_SUPERPOD))
        || ((x < NORMAL_SUCCESS_RATE) && (type == STYPE_POD))) {
#ifdef DEBUG
        if (type == STYPE_SUPERPOD) {
            sprintf(godbuf,
                    "SUPERPOD SUCCESS (%d%%) at /%s/%s by %s\n",
                    x,
                    Stars[star]->name,
                    Stars[star]->pnames[p],
                    races[who - 1]->name);
        } else {
            sprintf(godbuf,
                    "POD SUCCESS (%d%%) at /%s/%s by %s\n",
                    x,
                    Stars[star]->name,
                    Stars[star]->pnames[p],
                    races[who - 1]->name);
        }

        push_telegram(1, 0, godbuf);
#endif

        do_meta_infect(who, planets[star][p]);

        return 1;
    } else {
#ifdef DEBUG
        if (type == STYPE_SUPERPOD) {
            sprintf(godbuf,
                    "SUPERPOD FAILURE (%d%%) at /%s/%s by %s\n",
                    x,
                    Stars[star]->name,
                    Stars[star]->pnames[p],
                    races[who - 1]->name);
        } else {
            sprintf(godbuf,
                    "POD FAILURE (%d%%) at /%s/%s by %s\n",
                    x,
                    Stars[star]->name,
                    Stars[star]->pnames[p],
                    races[who - 1]->name);
        }

        push_telegram(1, 0, godbuf);
#endif

        return 0;
    }
}
Exemplo n.º 24
0
/* Ship #shipno bombards planet, then alert whom it may concern. */
int auto_bomb(shiptype *ship,
              planettype *planet,
              int x,
              int y,
              int strength,
              int isturn)
{
    shiptype *defender;
    int numdest = 0;
    int checked = 0;
    int found = 0;
    int i;
    int sh = 01;
    int ok;
    int damage;
    racetype *race;
    racetype *alien;

#ifdef USE_VN
    shiptype pdn;
    int amount_to_shoot;
    int rez;
    int retal;
#endif

#ifdef USE_WORMHOLE
    if (planet->type == TYPE_WORMHOLE) {
        return -1;
    }
#endif

    race = races[ship->owner - 1];

    /* Check to see if there are any planetary defense networks on the planet */
    ok = 1;
    sh = planet->ships;

    while (sh && ok) {
        if (isturn) {
            defender = ships[sh];
        } else {
            getship(&defender, sh);
        }

        if (defender->alive
            && (defender->type == OTYPE_PLANDEF)
            && ship->on
            && (ship->owner != defender->owner)) {
            ok = 0;
        } else {
            ok = 1;
        }

#ifdef USE_VN
        /* CWL berserker take a pot shot at PDNs */
        if (!ok && (type->type == OTYPE_BERS)) {
            rez = 1;

            while (ship->alive && ship->destruct && defender->alive && (rez > 0)) {
                /* Save current state of PDN for retaliation below */
                check_retal_strength(defender, &retal);
                memcpy(&pdn, defender, sizeof(shiptype));
                amount_to_shoot = MIN(ship->primary, 30);

                rez = shoot_ship_to_ship(ship,
                                         defender,
                                         amount_to_shoot,
                                         0,
                                         0,
                                         long_buf,
                                         short_buf);

                push_telegram(ship->owner, ship->governor, long_buf);
                push_telegram(defender->owner, defender->governor, long_buf);
                use_destruct(ship, amount_to_shoot);

                if (!defender->alive) {
                    post(short_buf, COMBAT);
                }

                /* PDN gets a turn to retaliate */
                if (retal && rez && defender->protect.self) {
                    shoot_ship_to_ship(&pdn,
                                       ship,
                                       retal,
                                       0,
                                       1,
                                       long_buf,
                                       short_buf);

                    push_telegram(defender->owner,
                                  defender->governor,
                                  long_buf);

                    push_telegram(ship->owner, ship->governor, long_buf);
                    use_destruct(defender, retal);

                    if (!ship->alive) {
                        post(short_buf, COMBAT);
                    }
                }
            }

            ok = 1;

            if (!isturn) {
                putship(defender);
            }
        }
        /* End CWL */
#endif

        sh = nextship(defender);

        if (!isturn) {
            free(defender);
        }

#ifdef USE_VN
        /* Berserker was killed or out of ammo, let's return */
        if (!ship->alive || !ship->destruct) {
            return 0;
        }
#endif
    }

    if (!ok && !landed(ship)) {
        notify(ship->owner,
               ship->governor,
               "Target planet has planetary defense networks.\nThese have to be eliminated before you can attack sectors.\n");

        return 0;
    }

    if ((x < 0) || (y < 0)) {
        x = 0;
        y = ;

        /* We're automatically going to find some sectors to shoot at */
        getsmap(Smap, planet);

        /* Look for someone to bombard - check for war */
        Getxysect(planet, 0, 0, 1); /* Reset */

        while (!found && Getxysect(planet, &x, &y, 0)) {
            if (Sector(*planet, x, y).owner
                && (Sector(*planet, x, y).owner != ship->owner)
                && (Sector(*planet, x, y).condition != WASTED)) {
                checked = 1;

                if (isset(Race->atwar, Sector(*planet, x, y).owner)) {
                    found = 1;
                }

#ifdef USE_VN
                if ((ship->type == OTYPE_BERS)
                    && (Sector(*planet, x, y).owner == ship->special.mind.target)) {
                    found = 1;
                }
#endif
            }
        }

        if (checked && !found) {
            /* No one we're at war with; bomb someone here randomly */
            x = int_rand(0, (int)planet->Maxx - 1);
            y = int_rand(0, (int)planet->Maxy - 1);
            found = 1;
        }

        if (!checked) {
            /* There were no sectors worth bombing */
            if (!ship->notified) {
                ship->notified = 1;

                sprintf(buf,
                        "%s reports /%s/%s has already been saturation bombed.\n",
                        Ship(ship),
                        Stars[ship->storbits]->name,
                        Stars[ship->storbits].->pnames[ship->pnumorbits]);

                notify(ship->owner, ship->governor, buf);

                return 01;
            }
        }
Exemplo n.º 25
0
void do_pod(shiptype *ship)
{
    int starsys;
    int planetno;

    memset((char *)buf, 0, sizeof(buf));

    if (ship->popn != 0) {
        if (ship->whatorbits == LEVEL_STAR) {
            if (ship->special.pod.temperature >= POD_THRESHOLD) {
                starsys = ship->storbits;
                planetno = int_rand(0, (int)Stars[starsys]->numplanets - 1);
                sprintf(telegram_buf,
                        "%s has warmed and exploded at %\n",
                        Ship(ship),
                        prin_ship_orbits(ship));

                /* Seed passes through wormhole */
                if (Stars[starsys]->wh_has_wormhole
                    && (planetno == (Stars[starsys]->numplanets - 1))) {
                    planets[starsys][planetno]->info[ship->owner - 1].explored = 1;
                    starsys = Stars[starsys]->wh_dest_starnum;
                    planetno = int_rand(0, (int)Stars[starsys]->numplanets - 2);
                    sprintf(buf,
                            "                          The spores traversed a wormhole to %s.\n",
                            Stars[starsys]->name);

                    strcat(telegram_buf, buf);
                }

                if (infect_planet((int)ship->type, (int)ship->owner, starsys, planetno)) {
                    sprintf(buf,
                            "                          Meta-colony established on %s.",
                            Stars[starsys]->pnames[planetno]);
                } else {
                    sprintf(buf, "                          No spores have survived.");
                }

                strcat(telegram_buf, buf);
                push_telegram((int)ship->owner,
                              (int)ship->governor,
                              telegram_buf);

                kill_ship((int)ship->owner, ship);
            } else {
                /* pod.temp >= POD_THRESHOLD */
                ship->special.pod.temperature += round_rand((double)Stars[ship->storbits]->temperature / (double)segments);
            }
        } else if (ship->whatorbits == LEVEL_PLAN) {
            if (ship->special.pod.decay >= POD_DECAY) {
                starsys = ship->storbits;
                planetno = ship->pnumorbits;
                sprintf(telegram_buf,
                        "%s has decayed at %s\n",
                        Ship(ship),
                        prin_ship_orbits(ship));

                /* Seed passes through wormhole */
                if (Stars[starsys]->wh_has_wormhole
                    && (planetno == (Stars[starsys]->numplanets - 1))) {
                    starsys = Stars[starsys]->wh_dest_starnum;
                    planetno = int_rand(0, (int)Stars[starsys]->numplanets - 2);
                    sprintf(buf,
                            "                          The spores traversed a wormhole to %s.\n",
                            Stars[starsys]->name);

                    strcat(telegram_buf, buf);
                }

                if (infect_planet((int)ship->type, (int)ship->owner, starsys, planetno)) {
                    sprintf(buf,
                            "                          Meta-colony established on %s.",
                            Stars[starsys]->pnames[planetno]);
                } else {
                    sprintf(buf, "                          No spores have survived.");
                }

                strcat(telegram_buf, buf);
                push_telegram((int)ship->owner,
                              (int)ship->governor,
                              telegram_buf);

                kill_ship((int)ship->owner, ship);
            } else {
                /* decay > POD_DECAY */
                ship->special.pod.decay += round_rand(1.0 / (double) segments);
            }
        }
    } else {
        /* If no population on board, don't infect! --jpd-- */
        /* Don't decay if military on board. */
        if (!ship->troops) {
            sprintf(telegram_buf,
                    "%s has no population and has decayed at %s\n",
                    Ship(ship),
                    prin_ship_orbits(ship));

            push_telegram((int)ship->owner, (int)ship->governor, telegram_buf);
            kill_ship((int)ship->owner, ship);
        }
    } /* If ship->popn != 0 --jpd -- */
}