コード例 #1
0
ファイル: sst.c プロジェクト: TimeDoctor/Super-Star-Trek
int main(int argc, char **argv) {
	int i;
	int hitme;
	char ch;
	prelim();

	if (argc > 1) { // look for -f option
		if (strcmp(argv[1], "-f")== 0) {
			coordfixed = 1;
			argc--;
			argv++;
		}
	}
					
	
	if (argc > 1) {
		fromcommandline = 1;
		line[0] = '\0';
		while (--argc > 0) {
			strcat(line, *(++argv));
			strcat(line, " ");
		}
	}
	else fromcommandline = 0;


	while (TRUE) { /* Play a game */
		setup();
		if (alldone) {
			score(0);
			alldone = 0;
		}
		else makemoves();
		skip(2);
		stars();
		skip(1);

		if (tourn && alldone) {
			printf("Do you want your score recorded?");
			if (ja()) {
				chew2();
				freeze(FALSE);
			}
		}
		printf("Do you want to play again?");
		if (!ja()) break;
	}
	skip(1);
	prout("May the Great Bird of the Galaxy roost upon your home planet.");
	return 0;
}
コード例 #2
0
ファイル: testMoveit.cpp プロジェクト: jpmerc/perception3d
int main(int argc, char** argv)
{


    ros::init(argc,argv,"test_moveit_jaco");

    ros::NodeHandle nh;
    ros::Publisher pub;
    //ros::AsyncSpinner spinner(1);
    //  spinner.start();

    pub = nh.advertise<sensor_msgs::PointCloud2>("robot_vision", 1);

    JacoCustom ja(nh);


    ros::CallbackQueue queue;
    ros::SubscribeOptions options = ros::SubscribeOptions::create<std_msgs::String>("/terminal_listener",
                                                                                    1,
                                                                                    boost::bind(&callBack2,_1, &ja),
                                                                                    ros::VoidPtr(),
                                                                                    &queue);

    ros::AsyncSpinner spinner(0, &queue);
    spinner.start();
    ros::spin();


    return 0;
}
コード例 #3
0
// ---------------------------------------------------------------------
void
compute_sequence(const struct UnstructuredGrid* grid       ,
                 const double*                  flux       ,
                 int*                           sequence   ,
                 int*                           components ,
                 int*                           ncomponents)
// ---------------------------------------------------------------------
{
    const std::size_t nc = grid->number_of_cells;
    const std::size_t nf = grid->number_of_faces;
    const std::size_t sz = std::max(nf, 3 * nc);

    std::vector<int> work(sz);
    std::vector<int> ia  (nc + 1);
    std::vector<int> ja  (nf);  // A bit too much.

    compute_reorder_sequence_graph(grid->number_of_cells,
                                   grid->cell_faces,
                                   grid->cell_facepos,
                                   grid->face_cells,
                                   flux,
                                   sequence,
                                   components,
                                   ncomponents,
                                   & ia[0], & ja[0], & work[0]);
}
コード例 #4
0
static int ProcessMessage(const FeedData *data)
{
    static int sent = 0;

    K condvec;
 
    if (trades == NULL)  {
        trades = create_trade_schema();
    }

    if (quotes == NULL) {
        quotes = create_quote_schema();
    }

    switch(data->type) {
        case FF_TRADE_MSG:
            js(&kK(trades)[0], ss(data->core.sym));
            js(&kK(trades)[1], ss(data->core.exg));
            ja(&kK(trades)[2], (void *) &data->msg.trade.size);
            ja(&kK(trades)[3], (void *) &data->msg.trade.volume);
            ja(&kK(trades)[4], (void *) &data->core.sequence);
            ja(&kK(trades)[5], (void *) &data->msg.trade.price); 
            
            condvec = ktn(4, KC);
            memcpy(&kC(condvec)[0], &data->core.cond, 4);
            jk(&kK(trades)[6], condvec); 
           
            break;
        case FF_QUOTE_MSG:
            js(&kK(quotes)[0], ss(data->core.sym));
            js(&kK(quotes)[1], ss(data->core.exg));
            ja(&kK(quotes)[2], (void *) &data->msg.quote.asksize);
            ja(&kK(quotes)[3], (void *) &data->msg.quote.bidsize);
            ja(&kK(quotes)[4], (void *) &data->msg.quote.askprice);
            ja(&kK(quotes)[5], (void *) &data->msg.quote.bidprice);
            ja(&kK(quotes)[6], (void *) &data->core.sequence);

            condvec = ktn(4, KC);
            memcpy(&kC(condvec)[0], &data->core.cond, 4);
            jk(&kK(quotes)[7], condvec);

            break;
    }
 
    if (++sent >= 10) {
        SendToKDB("quote", quotes); quotes = NULL;
        SendToKDB("trade", trades); trades = NULL;
        sent = 0;
    }

    return FEED_STATE;
}
コード例 #5
0
ファイル: events.c プロジェクト: aichao/sst
void waiting(void) {
	int key;
	double temp, delay, origTime;

	ididit = 0;
	for (;;) {
		key = scan();
		if (key  != IHEOL) break;
		proutn("How long? ");
	}
	chew();
	if (key != IHREAL) {
		huh();
		return;
	}
	origTime = delay = aaitem;
	if (delay <= 0.0) return;
	if (delay >= d.remtime || nenhere != 0) {
		prout("Are you sure? ");
		if (ja() == 0) return;
	}

	/* Alternate resting periods (events) with attacks */

	resting = 1;
	do {
		if (delay <= 0) resting = 0;
		if (resting == 0) {
			cramf(d.remtime, 0, 2);
			prout(" stardates left.");
			return;
		}
		temp = Time = delay;

		if (nenhere) {
			double rtime = 1.0 + Rand();
			if (rtime < temp) temp = rtime;
			Time = temp;
		}
		if (Time < delay) attack(0);
		if (nenhere==0) movetho();
		if (alldone) return;
		events();
		ididit = 1;
		if (alldone) return;
		delay -= temp;
		/* Repair Deathray if long rest at starbase */
		if (origTime-delay >= 9.99 && condit == IHDOCKED)
			damage[DDRAY] = 0.0;
	} while (d.galaxy[quadx][quady] != 1000); // leave if quadrant supernovas

	resting = 0;
	Time = 0;
}
コード例 #6
0
ファイル: examples.c プロジェクト: kevinarpe/kx
// join an integer to a list and join a K object to a list
int eg8()
{
        K z=ki(20);
        K intlist=ktn(KI,0);
		K x=ktn(0,0);
        DO(5,ja(&intlist,&i));        
        jk(&x,intlist);
        jk(&x,z);
        k(c,"display",x,(K)0);
        return 1;
}
コード例 #7
0
ファイル: odbc.c プロジェクト: kevinarpe/kx
K eval(K x,K y,K z){K*k;S*b,s;SQLULEN w;SQLLEN*nb;SQLINTEGER*wb;H*tb,u,t,j=0,p,m;F f;C c[128];I n=xj<0;D d=d1(n?-xj:xj);U(d)x=y;Q(z->t!=-KJ||xt!=-KS&&xt!=KC,"type")
 if(z->j)SQLSetStmtAttr(d,SQL_ATTR_QUERY_TIMEOUT,(SQLPOINTER)(SQLULEN)z->j,0);
 if(xt==-KS)Q1(SQLColumns(d,(S)0,0,(S)0,0,xs,S0,(S)0,0))else{I e;K q=kpn(xG,xn);ja(&q,"\0");e=SQLExecDirect(d,q->G0,xn);r0(q);Q1(e)}
 SQLNumResultCols(d,&j);P(!j,(d0(d),knk(0)))
 b=malloc(j*SZ),tb=malloc(j*2),wb=malloc(j*SZ),nb=malloc(j*SZ),x=ktn(KS,j),y=ktn(0,j);// sqlserver: no bind past nonbind
 DO(j,Q1(SQLDescribeCol(d,(H)(i+1),c,128,&u,&t,&w,&p,&m))xS[i]=sn(c,u);
if(t>90)t-=82;
Q(t<-11||t>12,xS[i])wb[i]=ut[tb[i]=t=t>0?t:12-t]==KS&&w?w+1:wt[t];if(ut[t]==KS&&(n||!wb[i]||wb[i]>9))tb[i]=13)
 DO(j,kK(y)[i]=ktn(ut[t=tb[i]],0);if(w=wb[i])Q1(SQLBindCol(d,(H)(i+1),ct[t],b[i]=malloc(w),w,nb+i)))
 for(;SQL_SUCCEEDED(SQLFetch(d));)DO(j,k=kK(y)+i;u=ut[t=tb[i]];s=b[i];n=SQL_NULL_DATA==(int)nb[i];
if(!u)jk(k,n?ktn(ct[t]?KC:KG,0):wb[i]?kp(s):gb(d,(H)(i+1),t));
else ja(k,n?nu(u):u==KH&&wb[i]==1?(t=(H)*s,(S)&t):u==KS?(s=dtb(s,nb[i]),(S)&s):u<KD?s:u==KZ?(f=ds(s)+(vs(s+6)+*(I*)(s+12)/1e9)/8.64e4,(S)&f):(w=u==KD?ds(s):vs(s),(S)&w))) 
 if(!SQLMoreResults(d))O("more\n");DO(j,if(wb[i])free(b[i]))R free(b),free(tb),free(wb),free(nb),d0(d),xT(xD(x,y));}
コード例 #8
0
void JIT::privateCompilePatchGetArrayLength(void* returnAddress)
{
    StructureStubInfo* stubInfo = &m_codeBlock->getStubInfo(returnAddress);

    // We don't want to repatch more than once - in future go to cti_op_put_by_id_generic.
    ctiRepatchCallByReturnAddress(returnAddress, reinterpret_cast<void*>(Interpreter::cti_op_get_by_id_array_fail));

    // Check eax is an array
    __ cmpl_im(reinterpret_cast<unsigned>(m_interpreter->m_jsArrayVptr), 0, X86::eax);
    JmpSrc failureCases1 = __ jne();

    // Checks out okay! - get the length from the storage
    __ movl_mr(FIELD_OFFSET(JSArray, m_storage), X86::eax, X86::ecx);
    __ movl_mr(FIELD_OFFSET(ArrayStorage, m_length), X86::ecx, X86::ecx);

    __ cmpl_ir(JSImmediate::maxImmediateInt, X86::ecx);
    JmpSrc failureCases2 = __ ja();

    __ addl_rr(X86::ecx, X86::ecx);
    __ addl_ir(1, X86::ecx);
    __ movl_rr(X86::ecx, X86::eax);
    JmpSrc success = __ jmp();

    void* code = __ executableCopy(m_codeBlock->executablePool());

    // Use the repatch information to link the failure cases back to the original slow case routine.
    void* slowCaseBegin = reinterpret_cast<char*>(stubInfo->callReturnLocation) - repatchOffsetGetByIdSlowCaseCall;
    X86Assembler::link(code, failureCases1, slowCaseBegin);
    X86Assembler::link(code, failureCases2, slowCaseBegin);

    // On success return back to the hot patch code, at a point it will perform the store to dest for us.
    intptr_t successDest = reinterpret_cast<intptr_t>(stubInfo->hotPathBegin) + repatchOffsetGetByIdPropertyMapOffset;
    X86Assembler::link(code, success, reinterpret_cast<void*>(successDest));

    // Track the stub we have created so that it will be deleted later.
    stubInfo->stubRoutine = code;

    // Finally repatch the jump to sow case back in the hot path to jump here instead.
    intptr_t jmpLocation = reinterpret_cast<intptr_t>(stubInfo->hotPathBegin) + repatchOffsetGetByIdBranchToSlowCase;
    X86Assembler::repatchBranchOffset(jmpLocation, code);
}
コード例 #9
0
int findDupTest() {
  int errs = 0;
  ColValPair ja(0, 0);
  std::vector<ColValPair> v;
  std::vector<ColValPair>::iterator dup = findDup(ja, v);
  if (dup != v.end()) ++errs;

  v.push_back(ColValPair(1, 0));
  dup = findDup(ja, v);
  if (dup != v.end()) ++errs;

  v.push_back(ColValPair(3, 0));
  dup = findDup(ja, v);
  if (dup != v.end()) ++errs;

  dup = findDup(ColValPair(1, 0), v);
  if (dup == v.end()) ++errs;
  if (std::distance(v.begin(), dup) != 0) errs += 1;

  return errs;
}
コード例 #10
0
void OptimalConstrainedMatches::_populateSolver(IntegerProgrammingSolver& solver)
{
  // try to maximize the score.
  solver.setObjectiveDirection(GLP_MAX);

  // each match is a column (variable) in the function that we want to maximize.
  solver.addColumns(_matches.size());
  for (size_t i = 0; i < _matches.size(); i++)
  {
    solver.setColumnKind(i + 1, GLP_BV);
    //solver.setColumnBounds(i + 1, GLP_DB, 0.0, 1.0);
    // The score of a match is the coefficient. This makes higher score matches worth
    // more in the function.
    solver.setObjectiveCoefficient(i + 1, _matches[i]->getScore() + EPSILON);
  }

  // there is one row (constraint) for each conflict.
  solver.addRows(_conflicts.size());
  vector<int> ia(_conflicts.size() * 2 + 1);
  vector<int> ja(_conflicts.size() * 2 + 1);
  vector<double> ra(_conflicts.size() * 2 + 1);
  int i = 0;
  for (MatchConflicts::ConflictMap::const_iterator it = _conflicts.constBegin();
       it != _conflicts.constEnd(); ++it)
  {
    // Set the coefficients to 1 for each of the conflicting pairs and set the max value to 1. This
    // will make it so only one of the values can be 1 at a time, or they can both be 0.
    solver.setRowBounds(i + 1, GLP_DB, 0.0, 1.0);
    ia[i * 2 + 1] = i + 1;
    ja[i * 2 + 1] = (int)it.key() + 1;
    ra[i * 2 + 1] = 1.0;
    ia[i * 2 + 2] = i + 1;
    ja[i * 2 + 2] = (int)it.value() + 1;
    ra[i * 2 + 2] = 1.0;
    i++;
  }

  // Populate the row coefficients.
  solver.loadMatrix(ia, ja, ra);
}
コード例 #11
0
ファイル: sst.c プロジェクト: TimeDoctor/Super-Star-Trek
void debugme(void) {
	proutn("Reset levels? ");
	if (ja() != 0) {
		if (energy < inenrg) energy = inenrg;
		shield = inshld;
		torps = intorps;
		lsupres = inlsr;
	}
	proutn("Reset damage? ");
	if (ja() != 0) {
		int i;
		for (i=0; i <= ndevice; i++) if (damage[i] > 0.0) damage[i] = 0.0;
		stdamtim = 1e30;
	}
	proutn("Toggle idebug? ");
	if (ja() != 0) {
		idebug = !idebug;
		if (idebug) prout("Debug output ON");
		else prout("Debug output OFF");
	}
	proutn("Cause selective damage? ");
	if (ja() != 0) {
		int i, key;
		for (i=1; i <= ndevice; i++) {
			proutn("Kill ");
			proutn(device[i]);
			proutn("? ");
			chew();
			key = scan();
			if (key == IHALPHA &&  isit("y")) {
				damage[i] = 10.0;
				if (i == DRADIO) stdamtim = d.date;
			}
		}
	}
	proutn("Examine/change events? ");
	if (ja() != 0) {
		int i;
		for (i = 1; i < NEVENTS; i++) {
			int key;
			if (future[i] == 1e30) continue;
			switch (i) {
				case FSNOVA:  proutn("Supernova       "); break;
				case FTBEAM:  proutn("T Beam          "); break;
				case FSNAP:   proutn("Snapshot        "); break;
				case FBATTAK: proutn("Base Attack     "); break;
				case FCDBAS:  proutn("Base Destroy    "); break;
				case FSCMOVE: proutn("SC Move         "); break;
				case FSCDBAS: proutn("SC Base Destroy "); break;
			}
			cramf(future[i]-d.date, 8, 2);
			chew();
			proutn("  ?");
			key = scan();
			if (key == IHREAL) {
				future[i] = d.date + aaitem;
			}
		}
		chew();
	}
	proutn("Make universe visible? ");
	if (ja() != 0) {
		int i, j;
		for (i = 1; i < 9; i++) 
		{
			for (j = 1; j < 9; j++)
			{
				starch[i][j] = 1;
			}
		}
	}
}
コード例 #12
0
ファイル: events.c プロジェクト: aichao/sst
void snova(int insx, int insy) {
	int comdead, nqx, nqy, nsx, nsy, num, kldead, iscdead;
	int nrmdead, npdead;
	int insipient=0;

	nsx = insy;
	nsy = insy;

	if (insy== 0) {
		if (insx == 1) {
			/* NOVAMAX being used */
			nqx = probecx;
			nqy = probecy;
		}
		else {
			int stars = 0;
			/* Scheduled supernova -- select star */
			/* logic changed here so that we won't favor quadrants in top
			left of universe */
			for (nqx = 1; nqx<=8; nqx++) {
				for (nqy = 1; nqy<=8; nqy++) {
					stars += d.galaxy[nqx][nqy] % 10;
				}
			}
			if (stars == 0) return; /* nothing to supernova exists */
			num = Rand()*stars + 1;
			for (nqx = 1; nqx<=8; nqx++) {
				for (nqy = 1; nqy<=8; nqy++) {
					num -= d.galaxy[nqx][nqy] % 10;
					if (num <= 0) break;
				}
				if (num <=0) break;
			}
#ifdef DEBUG
			if (idebug) {
				proutn("Super nova here?");
				if (ja()==1) {
					nqx = quadx;
					nqy = quady;
				}
			}
#endif
		}

		if (nqx != quady || nqy != quady || justin != 0) {
			/* it isn't here, or we just entered (treat as inroute) */
			if (damage[DRADIO] == 0.0 || condit == IHDOCKED) {
				skip(1);
				proutn("Message from Starfleet Command       Stardate ");
				cramf(d.date, 0, 1);
				skip(1);
				proutn("     Supernova in");
				cramlc(1, nqx, nqy);
				prout("; caution advised.");
			}
		}
		else {
			/* we are in the quadrant! */
			insipient = 1;
			num = Rand()* (d.galaxy[nqx][nqy]%10) + 1;
			for (nsx=1; nsx < 10; nsx++) {
				for (nsy=1; nsy < 10; nsy++) {
					if (quad[nsx][nsy]==IHSTAR) {
						num--;
						if (num==0) break;
					}
				}
				if (num==0) break;
			}
		}
	}
	else {
		insipient = 1;
	}

	if (insipient) {
		skip(1);
		prouts("***RED ALERT!  RED ALERT!");
		skip(1);
		proutn("***Incipient supernova detected at");
		cramlc(2, nsx, nsy);
		skip(1);
		nqx = quadx;
		nqy = quady;
		if (square(nsx-sectx) + square(nsy-secty) <= 2.1) {
			proutn("Emergency override attempts t");
			prouts("***************");
			skip(1);
			stars();
			alldone=1;
		}
	}
	/* destroy any Klingons in supernovaed quadrant */
	num=d.galaxy[nqx][nqy];
	kldead = num/100;
	comdead = iscdead = 0;
	if (nqx==d.isx && nqy == d.isy) {
		/* did in the Supercommander! */
		d.nscrem = d.isx = d.isy = isatb = iscate = 0;
		iscdead = 1;
		future[FSCMOVE] = future[FSCDBAS] = 1e30;
	}
	d.remkl -= kldead;
	if (d.remcom) {
		int maxloop = d.remcom, l;
		for (l = 1; l <= maxloop; l++) {
			if (d.cx[l] == nqx && d.cy[l] == nqy) {
				d.cx[l] = d.cx[d.remcom];
				d.cy[l] = d.cy[d.remcom];
				d.cx[d.remcom] = d.cy[d.remcom] = 0;
				d.remcom--;
				kldead--;
				comdead++;
				if (d.remcom==0) future[FTBEAM] = 1e30;
				break;
			}
		}
	}
	/* destroy Romulans and planets in supernovaed quadrant */
	num = d.newstuf[nqx][nqy];
	d.newstuf[nqx][nqy] = 0;
	nrmdead = num/10;
	d.nromrem -= nrmdead;
	npdead = num - nrmdead*10;
	if (npdead) {
		int l;
		for (l = 1; l <= inplan; l++)
			if (d.plnets[l].x == nqx && d.plnets[l].y == nqy) {
				d.plnets[l] = nulplanet;
			}
	}
	/* Destroy any base in supernovaed quadrant */
	if (d.rembase) {
		int maxloop = d.rembase, l;
		for (l = 1; l <= maxloop; l++)
			if (d.baseqx[l]==nqx && d.baseqy[l]==nqy) {
				d.baseqx[l] = d.baseqx[d.rembase];
				d.baseqy[l] = d.baseqy[d.rembase];
				d.baseqx[d.rembase] = d.baseqy[d.rembase] = 0;
				d.rembase--;
				break;
			}
	}
	/* If starship caused supernova, tally up destruction */
	if (insx) {
		num = d.galaxy[nqx][nqy] % 100;
		d.starkl += num % 10;
		d.basekl += num/10;
		d.killk += kldead;
		d.killc += comdead;
		d.nromkl += nrmdead;
		d.nplankl += npdead;
		d.nsckill += iscdead;
	}
	/* mark supernova in galaxy and in star chart */
	if ((quadx == nqx && quady == nqy) ||
		damage[DRADIO] == 0 ||
		condit == IHDOCKED)
		starch[nqx][nqy] = 1;
	d.galaxy[nqx][nqy] = 1000;
	/* If supernova destroys last klingons give special message */
	if (d.remkl==0 && (nqx != quadx || nqy != quady)) {
		skip(2);
		if (insx == 0) prout("Lucky you!");
		proutn("A supernova in");
		cramlc(1, nqx, nqy);
		prout(" has just destroyed the last Klingons.");
		finish(FWON);
		return;
	}
	/* if some Klingons remain, continue or die in supernova */
	if (alldone) finish(FSNOVAED);
	return;
}
コード例 #13
0
ファイル: ilp.cpp プロジェクト: pyongjoo/diverse
void ILP::sample() {
    
    PPReader& reader = handler->get_reader();
    
    
    // Read in all the data to this->data
    point *p;
    while ((p = reader.get())) {
        data.push_back(*p);
    }
    delete p;
    
    
    // Encode the problem into ILP
    uint N = data.size();
    
    glp_prob *lp = glp_create_prob();
    glp_set_obj_dir(lp, GLP_MIN);
    
    glp_add_rows(lp, 1 + 3*N*(N-1)/2);
    glp_add_cols(lp, N + N*(N-1)/2);
    
    vector<int> ia(1, 0);
    vector<int> ja(1, 0);
    vector<double> ar(1, 0.0);
    
    for (uint i = 1; i <= N; i++) {
        glp_set_obj_coef(lp, i, 0);
        glp_set_col_bnds(lp, i, GLP_DB, 0.0, 1.0);
        glp_set_col_kind(lp, i, GLP_BV);
    }
    
    for (uint i = 1; i <= N; i++) {
        ia.push_back(1);
        ja.push_back(i);
        ar.push_back(1.0);
    }
    glp_set_row_bnds(lp, 1, GLP_FX, K, K);
    
    // Set:
    // 1. coefficient for objective
    // 2. row bounds
    // 3. column bounds
    // 4. coefficient matrix for constraints
    uint k = 1;
    for (uint i = 1; i <= N-1; i++) {
        for (uint j = i+1; j <= N; j++) {
            point a = data[i-1];
            point b = data[j-1];
            
            // object coefficient and column bounds
            double l = handler->loss(handler->dist(a, b));
            glp_set_obj_coef(lp, N+k, l);
            glp_set_col_bnds(lp, N+k, GLP_DB, 0.0, 1.0);
            glp_set_col_kind(lp, N+k, GLP_BV);
            
            // row bounds
            glp_set_row_bnds(lp, 1 + (k-1)*3 + 1, GLP_LO, 0.0, 1.0);
            glp_set_row_bnds(lp, 1 + (k-1)*3 + 2, GLP_LO, 0.0, 1.0);
            glp_set_row_bnds(lp, 1 + (k-1)*3 + 3, GLP_LO, -1.0, 1.0);
            
            // coefficient matrix
            ia.push_back(1 + (k-1)*3 + 1);
            ja.push_back(i);
            ar.push_back(1.0);
            
            ia.push_back(1 + (k-1)*3 + 1);
            ja.push_back(N+k);
            ar.push_back(-1.0);
            
            ia.push_back(1 + (k-1)*3 + 2);
            ja.push_back(j);
            ar.push_back(1.0);
            
            ia.push_back(1 + (k-1)*3 + 2);
            ja.push_back(N+k);
            ar.push_back(-1.0);
            
            ia.push_back(1 + (k-1)*3 + 3);
            ja.push_back(i);
            ar.push_back(-1.0);
            
            ia.push_back(1 + (k-1)*3 + 3);
            ja.push_back(j);
            ar.push_back(-1.0);
            
            ia.push_back(1 + (k-1)*3 + 3);
            ja.push_back(N+k);
            ar.push_back(1.0);
            
            k++;
        }             
    }
    
    int* ia_a = &ia[0];
    int* ja_a = &ja[0];
    double* ar_a = &ar[0];
        
    glp_load_matrix(lp, ia.size()-1, ia_a, ja_a, ar_a);
    
    glp_iocp parm;
    glp_init_iocp(&parm);
    parm.presolve = GLP_ON;
    parm.msg_lev = GLP_MSG_OFF;
    
    int ret = glp_intopt(lp, &parm);
    
//    cout << "program returned: " << ret << endl;
    
    
    // Collect processed results
    for (uint i = 1; i <= N; i++) {
        double x = glp_mip_col_val(lp, i);
        if (x == 1.0) {
            sampled.push_back(data[i-1]);
        }
    }
}
コード例 #14
0
AmesosBTF_CrsMatrix::NewTypeRef
AmesosBTF_CrsMatrix::
operator()( OriginalTypeRef orig )
{
  origObj_ = &orig;
  const Epetra_BlockMap & OldRowMap = orig.RowMap();
  const Epetra_BlockMap & OldColMap = orig.ColMap();
  
  // Check if the matrix is on one processor.
  int myMatProc = -1, matProc = -1;
  int myPID = orig.Comm().MyPID();
  for (int proc=0; proc<orig.Comm().NumProc(); proc++) 
  {
    if (orig.NumGlobalNonzeros() == orig.NumMyNonzeros())
      myMatProc = myPID;
  }
  orig.Comm().MaxAll( &myMatProc, &matProc, 1 );
  
  if( orig.RowMap().DistributedGlobal() && matProc == -1)
    { cout << "FAIL for Global!\n"; abort(); }
  if( orig.IndicesAreGlobal() && matProc == -1)
    { cout << "FAIL for Global Indices!\n"; abort(); }
 
  int nGlobal = orig.NumGlobalRows(); 
  int n = orig.NumMyRows();
  int nnz = orig.NumMyNonzeros();
  
  if( debug_ )
  {
    cout << "Orig Matrix:\n";
    cout << orig << endl;
  }

  // Create std CRS format (without elements above the threshold)
  vector<int> ia(n+1,0);
  int maxEntries = orig.MaxNumEntries();
  vector<int> ja(nnz), ja_tmp(nnz);
  vector<double> jva_tmp(maxEntries);
  int cnt;

  Epetra_CrsGraph strippedGraph( Copy, OldRowMap, OldColMap, 0 );

  for( int i = 0; i < n; ++i )
  {
    orig.ExtractMyRowCopy( i, maxEntries, cnt, &jva_tmp[0], &ja_tmp[0] );
    ia[i+1] = ia[i];
    for( int j = 0; j < cnt; ++j )
      if( fabs(jva_tmp[j]) > threshold_ )
        ja[ ia[i+1]++ ] = ja_tmp[j];

    int new_cnt = ia[i+1] - ia[i];
    strippedGraph.InsertMyIndices( i, new_cnt, &ja[ ia[i] ] );
  }
  nnz = ia[n];
  strippedGraph.FillComplete();
  
  if( debug_ )
  {
    cout << "Stripped Graph\n";
    cout << strippedGraph;
  }

  // Compute the BTF permutation only on the processor that has the graph.
  if ( matProc == myPID ) {
    
    if( debug_ )
      {
	cout << "-----------------------------------------\n";
	cout << "CRS Format Graph (stripped) \n";
	cout << "-----------------------------------------\n";
	for( int i = 0; i < n; ++i )
	  {
	    cout << ia[i] << " - " << ia[i+1] << " : ";
	    for( int j = ia[i]; j<ia[i+1]; ++j )
	      cout << " " << ja[j];
	    cout << endl;
	  }
	cout << "-----------------------------------------\n";
      }
  
    // Transpose the graph, not the values
    int j=0, next=0;
    vector<int> ia_tmp(n+1,0);

    // Compute row lengths
    for (int i = 0; i < n; i++)
        for (int k = ia[i]; k < ia[i+1]; k++)
            ++ia_tmp[ ja[k]+1 ];

    // Compute pointers from row lengths
    ia_tmp[0] = 0;
    for (int i = 0; i < n; i++)
        ia_tmp[i+1] += ia_tmp[i];

    // Copy over indices
    for (int i = 0; i < n; i++) {
        for (int k = ia[i]; k < ia[i+1]; k++) {
            j = ja[k];
            next = ia_tmp[j];
            ja_tmp[next] = i;
            ia_tmp[j] = next + 1;
        }
    }

    // Reshift ia_tmp
    for (int i=n-1; i >= 0; i--) ia_tmp[i+1] = ia_tmp[i];
    ia_tmp[0] = 0;

    // Transformation information
    int numMatch = 0;       // number of nonzeros on diagonal after permutation.
    double maxWork =  0.0;  // no limit on how much work to perform in max-trans.
    double workPerf = 0.0;  // how much work was performed in max-trans.
    
    // Create a work vector for the BTF code.
    vector<int> work(5*n);
    
    // Storage for the row and column permutations.
    vector<int> rowperm(n);
    vector<int> colperm(n);
    vector<int> blockptr(n+1);
    
    // NOTE:  The permutations are sent in backwards since the matrix is transposed.
    // On output, rowperm and colperm are the row and column permutations of A, where 
    // i = BTF_UNFLIP(rowperm[k]) if row i of A is the kth row of P*A*Q, and j = colperm[k] 
    // if column j of A is the kth column of P*A*Q.  If rowperm[k] < 0, then the 
    // (k,k)th entry in P*A*Q is structurally zero.
    
    numBlocks_ = amesos_btf_order( n, &ia_tmp[0], &ja_tmp[0], maxWork, &workPerf,
			    &rowperm[0], &colperm[0], &blockptr[0], 
			    &numMatch, &work[0] );
    
    // Reverse ordering of permutation to get upper triangular form, if necessary.
    rowPerm_.resize( n );
    colPerm_.resize( n ); 
    blockptr.resize( numBlocks_+1 );
    blockPtr_.resize( numBlocks_+1 );
    if (!upperTri_) {
      for( int i = 0; i < n; ++i )
	{
	  rowPerm_[i] = BTF_UNFLIP(rowperm[(n-1)-i]);
	  colPerm_[i] = colperm[(n-1)-i];
	}
      for( int i = 0; i < numBlocks_+1; ++i ) 
	{
	  blockPtr_[i] = n - blockptr[numBlocks_-i];
	}
    }
    else {
      colPerm_ = colperm;
      blockPtr_ = blockptr;
      for( int i = 0; i < n; ++i )
	{
	  rowPerm_[i] = BTF_UNFLIP(rowperm[i]);
	}
    }
    
    if( debug_ ) {
      cout << "-----------------------------------------\n";
      cout << "BTF Output (n = " << n << ")\n";
      cout << "-----------------------------------------\n";
      cout << "Num Blocks: " << numBlocks_ << endl;
      cout << "Num NNZ Diags: " << numMatch << endl;
      cout << "RowPerm and ColPerm \n";
      for( int i = 0; i<n; ++i )
	cout << rowPerm_[i] << "\t" << colPerm_[i] << endl;
      cout << "-----------------------------------------\n";
    }  
  }

  // Broadcast the BTF permutation information to all processors.
  rowPerm_.resize( nGlobal );
  colPerm_.resize( nGlobal );

  orig.Comm().Broadcast(&rowPerm_[0], nGlobal, matProc);
  orig.Comm().Broadcast(&colPerm_[0], nGlobal, matProc);
  orig.Comm().Broadcast(&numBlocks_, 1, matProc);

  blockPtr_.resize( numBlocks_+1 );
  orig.Comm().Broadcast(&blockPtr_[0], numBlocks_+1, matProc);
  
  //Generate New Domain and Range Maps
  //for now, assume they start out as identical
  vector<int> myElements( n );
  OldRowMap.MyGlobalElements( &myElements[0] );
  
  vector<int> newDomainElements( n );
  vector<int> newRangeElements( n );
  for( int i = 0; i < n; ++i )
  {
    newRangeElements[ i ] = myElements[ rowPerm_[i] ];
    newDomainElements[ i ] = myElements[ colPerm_[i] ];
  }

  NewRowMap_ = Teuchos::rcp( new Epetra_Map( nGlobal, n, &newRangeElements[0], OldRowMap.IndexBase(), OldRowMap.Comm() ) );
  NewColMap_ = Teuchos::rcp( new Epetra_Map( nGlobal, n, &newDomainElements[0], OldColMap.IndexBase(), OldColMap.Comm() ) );

  if( debug_ )
  {
    cout << "New Row Map\n";
    cout << *NewRowMap_ << endl;
    cout << "New Col Map\n";
    cout << *NewColMap_ << endl;
  }

  //Generate New Graph
  NewGraph_ = Teuchos::rcp( new Epetra_CrsGraph( Copy, *NewRowMap_, *NewColMap_, 0 ) );
  Importer_ = Teuchos::rcp( new Epetra_Import( *NewRowMap_, OldRowMap ) );
  NewGraph_->Import( strippedGraph, *Importer_, Insert );
  NewGraph_->FillComplete();

  if( debug_ )
  {
    cout << "NewGraph\n";
    cout << *NewGraph_;
  }

  NewMatrix_ = Teuchos::rcp( new Epetra_CrsMatrix( Copy, *NewGraph_ ) );
  NewMatrix_->Import( orig, *Importer_, Insert );
  NewMatrix_->FillComplete();

  if( debug_ )
  {
    cout << "New CrsMatrix\n";
    cout << *NewMatrix_ << endl;
  }

  newObj_ = &*NewMatrix_;

  return *NewMatrix_;
}
コード例 #15
0
void CTestClient::onTriggerMenu(Node* node, void* resp)
{
    MT->print("case encounter");
    
    m_caseState = CASE_STATE::Encounter;
    
    CCPomeloReponse* ccpomeloresp = (CCPomeloReponse*)resp;
    CJsonT docs(ccpomeloresp->docs);
    
    int type = docs.getInt("menuType");
    if (type == (int)FBDefs::MENU_TYPE::NONE)
    {
        return;
    }
    
    CC_ASSERT(type >= 0 && type < (unsigned int)FBDefs::MENU_TYPE::NONE);
    
    
    json_t* players = nullptr;

    decltype(m_testCase->m_atk)* tpInfo = nullptr;
    if (isAttacking())
    {
        players = docs.getChild("attackPlayers");
        tpInfo = &(m_testCase->m_atk);
        CCLOG("attack");
    }
    else
    {
        players = docs.getChild("defendplayers");
        tpInfo = &(m_testCase->m_def);
        CCLOG("def");
    }
    CJsonTArray ja(players);
    
    for (int i = 0; i < ja.size(); ++i)
    {
        auto playerId = ja.get(i).toInt();
        MT->print("playerId: %d", playerId);
        for (auto info : *tpInfo)
        {
            if (info->playerNumber == playerId)
            {
                // 发送命令
                CJsonT msg;
                if (isAttacking())
                {
                    MT->printA("%s", CTestPlayerInfo::ins_str[(int)info->instruction].c_str());
                }
                log("ins: %d", (unsigned int)info->instruction);
                msg.setChild("cmd", (unsigned int)info->instruction);
                if (isAttacking() && (*tpInfo).size() > 1)
                {
                    msg.setChild("targetPlayerId", (unsigned int)(*tpInfo)[1]->playerNumber);
                }
                
                m_pomelo->request("match.matchHandler.menuCmd", msg, [this](Node* node, void* resp){
                    CCPomeloReponse* ccpomeloresp = (CCPomeloReponse*)resp;
                    CJsonT docs(ccpomeloresp->docs);
                });
                msg.release();
                break;
            }
        }
    }
}
コード例 #16
0
//==============================================================================
int Ifpack2_AMDReordering::Compute(const Ifpack2_Graph& Graph)
{
  IsComputed_ = false;
  NumMyRows_ = Graph.NumMyRows();
  int NumNz = Graph.NumMyNonzeros();
  
  if (NumMyRows_ == 0)
    IFPACK2_CHK_ERR(-1); // strange graph this one
  
  // Extract CRS format
  vector<int> ia(NumMyRows_+1,0);
  vector<int> ja(NumNz);
  int cnt;
  for( int i = 0; i < NumMyRows_; ++i )
  {
    int * tmpP = &ja[ia[i]];
    Graph.ExtractMyRowCopy( i, NumNz-ia[i], cnt, tmpP );
    ia[i+1] = ia[i] + cnt;
  }

  // Trim down to local only
  vector<int> iat(NumMyRows_+1);
  vector<int> jat(NumNz);
  int loc = 0;
  for( int i = 0; i < NumMyRows_; ++i )
  {
    iat[i] = loc;
    for( int j = ia[i]; j < ia[i+1]; ++j )
    {
      if( ja[j] < NumMyRows_ )
        jat[loc++] = ja[j];
      else
	break;
    }
  }
  iat[NumMyRows_] = loc;

  // Compute AMD permutation
  Reorder_.resize(NumMyRows_);
  vector<double> info(AMD_INFO);

  amesos_amd_order( NumMyRows_, &iat[0], &jat[0], &Reorder_[0], NULL, &info[0] );

  if( info[AMD_STATUS] == AMD_INVALID )
    cout << "AMD ORDERING: Invalid!!!!\n";

  // Build inverse reorder (will be used by ExtractMyRowCopy() 
  InvReorder_.resize(NumMyRows_);

  for (int i = 0 ; i < NumMyRows_ ; ++i)
    InvReorder_[i] = -1;

  for (int i = 0 ; i < NumMyRows_ ; ++i)
    InvReorder_[Reorder_[i]] = i;

  for (int i = 0 ; i < NumMyRows_ ; ++i) {
    if (InvReorder_[i] == -1)
      IFPACK2_CHK_ERR(-1);
  }

  IsComputed_ = true;
  return(0);
}
コード例 #17
0
CrsGraph_AMD::NewTypeRef
CrsGraph_AMD::
operator()( OriginalTypeRef orig )
{
  origObj_ = &orig;

  int n = orig.NumMyRows();
  int nnz = orig.NumMyNonzeros();

  //create std CRS format
  std::vector<int> ia(n+1,0);
  std::vector<int> ja(nnz);
  int cnt;
  for( int i = 0; i < n; ++i )
  {
    int * tmpP = &ja[ia[i]];
    orig.ExtractMyRowCopy( i, nnz-ia[i], cnt, tmpP );
    ia[i+1] = ia[i] + cnt;
  }

  //trim down to local only
  std::vector<int> iat(n+1);
  std::vector<int> jat(nnz);
  int loc = 0;
  for( int i = 0; i < n; ++i )
  {
    iat[i] = loc;
    for( int j = ia[i]; j < ia[i+1]; ++j )
    {
      if( ja[j] < n )
        jat[loc++] = ja[j];
      else
	break;
    }
  }
  iat[n] = loc;


  if( verbose_ )
  {
    std::cout << "Orig Graph\n";
    std::cout << orig << std::endl;
    std::cout << "-----------------------------------------\n";
    std::cout << "CRS Format Graph\n";
    std::cout << "-----------------------------------------\n";
    for( int i = 0; i < n; ++i )
    {
      std::cout << i << ": " << iat[i+1] << ": ";
      for( int j = iat[i]; j<iat[i+1]; ++j )
        std::cout << " " << jat[j];
      std::cout << std::endl;
    }
    std::cout << "-----------------------------------------\n";
  }

  std::vector<int> perm(n);
  std::vector<double> info(AMD_INFO);

  amd_order( n, &iat[0], &jat[0], &perm[0], NULL, &info[0] ); 

  if( info[AMD_STATUS] == AMD_INVALID )
    std::cout << "AMD ORDERING: Invalid!!!!\n";

  if( verbose_ )
  {
    std::cout << "-----------------------------------------\n";
    std::cout << "AMD Output\n";
    std::cout << "-----------------------------------------\n";
    std::cout << "STATUS: " << info[AMD_STATUS] << std::endl;
    std::cout << "SYMM: " << info[AMD_SYMMETRY] << std::endl;
    std::cout << "N: " << info[AMD_N] << std::endl;
    std::cout << "NZ: " << info[AMD_NZ] << std::endl;
    std::cout << "SYMM: " << info[AMD_SYMMETRY] << std::endl;
    std::cout << "NZDIAG: " << info[AMD_NZDIAG] << std::endl;
    std::cout << "NZ A+At: " << info[AMD_NZ_A_PLUS_AT] << std::endl;
    std::cout << "NDENSE: " << info[AMD_SYMMETRY] << std::endl;
    std::cout << "Perm\n";
    for( int i = 0; i<n; ++i )
      std::cout << perm[i] << std::endl;
    std::cout << "-----------------------------------------\n";
  }

  //Generate New Domain and Range Maps
  //for now, assume they start out as identical
  const Epetra_BlockMap & OldMap = orig.RowMap();
  int nG = orig.NumGlobalRows();

  std::vector<int> newElements( n );
  for( int i = 0; i < n; ++i )
    newElements[i] = OldMap.GID( perm[i] );

  NewMap_ = new Epetra_Map( nG, n, &newElements[0], OldMap.IndexBase(), OldMap.Comm() );

  if( verbose_ )
  {
    std::cout << "Old Map\n";
    std::cout << OldMap << std::endl;
    std::cout << "New Map\n";
    std::cout << *NewMap_ << std::endl;
  }

  //Generate New Graph
  NewGraph_ = new Epetra_CrsGraph( Copy, *NewMap_, 0 );
  Epetra_Import Importer( *NewMap_, OldMap );
  NewGraph_->Import( orig, Importer, Insert );
  NewGraph_->FillComplete();

  if( verbose_ )
  {
    std::cout << "New CrsGraph\n";
    std::cout << *NewGraph_ << std::endl;
  }

  newObj_ = NewGraph_;

  return *NewGraph_;
}
コード例 #18
0
//==========================================================================
int Ifpack_SPARSKIT::Compute() 
{
  if (!IsInitialized()) 
    IFPACK_CHK_ERR(Initialize());

  IsComputed_ = false;

  // convert the matrix into SPARSKIT format. The matrix is then
  // free'd after method Compute() returns.

  // convert the matrix into CSR format. Note that nnz is an over-estimate,
  // since it contains the nonzeros corresponding to external nodes as well.
  int n   = Matrix().NumMyRows();
  int nnz = Matrix().NumMyNonzeros();

  vector<double> a(nnz);
  vector<int>    ja(nnz);
  vector<int>    ia(n + 1);

  const int MaxNumEntries = Matrix().MaxNumEntries();

  vector<double> Values(MaxNumEntries);
  vector<int>    Indices(MaxNumEntries);

  int count = 0;

  ia[0] = 1;
  for (int i = 0 ; i < n ; ++i)
  {
    int NumEntries;
    int NumMyEntries = 0;
    Matrix().ExtractMyRowCopy(i, MaxNumEntries, NumEntries, &Values[0], 
                              &Indices[0]);

    // NOTE: There might be some issues here with the ILU(0) if the column indices aren't sorted.
    // The other factorizations are probably OK.

    for (int j = 0 ; j < NumEntries ; ++j)
    {
      if (Indices[j] < n) // skip non-local columns
      {
        a[count]  = Values[j];
        ja[count] = Indices[j] + 1; // SPARSKIT is FORTRAN
        ++count;
        ++NumMyEntries;
      }
    }
    ia[i + 1] = ia[i] + NumMyEntries;
  }

  if (mbloc_ == -1) mbloc_ = n;

  int iwk;

  if (Type_ == "ILUT" || Type_ == "ILUTP" || Type_ == "ILUD" ||
      Type_ == "ILUDP")
    iwk = nnz + 2 * lfil_ * n;
  else if (Type_ == "ILUK")
    iwk = (2 * lfil_ + 1) * nnz + 1;
  else if (Type_ == "ILU0")
    iwk = nnz+2;

  int ierr = 0;

  alu_.resize(iwk);
  jlu_.resize(iwk);
  ju_.resize(n + 1);

  vector<int>    jw(n + 1);
  vector<double> w(n + 1);

  if (Type_ == "ILUT")
  {
    jw.resize(2 * n);
    F77_ILUT(&n, &a[0], &ja[0], &ia[0], &lfil_, &droptol_,
             &alu_[0], &jlu_[0], &ju_[0], &iwk, &w[0], &jw[0], &ierr);
  }
  else if (Type_ == "ILUD")
  {
    jw.resize(2 * n);
    F77_ILUD(&n, &a[0], &ja[0], &ia[0], &alph_, &tol_,
             &alu_[0], &jlu_[0], &ju_[0], &iwk, &w[0], &jw[0], &ierr);
  }
  else if (Type_ == "ILUTP")
  {
    jw.resize(2 * n);
    iperm_.resize(2 * n);
    F77_ILUTP(&n, &a[0], &ja[0], &ia[0], &lfil_, &droptol_, &permtol_, 
              &mbloc_, &alu_[0], &jlu_[0], &ju_[0], &iwk, &w[0], &jw[0],
              &iperm_[0], &ierr);
    for (int i = 0 ; i < n ; ++i)
      iperm_[i]--;
  }
  else if (Type_ == "ILUDP")
  {
    jw.resize(2 * n);
    iperm_.resize(2 * n);
    F77_ILUDP(&n, &a[0], &ja[0], &ia[0], &alph_, &droptol_, &permtol_, 
              &mbloc_, &alu_[0], &jlu_[0], &ju_[0], &n, &w[0], &jw[0],
              &iperm_[0], &ierr);
    for (int i = 0 ; i < n ; ++i)
      iperm_[i]--;
  }
  else if (Type_ == "ILUK")
  {
    vector<int> levs(iwk);
    jw.resize(3 * n);
    F77_ILUK(&n, &a[0], &ja[0], &ia[0], &lfil_, 
             &alu_[0], &jlu_[0], &ju_[0], &levs[0], &iwk, &w[0], &jw[0], &ierr);
  }
  else if (Type_ == "ILU0")
  {
    // here w is only of size n
    jw.resize(2 * n);
    F77_ILU0(&n, &a[0], &ja[0], &ia[0], 
             &alu_[0], &jlu_[0], &ju_[0], &jw[0], &ierr);
  }
  IFPACK_CHK_ERR(ierr);

  IsComputed_ = true;
  return(0);
}
コード例 #19
0
ファイル: ai.c プロジェクト: aichao/sst
void scom(int *ipage) {
	int i, i2, j, ideltax, ideltay, ibqx, ibqy, sx, sy, ifindit, iwhichb;
	int iqx, iqy;
	int basetbl[6];
	double bdist[6];
	int flag;
#ifdef DEBUG
	if (idebug) prout("SCOM");
#endif

	/* Decide on being active or passive */
	flag = ((d.killc+d.killk)/(d.date+0.01-indate) < 0.1*skill*(skill+1.0) ||
			(d.date-indate) < 3.0);
	if (iscate==0 && flag) {
		/* compute move away from Enterprise */
		ideltax = d.isx-quadx;
		ideltay = d.isy-quady;
		if (sqrt(ideltax*(double)ideltax+ideltay*(double)ideltay) > 2.0) {
			/* circulate in space */
			ideltax = d.isy-quady;
			ideltay = quadx-d.isx;
		}
	}
	else {
		/* compute distances to starbases */
		if (d.rembase <= 0) {
			/* nothing left to do */
			future[FSCMOVE] = 1e30;
			return;
		}
		sx = d.isx;
		sy = d.isy;
		for (i = 1; i <= d.rembase; i++) {
			basetbl[i] = i;
			ibqx = d.baseqx[i];
			ibqy = d.baseqy[i];
			bdist[i] = sqrt(square(ibqx-sx) + square(ibqy-sy));
		}
		if (d.rembase > 1) {
			/* sort into nearest first order */
			int iswitch;
			do {
				iswitch = 0;
				for (i=1; i < d.rembase-1; i++) {
					if (bdist[i] > bdist[i+1]) {
						int ti = basetbl[i];
						double t = bdist[i];
						bdist[i] = bdist[i+1];
						bdist[i+1] = t;
						basetbl[i] = basetbl[i+1];
						basetbl[i+1] =ti;
						iswitch = 1;
					}
				}
			} while (iswitch);
		}
		/* look for nearest base without a commander, no Enterprise, and
		   without too many Klingons, and not already under attack. */
		ifindit = iwhichb = 0;

		for (i2 = 1; i2 <= d.rembase; i2++) {
			i = basetbl[i2];	/* bug in original had it not finding nearest*/
			ibqx = d.baseqx[i];
			ibqy = d.baseqy[i];
			if ((ibqx == quadx && ibqy == quady) ||
				(ibqx == batx && ibqy == baty) ||
				d.galaxy[ibqx][ibqy] > 899) continue;
			/* if there is a commander, an no other base is appropriate,
			   we will take the one with the commander */
			for (j = 1; j <= d.remcom; j++) {
				if (ibqx==d.cx[j] && ibqy==d.cy[j] && ifindit!= 2) {
						ifindit = 2;
						iwhichb = i;
						break;
				}
			}
			if (j > d.remcom) { /* no commander -- use this one */
				ifindit = 1;
				iwhichb = i;
				break;
			}
		}
		if (ifindit==0) return; /* Nothing suitable -- wait until next time*/
		ibqx = d.baseqx[iwhichb];
		ibqy = d.baseqy[iwhichb];
		/* decide how to move toward base */
		ideltax = ibqx - d.isx;
		ideltay = ibqy - d.isy;
	}
	/* Maximum movement is 1 quadrant in either or both axis */
	if (ideltax > 1) ideltax = 1;
	if (ideltax < -1) ideltax = -1;
	if (ideltay > 1) ideltay = 1;
	if (ideltay < -1) ideltay = -1;

	/* try moving in both x and y directions */
	iqx = d.isx + ideltax;
	iqy = d.isy + ideltax;
	if (checkdest(iqx, iqy, flag, ipage)) {
		/* failed -- try some other maneuvers */
		if (ideltax==0 || ideltay==0) {
			/* attempt angle move */
			if (ideltax != 0) {
				iqy = d.isy + 1;
				if (checkdest(iqx, iqy, flag, ipage)) {
					iqy = d.isy - 1;
					checkdest(iqx, iqy, flag, ipage);
				}
			}
			else {
				iqx = d.isx + 1;
				if (checkdest(iqx, iqy, flag, ipage)) {
					iqx = d.isx - 1;
					checkdest(iqx, iqy, flag, ipage);
				}
			}
		}
		else {
			/* try moving just in x or y */
			iqy = d.isy;
			if (checkdest(iqx, iqy, flag, ipage)) {
				iqy = d.isy + ideltay;
				iqx = d.isx;
				checkdest(iqx, iqy, flag, ipage);
			}
		}
	}
	/* check for a base */
	if (d.rembase == 0) {
		future[FSCMOVE] = 1e30;
	}
	else for (i=1; i<=d.rembase; i++) {
		ibqx = d.baseqx[i];
		ibqy = d.baseqy[i];
		if (ibqx==d.isx && ibqy == d.isy && d.isx != batx && d.isy != baty) {
			/* attack the base */
			if (flag) return; /* no, don't attack base! */
			iseenit = 0;
			isatb=1;
			future[FSCDBAS] = d.date + 1.0 +2.0*Rand();
			if (batx != 0) future[FSCDBAS] += future[FCDBAS]-d.date;
			if (damage[DRADIO] > 0 && condit != IHDOCKED)
				return; /* no warning */
			iseenit = 1;
			if (*ipage == 0)  pause(1);
			*ipage=1;
			proutn("Lt. Uhura-  \"Captain, the starbase in");
			cramlc(1, d.isx, d.isy);
			skip(1);
			prout("   reports that it is under attack from the Klingon Super-commander.");
			proutn("   It can survive until stardate ");
			cramf(future[FSCDBAS], 0, 1);
			prout(" .\"");
			if (resting==0) return;
			prout("Mr. Spock-  \"Captain, shall we cancel the rest period?\"");
			if (ja()==0) return;
			resting = 0;
			Time = 0.0; /* actually finished */
			return;
		}
	}
	/* Check for intelligence report */
	if (
#ifdef DEBUG
		idebug==0 &&
#endif
		(Rand() > 0.2 ||
		 (damage[DRADIO] > 0.0 && condit != IHDOCKED) ||
		 starch[d.isx][d.isy] > 0))
		return;
	if (*ipage==0) pause(1);
	*ipage = 1;
	prout("Lt. Uhura-  \"Captain, Starfleet Intelligence reports");
	proutn("   the Super-commander is in");
	cramlc(1, d.isx, d.isy);
	prout(".\"");
	return;
}
コード例 #20
0
ファイル: events.c プロジェクト: aichao/sst
void events(void) {

	int ictbeam=0, ipage=0, istract=0, line, i, j, k, l, ixhold, iyhold;
	double fintim = d.date + Time, datemin, xtime, repair, yank;
	

#ifdef DEBUG
	if (idebug) prout("EVENTS");
#endif

	if (stdamtim == 1e30 && damage[DRADIO] != 0.0) {
		/* chart will no longer be updated because radio is dead */
		stdamtim = d.date;
		for (i=1; i <= 8 ; i++)
			for (j=1; j <= 8; j++)
				if (starch[i][j] == 1) starch[i][j] = d.galaxy[i][j]+1000;
	}

	for (;;) {
		/* Select earliest extraneous event, line==0 if no events */
		line = FSPY;
		if (alldone) return;
		datemin = fintim;
		for (l=1; l<=NEVENTS; l++)
			if (future[l] <= datemin) {
				line = l;
				datemin = future[l];
			}
		xtime = datemin-d.date;
		d.date = datemin;
		/* Decrement Federation resources and recompute remaining time */
		d.remres -= (d.remkl+4*d.remcom)*xtime;
		d.remtime = d.remres/(d.remkl+4*d.remcom);
		if (d.remtime <=0) {
			finish(FDEPLETE);
			return;
		}
		/* Is life support adequate? */
		if (damage[DLIFSUP] && condit != IHDOCKED) {
			if (lsupres < xtime && damage[DLIFSUP] > lsupres) {
				finish(FLIFESUP);
				return;
			}
			lsupres -= xtime;
			if (damage[DLIFSUP] <= xtime) lsupres = inlsr;
		}
		/* Fix devices */
		repair = xtime;
		if (condit == IHDOCKED) repair /= docfac;
		/* Don't fix Deathray here */
		for (l=1; l<=ndevice; l++)
			if (damage[l] > 0.0 && l != DDRAY)
				damage[l] -= (damage[l]-repair > 0.0 ? repair : damage[l]);
		/* If radio repaired, update star chart and attack reports */
		if (stdamtim != 1e30 && damage[DRADIO] == 0.0) {
			stdamtim = 1e30;
			prout("Lt. Uhura- \"Captain, the sub-space radio is working and");
			prout("   surveillance reports are coming in.");
			skip(1);
			for (i=1; i <= 8 ; i++)
				for (j=1; j <= 8; j++)
					if (starch[i][j] > 999) starch[i][j] = 1;
			if (iseenit==0) {
				attakreport();
				iseenit = 1;
			}
			skip(1);
			prout("   The star chart is now up to date.\"");
			skip(1);
		}
		/* Cause extraneous event LINE to occur */
		Time -= xtime;
		switch (line) {
			case FSNOVA: /* Supernova */
				if (ipage==0) pause(1);
				ipage=1;
				snova(0,0);
				future[FSNOVA] = d.date + expran(0.5*intime);
				if (d.galaxy[quadx][quady] == 1000) return;
				break;
			case FSPY: /* Check with spy to see if S.C. should tractor beam */
				if (d.nscrem == 0 ||
					ictbeam+istract > 0 ||
					condit==IHDOCKED || isatb==1 || iscate==1) return;
				if (ientesc ||
					(energy < 2000 && torps < 4 && shield < 1250) ||
					(damage[DPHASER]>0 && (damage[DPHOTON]>0 || torps < 4)) ||
					(damage[DSHIELD] > 0 &&
					 (energy < 2500 || damage[DPHASER] > 0) &&
					 (torps < 5 || damage[DPHOTON] > 0))) {
					/* Tractor-beam her! */
					istract=1;
					yank = square(d.isx-quadx) + square(d.isy-quady);
					/*********TBEAM CODE***********/
				}
				else return;
			case FTBEAM: /* Tractor beam */
				if (line==FTBEAM) {
					if (d.remcom == 0) {
						future[FTBEAM] = 1e30;
						break;
					}
					i = Rand()*d.remcom+1.0;
					yank = square(d.cx[i]-quadx) + square(d.cy[i]-quady);
					if (istract || condit == IHDOCKED || yank == 0) {
						/* Drats! Have to reschedule */
						future[FTBEAM] = d.date + Time +
										 expran(1.5*intime/d.remcom);
						break;
					}
				}
				/* tractor beaming cases merge here */
				yank = sqrt(yank);
				if (ipage==0) pause(1);
				ipage=1;
				Time = (10.0/(7.5*7.5))*yank; /* 7.5 is yank rate (warp 7.5) */
				ictbeam = 1;
				skip(1);
				proutn("***");
				crmshp();
				prout(" caught in long range tractor beam--");
				/* If Kirk & Co. screwing around on planet, handle */
				atover(1); /* atover(1) is Grab */
				if (alldone) return;
				if (icraft == 1) { /* Caught in Galileo? */
					finish(FSTRACTOR);
					return;
				}
				/* Check to see if shuttle is aboard */
				if (iscraft==0) {
					skip(1);
					if (Rand() >0.5) {
						prout("Galileo, left on the planet surface, is captured");
						prout("by aliens and made into a flying McDonald's.");
						damage[DSHUTTL] = -10;
						iscraft = -1;
					}
					else {
						prout("Galileo, left on the planet surface, is well hidden.");
					}
				}
				if (line==0) {
					quadx = d.isx;
					quady = d.isy;
				}
				else {
					quadx = d.cx[i];
					quady = d.cy[i];
				}
				iran10(&sectx, &secty);
				crmshp();
				proutn(" is pulled to");
				cramlc(1, quadx, quady);
				proutn(", ");
				cramlc(2, sectx, secty);
				skip(1);
				if (resting) {
					prout("(Remainder of rest/repair period cancelled.)");
					resting = 0;
				}
				if (shldup==0) {
					if (damage[DSHIELD]==0 && shield > 0) {
						sheild(2); /* Shldsup */
						shldchg=0;
					}
					else prout("(Shields not currently useable.)");
				}
				newqad(0);
				/* Adjust finish time to time of tractor beaming */
				fintim = d.date+Time;
				if (d.remcom <= 0) future[FTBEAM] = 1e30;
				else future[FTBEAM] = d.date+Time+expran(1.5*intime/d.remcom);
				break;
			case FSNAP: /* Snapshot of the universe (for time warp) */
				snapsht = d;
				d.snap = 1;
				future[FSNAP] = d.date + expran(0.5 * intime);
				break;
			case FBATTAK: /* Commander attacks starbase */
				if (d.remcom==0 || d.rembase==0) {
					/* no can do */
					future[FBATTAK] = future[FCDBAS] = 1e30;
					break;
				}
				i = 0;
				for (j=1; j<=d.rembase; j++) {
					for (k=1; k<=d.remcom; k++)
						if (d.baseqx[j]==d.cx[k] && d.baseqy[j]==d.cy[k] &&
							(d.baseqx[j]!=quadx || d.baseqy[j]!=quady) &&
							(d.baseqx[j]!=d.isx || d.baseqy[j]!=d.isy)) {
							i = 1;
							break;
						}
					if (i == 1) break;
				}
				if (j>d.rembase) {
					/* no match found -- try later */
					future[FBATTAK] = d.date + expran(0.3*intime);
					future[FCDBAS] = 1e30;
					break;
				}
				/* commander + starbase combination found -- launch attack */
				batx = d.baseqx[j];
				baty = d.baseqy[j];
				future[FCDBAS] = d.date+1.0+3.0*Rand();
				if (isatb) /* extra time if SC already attacking */
					future[FCDBAS] += future[FSCDBAS]-d.date;
				future[FBATTAK] = future[FCDBAS] +expran(0.3*intime);
				iseenit = 0;
				if (damage[DRADIO] != 0.0 &&
					condit != IHDOCKED) break; /* No warning :-( */
				iseenit = 1;
				if (ipage==0) pause(1);
				ipage = 1;
				skip(1);
				proutn("Lt. Uhura-  \"Captain, the starbase in");
				cramlc(1, batx, baty);
				skip(1);
				prout("   reports that it is under atttack and that it can");
				proutn("   hold out only until stardate ");
				cramf(future[FCDBAS],1,1);
				prout(".\"");
				if (resting) {
					skip(1);
					proutn("Mr. Spock-  \"Captain, shall we cancel the rest period?\"");
					if (ja()) {
						resting = 0;
						Time = 0.0;
						return;
					}
				}
				break;
			case FSCDBAS: /* Supercommander destroys base */
				future[FSCDBAS] = 1e30;
				isatb = 2;
				if (d.galaxy[d.isx][d.isy]%100 < 10) break; /* WAS RETURN! */
				ixhold = batx;
				iyhold = baty;
				batx = d.isx;
				baty = d.isy;
			case FCDBAS: /* Commander succeeds in destroying base */
				if (line==FCDBAS) {
					future[FCDBAS] = 1e30;
					/* find the lucky pair */
					for (i = 1; i <= d.remcom; i++)
						if (d.cx[i]==batx && d.cy[i]==baty) break;
					if (i > d.remcom || d.rembase == 0 ||
						d.galaxy[batx][baty] % 100 < 10) {
						/* No action to take after all */
						batx = baty = 0;
						break;
					}
				}
				/* Code merges here for any commander destroying base */
				/* Not perfect, but will have to do */
				if (starch[batx][baty] == -1) starch[batx][baty] = 0;
				/* Handle case where base is in same quadrant as starship */
				if (batx==quadx && baty==quady) {
					if (starch[batx][baty] > 999) starch[batx][baty] -= 10;
					quad[basex][basey]= IHDOT;
					basex=basey=0;
					newcnd();
					skip(1);
					prout("Spock-  \"Captain, I believe the starbase has been destroyed.\"");
				}
				else if (d.rembase != 1 &&
						 (damage[DRADIO] <= 0.0 || condit == IHDOCKED)) {
					/* Get word via subspace radio */
					if (ipage==0) pause(1);
					ipage = 1;
					skip(1);
					prout("Lt. Uhura-  \"Captain, Starfleet Command reports that");
					proutn("   the starbase in");
					cramlc(1, batx, baty);
					prout(" has been destroyed by");
					if (isatb==2) prout("the Klingon Super-Commander");
					else prout("a Klingon Commander");
				}
				/* Remove Starbase from galaxy */
				d.galaxy[batx][baty] -= 10;
				for (i=1; i <= d.rembase; i++)
					if (d.baseqx[i]==batx && d.baseqy[i]==baty) {
						d.baseqx[i]=d.baseqx[d.rembase];
						d.baseqy[i]=d.baseqy[d.rembase];
					}
				d.rembase--;
				if (isatb == 2) {
					/* reinstate a commander's base attack */
					batx = ixhold;
					baty = iyhold;
					isatb = 0;
				}
				else {
					batx = baty = 0;
				}
				break;
			case FSCMOVE: /* Supercommander moves */
				future[FSCMOVE] = d.date+0.2777;
				if (ientesc+istract==0 &&
					isatb!=1 &&
					(iscate!=1 || justin==1)) scom(&ipage);
				break;
			case FDSPROB: /* Move deep space probe */
				future[FDSPROB] = d.date + 0.01;
				probex += probeinx;
				probey += probeiny;
				i = (int)(probex/10 +0.05);
				j = (int)(probey/10 + 0.05);
				if (probecx != i || probecy != j) {
					probecx = i;
					probecy = j;
					if (i < 1 || i > 8 || j < 1 || j > 8 ||
						d.galaxy[probecx][probecy] == 1000) {
						// Left galaxy or ran into supernova
						if (damage[DRADIO]==0.0 || condit == IHDOCKED) {
							if (ipage==0) pause(1);
							ipage = 1;
							skip(1);
							proutn("Lt. Uhura-  \"The deep space probe ");
							if (i < 1 ||i > 8 || j < 1 || j > 8)
								proutn("has left the galaxy");
							else
								proutn("is no longer transmitting");
							prout(".\"");
						}
						future[FDSPROB] = 1e30;
						break;
					}
					if (damage[DRADIO]==0.0   || condit == IHDOCKED) {
						if (ipage==0) pause(1);
						ipage = 1;
						skip(1);
						proutn("Lt. Uhura-  \"The deep space probe is now in ");
						cramlc(1, probecx, probecy);
						prout(".\"");
					}
				}
				/* Update star chart if Radio is working or have access to
				   radio. */
				if (damage[DRADIO] == 0.0 || condit == IHDOCKED)
					starch[probecx][probecy] = damage[DRADIO] > 0.0 ?
										   d.galaxy[probecx][probecy]+1000 : 1;
				proben--; // One less to travel
				if (proben == 0 && isarmed &&
					d.galaxy[probecx][probecy] % 10 > 0) {
					/* lets blow the sucker! */
					snova(1,0);
					future[FDSPROB] = 1e30;
					if (d.galaxy[quadx][quady] == 1000) return;
				}
				break;
		}
	}
}