Ejemplo n.º 1
0
void FlipFlap::show_scores(int i){						//end screen
  stringstream ss;
   if (i == 0)									//if they won
    ss<<"Congratulations, "<<initials<<", you won! Your score was: "<<calc_score(current_flips); //print name and score
  else										//if they lost
    ss<<"Sorry, "<<initials<<", you lost.  Your score was 0.";			//print name 
  end_text = new Text(Point(100,100),ss.str());
  attach(*end_text);
  scores.game_score(initials,calc_score(current_flips));			//write name and score to scores
  scores.write_highscores();
  replay = new Button(Point(100,200),70,20,"Play again?",cb_replay);		//ask if they want to play again
  attach(*replay);
}
Ejemplo n.º 2
0
void FlipFlap::flip(int p){							//flip the top p pancakes
        ++current_flips;							//increment flips player has made
        for(Pancake* pancake : game_stack_p){					//detach old stack from window
                detach(*pancake);
        }
        auto it = std::next(game_stack_p.begin(), (p-1));			//flip order in the list
        reverse(it,game_stack_p.end());
        for(int i = (p-1); i < game_stack.size(); ++i){
                game_stack_p[i] = new Pancake(game_stack_p[i]->get_size(),i);
        }
        for(Pancake* pancake : game_stack_p){					//re-attach the changed pancakes
                attach(*pancake);
        }
        update_boxes();								//update on-screen counters
        redraw();								//redraw window
        if(check_score()){							//if stack is sorted
                for(Pancake* pancake : game_stack_p){				//detach pancake stack
                        detach(*pancake);
                }
                for(int i = 0; i < (current_level-1); ++i)			//detach flip buttons
                        detach(buttons[i]);
                show_scores(0);							//go to show scores (Win)
        }
       if(calc_score(current_flips) == 0){					//if score has hit 0
         for(Pancake* pancake : game_stack_p){					//detach pancakes
                        detach(*pancake);
                }
                for(int i = 0; i < (current_level-1); ++i)
                        detach(buttons[i]);					//detach flip buttons
                show_scores(1);							//go to show scores (Lose)
       }

}
Ejemplo n.º 3
0
/**
 \fn recherche_mot_grille(t_valeurmot mot_dico,t_lettre grille[N][M]);
 \brief recherche un mot dans la grille
 \param (le mot,la grille)
  \return 1 si le mot est present 0 sinon
 */
int recherche_mot_grille(t_valeurmot *mot_dico,t_lettre grille[N][M]){
    int i,j,k=0;
    int chemin_mot_sommet,redondance_lettre_sommet;	
    t_coord chemin_mot_pile[t_max];
    t_coord redondance_lettre_pile[t_max];
	
    /*On recherche la premiere lettre du mot parmis la grille,ce sera nos points de departs*/
    for(i=0;i<N ;i++){
        for(j=0;j<M;j++){
				/*Si on trouve un point de depart*/
               if(grille[i][j].c==mot_dico->mot[k]){
					/*On initialise nos piles de chemin et de redondance*/
                    initpile(&chemin_mot_sommet);
                    initpile(&redondance_lettre_sommet);
					/*On push les coordonnées de depart à nos piles*/
                    push(i,j,chemin_mot_pile,&chemin_mot_sommet);
                    push(i,j,redondance_lettre_pile,&redondance_lettre_sommet);
                    k++;
					/*TANT QUE tout les chemins ne sont pas teste*/
                    while(chemin_mot_sommet!=-1){
                        if(mot_dico->mot[k]=='\0'){
                        		calc_score(mot_dico,chemin_mot_pile,&chemin_mot_sommet,grille);
								return 1;
                        } 
                        chemin(grille,mot_dico->mot[k],&k,chemin_mot_pile,redondance_lettre_pile,&chemin_mot_sommet,&redondance_lettre_sommet); // on cherche le chemin de la prochaine lettre du mot
                    }
               }
        }
    }
	 /*On a parcouru la grille sans trouve de mot on retourne donc 0*/
   return 0;
}
Ejemplo n.º 4
0
void LR::calc_loss(double *loss, float *acc)
{
	double neg_log_likeli = 0.0;
	int err_num = 0;
	//对每个样本的类别计算
	for (size_t i = 0; i < samp_class_vec.size(); i++)
	{
		int samp_class = samp_class_vec[i];
		sparse_feat samp_feat = samp_feat_vec[i];     //获得类别i下所有的样本
		vector<float> score_vec = calc_score(samp_feat);    //计算该类别所有样本的分数
		int pred_class = score_to_class(score_vec);    //将分数映射到类别
		if (pred_class != samp_class)
			err_num += 1;
		vector<float> softmax_vec = softmax(score_vec);
	    for (int j = 0; j < class_set_size; j++)
	    {
			if (j == samp_class)
			{
				double pj = softmax_vec[j];
				double temp = pj < LOG_LIM ? LOG_LIM : pj;
				neg_log_likeli += log(temp);
			}
		}
	}
	*loss = -neg_log_likeli ; // CE(Cross Entropy) loss equals negative log-likelihood in LR
	*acc = 1 - (float)err_num / samp_class_vec.size();
}
Ejemplo n.º 5
0
static long
botl_score(void)
{
    long umoney = money_cnt(invent) + hidden_gold();

    return calc_score(DIED, FALSE, umoney);
}
Ejemplo n.º 6
0
Archivo: sinap.c Proyecto: mkopta/sinap
void sinap(void)
{
	U score_limit = 1000U, accG, accL, dice_count, r_dice_count;
	UC dice[6];
	int c;
	Occurrences o;
	Player a = {0, "A", 0}, b = {1, "B", 0},
	       *p = random_number(0,1) == 0 ? &a : &b;

	while (a.score < score_limit && b.score < score_limit) {
		printf("\nScore: '%s'=%u '%s'=%u. Press enter to continue..",
				a.name, a.score, b.name, b.score);
		(void) fflush(stdout);
		while (getchar() != '\n');
		/* switch player */
		p = p->id == a.id ? &b : &a;
		accG = accL = 0;
		dice_count = r_dice_count = 6U;
		while (1) {
			printf("Player '%s' rolls: ", p->name);
			roll_dice(dice, dice_count);
			print_dice(dice, dice_count);
			o = calculate_occurrences(dice, dice_count);
			accL = calc_score(o);
			r_dice_count = remaining_dice(o, dice_count);
			printf(" ## s=%u ", accL);
			if (accL > 0) {
				printf("S=%u ", accL + accG);
				printf("t=%u ", p->score);
				printf("T=%u ", accL + accG + p->score);
				printf("r=%u", r_dice_count);
			}
			putchar('\n');
			if (accL == 0) {
				break;
			} else {
				dice_count = r_dice_count;
				accG += accL;
				if (accG + p->score > score_limit) {
					p->score += accG;
					break;
				}
			}
			if (!(p->score == 0 && accG < 35)) {
				printf("Continue? [Y/n]: ");
				(void) fflush(stdout);
				c = getchar();
				if (c != '\n')
					while (getchar() != '\n');
				if (c == 'n') {
					p->score += accG;
					break;
				}
			}
		}
	}

	printf("Player '%s' wins with score %u.\n", p->name, p->score);
}
Ejemplo n.º 7
0
/**
 \fn int main();
 \brief programme principal
 */
int main(){
	CU_pSuite pSuite = NULL;
	t_lettre grille[4][4]={{{'z',0,0},{'q',0,0},{'t',0,0},{'c',0,0}},
							{{'u',0,0},{'c',0,0},{'y',0,0},{'b',0,0}},
								{{'r',0,0},{'i',0,0},{'b',0,0},{'o',0,0}},
								{{'t',0,0},{'n',0,0},{'e',0,0},{'a',0,0}}};
	t_valeurmot mot_dico1={"bobine",0};
	t_valeurmot mot_dico2={"truc",0};
	t_coord chemin_mot_pile1[6]={{1,3},{2,3},{2,2},{2,1},{3,1},{3,2}};
	t_coord chemin_mot_pile2[4]={{0,3},{0,2},{0,1},{1,1}};
	int chemin_mot_sommet1=5;
	int chemin_mot_sommet2=3;
	calc_score(&mot_dico1,chemin_mot_pile1,&chemin_mot_sommet1,grille);
	calc_score(&mot_dico1,chemin_mot_pile2,&chemin_mot_sommet2,grille);
	void test_score(void){
		CU_ASSERT_EQUAL(mot_dico1.score, 10);
		CU_ASSERT_EQUAL(mot_dico2.score, 2);
	}
Ejemplo n.º 8
0
static void
fill_topten_entry(struct toptenentry *newtt, int how)
{
    int uid = getuid();

    memset(newtt, 0, sizeof (struct toptenentry));

    /* deepest_lev_reached() is in terms of depth(), and reporting the deepest
       level reached in the dungeon death occurred in doesn't seem right, so we 
       have to report the death level in depth() terms as well (which also
       seems reasonable since that's all the player sees on the screen anyway) */
    newtt->ver_major = VERSION_MAJOR;
    newtt->ver_minor = VERSION_MINOR;
    newtt->patchlevel = PATCHLEVEL;
    newtt->points = u.urexp > -1 ?      /* u.urexp stores score once invent is
                                           invalid */
        u.urexp : calc_score(how, FALSE, money_cnt(invent) + hidden_gold());
    newtt->deathdnum = u.uz.dnum;
    newtt->deathlev = depth(&u.uz);
    newtt->maxlvl = deepest_lev_reached(TRUE);
    newtt->hp = u.uhp;
    newtt->maxhp = u.uhpmax;
    newtt->deaths = u.umortality;
    newtt->uid = uid;
    newtt->moves = moves;
    newtt->how = how;
    strncpy(newtt->plrole, urole.filecode, ROLESZ);
    newtt->plrole[ROLESZ] = '\0';
    strncpy(newtt->plrace, urace.filecode, ROLESZ);
    newtt->plrace[ROLESZ] = '\0';
    strncpy(newtt->plgend, genders[flags.female].filecode, ROLESZ);
    newtt->plgend[ROLESZ] = '\0';
    strncpy(newtt->plalign, aligns[1 - u.ualign.type].filecode, ROLESZ);
    newtt->plalign[ROLESZ] = '\0';
    strncpy(newtt->name, plname, NAMSZ);
    newtt->name[NAMSZ] = '\0';
    newtt->death[0] = '\0';
    switch (killer_format) {
    default:
        impossible("bad killer format?");
    case KILLED_BY_AN:
        strcat(newtt->death, killed_by_prefix[how]);
        strncat(newtt->death, an(killer), DTHSZ - strlen(newtt->death));
        break;
    case KILLED_BY:
        strcat(newtt->death, killed_by_prefix[how]);
        strncat(newtt->death, killer, DTHSZ - strlen(newtt->death));
        break;
    case NO_KILLER_PREFIX:
        strncat(newtt->death, killer, DTHSZ);
        break;
    }
    newtt->birthdate = yyyymmdd(u.ubirthday);
    newtt->deathdate = yyyymmdd((time_t) 0L);
    time(&deathtime_internal);
}
Ejemplo n.º 9
0
int main(void)
{
	baseball bb2016[N];

	FILE *fp; //ファイルポインタの宣言
	char *filename_r = "Pa2016.txt"; //データ読み込み用のファイル
	char *filename_w = "Pa2016result.txt"; //データ書き込み用のファイル
	char s[10];
	int score[N][D_SIZE-1]; //ファイルから読み込んだデータ(数値)を格納

	int iLp = 0;
	int num = 0;

	//データ読み込み用のファイルを開く
	if((fp = fopen(filename_r, "r")) == NULL){
		fprintf(stderr," エラー:ファイル(%s)がオープンできません\n",filename_r);
		return -1;
	}


	//データ読み込み
  while (fscanf(fp,"%s",s) != EOF){
  	if(atoi(s)==0 && strcmp(s,"0")!=0){
    	strcpy(bb2016[num].team_name,s); //チーム名の時は構造体の配列に格納
  	}else{
  		score[num][iLp-1] = atoi(s);
  	}

    iLp++;
    if(iLp == D_SIZE){
    	num++;
    	iLp = 0; //初期値に戻す
    }
  }
	fclose(fp);

	//各チームの勝数、負数、引分数、勝率を計算
	calc_score(score,bb2016);

	//勝率の昇順にソートする
	sort(bb2016);

	//データ書き込み用のファイルを開く
	if ((fp = fopen(filename_w, "w")) == NULL){
		fprintf(stderr," エラー:ファイル(%s)がオープンできません\n",filename_w);
		return -1;
	}

	//結果の書き込み
	for (iLp=0;iLp<N;iLp++){
		fprintf(fp,"%d位:%-10s\t%.3f\n",iLp+1,bb2016[iLp].team_name,bb2016[iLp].wpct);
	}
	fclose(fp);

	return 0;
}
Ejemplo n.º 10
0
void FlipFlap::update_boxes(){							//update on-screen counters
  stringstream ss;								//put min_flips into a string
  ss << min_flips;		
  min_box->put(ss.str());							//display minimun flips needed
  stringstream flbox;								//put current flips into a string
  flbox << current_flips;
  flips_box->put(flbox.str());							//display current flips
  stringstream scbox;								//put score in a string
  scbox << calc_score(current_flips);
  score_box->put(scbox.str());							//display current score
}
Ejemplo n.º 11
0
int simple_ai::decide(tetris& game_ref)
{
    game_ref.fix_tetro_on_map();
    game_ref.clear_lines();

    MOVE_FACTORS factors;
    generate_factors(game_ref, factors);

    int score = calc_score(game_ref, factors);
    update_factors(factors);

    return score;
}
Ejemplo n.º 12
0
static int move(int dir)
{
    switch(dir)
    {
    case LEFT:
        col--;
        break;
    case RIGHT:
        col++;
        break;
    case DOWN:
        row++;
        break;
    case ROTATE:
        rot = (rot+1)%4;
        break;
    }
    int rc = check_move();
    if(rc == 1)
    {
        switch(dir)
        {
        case LEFT:
            col++;
            break;
        case RIGHT:
            col--;
            break;
        case DOWN:
            row--;
            break;
        case ROTATE:
            rot = rot == 0 ? 3 : rot-1;
            break;
        }
        if(dir == DOWN)
        {
            cement_block();
            trigger_event("BlockHit", NULL);
            int lines = check_lines();
            if(lines)
                calc_score(lines);
            new_block();
       }
    }
    else
    {
        trigger_event("MoveSucceeded", (void*)dir);
    }
    return rc;
}
Ejemplo n.º 13
0
void brute_hash1(){
    //uint8_t csn[8] = {0,0,0,0,0xf7,0xff,0x12,0xe0};
    uint8_t k[8]= {0,0,0,0,0,0,0,0};
    uint16_t a,b,c,d;
	//uint8_t testcsn[8] ={0x00,0x0d,0x0f,0xfd,0xf7,0xff,0x12,0xe0} ;
    uint8_t csn[8] = {0x04,0x0f,0x0f,0xf7,0xf7,0xff,0x12,0xe0};
	//uint8_t testkey2[8] = {0};
    hash1(csn, k);
    printf("CSN\t%02x%02x%02x%02x%02x%02x%02x%02x\t%02x %02x %02x %02x %02x %02x %02x %02x\t"
               ,csn[0],csn[1],csn[2],csn[3],csn[4],csn[5],csn[6],csn[7]
                ,k[0],k[1],k[2],k[3],k[4],k[5],k[6],k[7]
                );

	//uint8_t testkey[8] ={0x05 ,0x01 ,0x00 ,0x10 ,0x45 ,0x08 ,0x45,0x56} ;
    calc_score(csn,k);
    printf("Brute forcing hashones\n");
    //exit(1);
    for(a=0;a < 256;a++)
    {
        //if(a > 0)printf("%d/256 done...\n", a);
        for(b=0;b < 256 ; b++)
            for(c=0;c < 256;c++)
               for(d=0;d < 256;d++)
                {
                    csn[0] = a;
                    csn[1] = b;
                    csn[2] = c;
                    csn[3] = d;
                    csn[4] = 0xf7;
                    csn[5] = 0xff;
                    csn[6] = 0x12;
                    csn[7] = 0xe0;
                    hash1(csn, k);
                    calc_score(csn,k);
               }
    }

}
Ejemplo n.º 14
0
/* Keep score of an entire game from start to finish */ 
void playfull_single(player *currentp)/*#{{{*/
{
    frame *currFrame = NULL;       /* current frame in play */
    uint64_t *scoreTotal = NULL;   /* total score for current player */

    register uint64_t i = 0;

    char previousR2 = '\0';
    char previousR1 = '\0';

    assert(currentp != NULL);
    
    /* single player specific opening */
    printf("\nYou are playing single player, get some!\n");

    scoreTotal = &currentp -> scoreTotal;

    /* go through each frame for the player, and play it! */
    currFrame = currentp -> allFrames;
    for(i = 1; i < MAXFRAMES; ++i, ++currFrame) /* all but frame 11 */
    {
        /* get 2 rolls */
        printf("\nEnter in current frame results.");
        play_frame(currFrame);

        /* fill in fv and score */
        *scoreTotal = calc_score(currFrame); 
        
       display_game(&currentp, NULL, 1);
    } /* end for */

    /* current frame is currently on frame 11/11, pointers are fun! */
    --currFrame;
    previousR2 = currFrame -> roll[R2];
    previousR1 = currFrame -> roll[R1];
    ++currFrame;
    if(previousR2 == '/' || previousR1 == 'X')
    {
        yes_bonus_r(currFrame);
        *scoreTotal += calc_bonus_r(currFrame);
    } /* end if */
   
    /* clear the screen before printing final results */
    system("clear");
    printf("\n\n\nYou finished a single player game! alone!\n");

    display_game(&currentp, NULL, 1);

} /* end playfull_single #}}} */
Ejemplo n.º 15
0
bool
AbstractContest::save_solution()
{
  const fixed score = calc_score();
  const bool improved = (score>best_result.score);

  if (improved) {
    best_result.score = score;
    best_result.distance = calc_distance();
    best_result.time = calc_time();
    if (positive(best_result.time))
      best_result.speed = best_result.distance / best_result.time;
    else
      best_result.speed = fixed_zero;
    return true;
  }
  return false;
}
Ejemplo n.º 16
0
void LR::update_online(int samp_class, sparse_feat &samp_feat, float learn_rate, float lambda)
{
	vector<float> score_vec = calc_score(samp_feat); //(W'*X)
	vector<float> softmax_vec = softmax(score_vec);
	for (int i=0;i<class_set_size;i++)                          //对于每一个类
	{

		float error_term=((int)(i==samp_class)-softmax_vec[i]);
		for (int j=0;j<samp_feat.id_vec.size();j++)             //对于每个类中的每个样本,更新参数
		{
			int feat_id=samp_feat.id_vec[j];
			float feat_value=samp_feat.value_vec[j];
			float delt=error_term*feat_value;    //梯度 = x^i * (指示函数 - y)
			//float regul = lambda * omega[feat_id][i];
			omega[feat_id][i]+=learn_rate*delt;    //更新参数,学习率 * 梯度
		}
	}
}
Ejemplo n.º 17
0
int main()
{
    int t,i,a,b,id;
    char name[3];
    scanf("%d",&t);
    while(t--){
        scanf("%d%d",&n,&m);
        memset(player,0,sizeof(player[0])*n);
        num_ZG=num_ZC=num_FZ=num_NJ=0;
        for(i=0;i<n;i++){
            scanf("%s",name);
            switch(name[1]){
            case 'G':player[i].id=1;num_ZG++;break;
            case 'C':player[i].id=2;num_ZC++;break;
            case 'Z':player[i].id=3;num_FZ++;break;
            case 'J':player[i].id=4;num_NJ++;break;
            }
        }
        flag=whether_win();
        while(m--){
            scanf("%d%d",&a,&b);
            if(flag)
                continue;
            player[b].state=1;
            if(!num_FZ&&!num_ZC&&num_NJ==1&&num_ZG==1)
                player[b].killed_by=player[a].id;
            id=player[b].id;
            switch(id){
            case 1:num_ZG--;player[a].kill_ZG++;break;
            case 2:num_ZC--;player[a].kill_ZC++;break;
            case 3:num_FZ--;player[a].kill_FZ++;break;
            case 4:num_NJ--;player[a].kill_NJ++;break;
            }
            flag=whether_win();
        }
        calc_score(flag);
        printf("%d",player[0].score);
        for(i=1;i<n;i++)
            printf(" %d",player[i].score);
        printf("\n");
    }
    return 0;
}
Ejemplo n.º 18
0
void loose2(){
	effect_reset();
	int j;
	for(j=0;j<snakelen*5+50; j++){
		if(j%5==0 && j<snakelen*5){
			effect_create(EFFECT_TYPE_STROBE , snake[j/5], -63-32*(sin(j/5)+1),0,-32*(sin(j/5+3.14159)+1), 2, j, 30); 
			effect_create(EFFECT_TYPE_FADEIN , snake[j/5], -63-32*(sin(j/5)+1),0,-32*(sin(j/5+3.14159)+1), 2, j, 30); 
			effect_create(EFFECT_TYPE_DELAY , snake[j/5], -63-32*(sin(j/5)+1),0,-32*(sin(j/5+3.14159)+1), 2, j+30, snakelen*5+50); 
		}
		snake_draw();
		effect_draw(j);
		blit();
		update();
		//usleep(10000);
	}
	calc_score();
	display_score();
	welcome();
}
Ejemplo n.º 19
0
int main(int argc,char** argv)
{
	int* a;
	int t,n,i;
	while(scanf("%d",&t)!=EOF)
	{
		while(t--)
		{
			scanf("%d",&n);
			a=(int*)malloc(n*sizeof(int));
			for(i=0;i<n;i++)
			{
				scanf("%d",a+i);
			}
			m_sort(a,n);
			printf("%lf\n",calc_score(a,n));
			free(a);
		}
	}
	return 0;
}
Ejemplo n.º 20
0
float LR::classify_testing_file(string testing_file, string output_file, int output_format)
{
	cout << "Classifying testing file..." << endl;
	vector<sparse_feat> test_feat_vec;
	vector<int> test_class_vec;
	vector<int> pred_class_vec;
	read_samp_file(testing_file, test_feat_vec, test_class_vec);
	ofstream fout(output_file.c_str());
	for (size_t i = 0; i < test_class_vec.size(); i++)
	{
		int samp_class = test_class_vec[i];
		sparse_feat samp_feat = test_feat_vec[i];
		vector<float> pred_score = calc_score(samp_feat);
		int pred_class = score_to_class(pred_score);
		pred_class_vec.push_back(pred_class);
		fout << pred_class << "\t"<<samp_class<<"\t";
		if (output_format == 1)
		{
			for (int j = 0; j < class_set_size; j++)
			{
				fout << j << ":" << pred_score[j] << ' ';
			}
		}
		else if (output_format == 2)
		{
			vector<float> pred_prb = score_to_prb(pred_score);
			for (int j = 0; j < class_set_size; j++)
			{
				fout << j << ":" << pred_prb[j] << ' ';
			}
		}

		fout << endl;
	}
	fout.close();
	float acc = calc_acc(test_class_vec, pred_class_vec);
	return acc;
}
Ejemplo n.º 21
0
int main(void){

        int in;

	ctr = 0;
	lastmove = 0;
	
	pos = 0;
	dir = 0;
	nextdir = 0;
	
	tick_delay = 10;
	
	spi_init();

        initscr();                      /* Start curses mode              */
        keypad(stdscr, TRUE);
        nodelay(stdscr, TRUE);
        cbreak();
        noecho();

	nunchuck_init();
	effect_init(); 
      
	welcome();
 
	snakesetup();


	logfile = fopen("snakelog.txt","a+");
	fprintf(logfile, "snake inited\n");

        while(42){
                in = getch();
              	do{ 
			while(nunchuck_read()){
				nunchuck_init();
				//nunchuck_read();
				mvprintw(6,0,"nunchuck reinited\n");
			}
		}while(joyX < 10 || joyX == 255 || joyY < 10 || joyY == 255);
		if (dir != 1 && (in == KEY_LEFT || (joyX < XCENTER - JOYDEADZONE && joyX > 10 ))){
			nextdir = 0;
                }
                else if (dir != 0 && (in == KEY_RIGHT || (joyX > XCENTER + JOYDEADZONE && joyX < 240))){
			nextdir = 1;
                }
                else if (dir != 3 && (in == KEY_UP || joyY > YCENTER + JOYDEADZONE)){
			nextdir = 2;
                }
                else if (dir != 2 && (in == KEY_DOWN || (joyY < YCENTER - JOYDEADZONE && joyY > 10))){
			nextdir = 3;
                }

		if (joyX > 150){

		}


		if(lastmove+tick_delay <= ctr){
			lastmove = ctr;
			dir = nextdir;
			snake_do(dir);
			
			//if(!buttonC && tick_delay > 0) tick_delay--; 
			//if(!buttonZ && tick_delay < 30) tick_delay++; 
                }
		
		
				
		//setpixel((accelX-512)/10+WIDTH/2,(accelY-512)/20+6,127,32,16);

		
		mvprintw(0,2,"pos: %d\n", pos);
		mvprintw(1,0,"joy X,Y: %d, %d\n", joyX, joyY);
		mvprintw(2,0,"Accel X,Y,Z: %d, %d, %d\n", accelX, accelY, accelZ);
		mvprintw(3,0,"Button C,Z: %d, %d\n", buttonC, buttonZ);
		calc_score();
		mvprintw(4,5,"Score: %d     ", score);	
		refresh();  //ncurses
		
		snake_draw();
		effect_draw(ctr);
		buffer[nompos*3+1] = 127;
		
		blit();    
        	update();
		ctr++;
		}


        endwin();                       /* End curses mode                */

        return 0;


}
Ejemplo n.º 22
0
static void
disclose(int how, boolean taken, long umoney)
{
    char c = 0, defquery;
    const char *qbuf;
    boolean ask = should_query_disclose_options(&defquery);

    if (invent) {
        if (taken)
            qbuf = msgprintf("Do you want to see what you had when you %s?",
                             (how == QUIT) ? "quit" : "died");
        else
            /* This phrase is so fundamentally NetHack, I felt a huge sense of
               pride when I got to edit it, even though I was just changing it
               from a stack allocation to a string literal. Then I felt I should
               add a comment to it because it feels important enough to be
               dignified with one. So here it is. --AIS */
            qbuf = "Do you want your possessions identified?";

        if (!done_stopprint) {
            c = ask ? yn_function(qbuf, ynqchars, defquery) : defquery;
            if (c == 'y') {
                struct obj *obj;

                for (obj = invent; obj; obj = obj->nobj) {
                    discover_object(obj->otyp, TRUE, FALSE, TRUE);
                    obj->known = obj->bknown = obj->dknown = obj->rknown = 1;
                }
                display_inventory(NULL, FALSE);
                container_contents(invent, TRUE, TRUE);
            }
            if (c == 'q')
                done_stopprint++;
        }
    }

    if (!done_stopprint) {
        c = ask ? yn_function("Do you want to see your attributes?", ynqchars,
                              defquery) : defquery;
        if (c == 'y')
            enlighten_mon(&youmonst, how > LAST_KILLER ? 1 : 2, 1); /* final */
        if (c == 'q')
            done_stopprint++;
    }

    if (!done_stopprint)
        list_vanquished(defquery, ask);

    if (!done_stopprint)
        list_genocided(defquery, ask);

    if (!done_stopprint) {
        c = ask ? yn_function("Do you want to see your conduct?", ynqchars,
                              defquery) : defquery;
        if (c == 'y')
            show_conduct(how > LAST_KILLER ? 1 : 2);
        if (c == 'q')
            done_stopprint++;
    }

    if (!done_stopprint) {
        c = ask ? yn_function("Do you want to see a breakdown of your score?",
                              ynqchars, defquery) : defquery;
        if (c == 'y')
            calc_score(how, TRUE, umoney);
        if (c == 'q')
            done_stopprint++;
    }
}
Ejemplo n.º 23
0
void clust_align(int x,int y)
	{
		int i,j,k,h,path[100][100],len;
		char tmp;
		float dp[100][100],t1,t2,t3;

		dp[0][0]=0;

		int ln1 = strlen(cluster[x].seq_list[0]);
		int ln2 = strlen(cluster[y].seq_list[0]);

		for(i=1;i<=ln1;i++)
		{
			dp[i][0] = (float)(gap)*i;
			path[i][0] = 1;
		}

		for(i=1;i<=ln2;i++)
		{
			dp[0][i] = (float)(gap)*i;
			path[0][i] = 2;
		}

		for(i=1;i<=ln1;i++)
			{
				for(j=1;j<=ln2;j++)
				{
					t1 = dp[i-1][j-1]+calc_score(x,y,i-1,j-1);
					t2 = dp[i-1][j] + calc_gap(x,i-1);
					t3 = dp[i][j-1] + calc_gap(y,j-1);

					if(t1>=t2)
					{
						if(t1>=t3)
						{
							dp[i][j] = t1;
							path[i][j] = 0;
						}
						else
						{
							dp[i][j] = t3;
							path[i][j] = 2;
						}				
					}
					else
					{
						if(t2>=t3)
						{
							dp[i][j] = t2;
							path[i][j] = 1;
						}
						else
						{
							dp[i][j] = t3;
							path[i][j] = 2;
						}
					}

				}
			}

		i=ln1;
		j=ln2;
		k = 0;
		while(i!=0 || j!=0)
		{
			if(path[i][j]==0)
			{
				for(h=0;h<cluster[x].tot_seq;h++)
				{
					cluster[num_clust].seq_list[h][k]=cluster[x].seq_list[h][i-1];
				}

				for(h=0;h<cluster[y].tot_seq;h++)
				{
					cluster[num_clust].seq_list[h+cluster[x].tot_seq][k]=cluster[y].seq_list[h][j-1];
				}

				i--;
				j--;

			}
			else if(path[i][j]==1)
			{
				for(h=0;h<cluster[x].tot_seq;h++)
				{
					cluster[num_clust].seq_list[h][k]=cluster[x].seq_list[h][i-1];
				}

				for(h=0;h<cluster[y].tot_seq;h++)
				{
					cluster[num_clust].seq_list[h+cluster[x].tot_seq][k]='-';
				}
				i--;
			}
			else
			{
				for(h=0;h<cluster[x].tot_seq;h++)
				{
					cluster[num_clust].seq_list[h][k]='-';
				}

				for(h=0;h<cluster[y].tot_seq;h++)
				{
					cluster[num_clust].seq_list[h+cluster[x].tot_seq][k]=cluster[y].seq_list[h][j-1];
				}

				j--;
			}
			k++;
		}

		cluster[num_clust].tot_seq = cluster[x].tot_seq + cluster[y].tot_seq;

		for(i=0;i<cluster[num_clust].tot_seq;i++)
			{
				cluster[num_clust].seq_list[i][k]='\0';
			}

		
		for(j=0;j<cluster[num_clust].tot_seq;j++)
			{
				for(i=0;i<k/2;i++)
				{
					tmp = cluster[num_clust].seq_list[j][i];
					cluster[num_clust].seq_list[j][i] = cluster[num_clust].seq_list[j][k-i-1];
					cluster[num_clust].seq_list[j][k-i-1] = tmp;

				}
			}

		for(i=0;i<cluster[num_clust].tot_seq;i++)
		{
			len = k;
			for(j=0;j<len;j++)
				if(cluster[num_clust].seq_list[i][j]=='-')
					cluster[num_clust].seq_list[i][j] = 'X';
		}


		num_clust++;
		alive--;

		visit[x] = 1;
		visit[y] = 1;

		update_hammat(x,y);
	}
Ejemplo n.º 24
0
static int diff(sint A,sint B,sint M,sint N,sint tb,sint te)
{
  sint type;
  sint midi,midj,i,j;
  int midh;
  static pwint f, hh, e, s, t;
  
  if(N<=0)  {
    if(M>0) {
      del(M);
    }
    
    return(-(int)tbgap(M));
  }
  
  if(M<=1) {
    if(M<=0) {
      add(N);
      return(-(int)tbgap(N));
    }
    
    midh = -(tb+gh) - tegap(N);
    hh = -(te+gh) - tbgap(N);
    if (hh>midh) midh = hh;
    midj = 0;
    for(j=1;j<=N;j++) {
      hh = calc_score(1,j,A,B)
	- tegap(N-j) - tbgap(j-1);
      if(hh>midh) {
	midh = hh;
	midj = j;
      }
    }
    
    if(midj==0) {
      del(1);
      add(N);
    }
    else {
      if(midj>1)
	add(midj-1);
      displ[print_ptr++] = last_print = 0;
      if(midj<N)
	add(N-midj);
    }
    return midh;
  }
  
/* Divide: Find optimum midpoint (midi,midj) of cost midh */
  
  midi = M / 2;
  HH[0] = 0.0;
  t = -tb;
  for(j=1;j<=N;j++) {
    HH[j] = t = t-gh;
    DD[j] = t-g;
  }
  
  t = -tb;
  for(i=1;i<=midi;i++) {
    s=HH[0];
    HH[0] = hh = t = t-gh;
    f = t-g;
    for(j=1;j<=N;j++) {
      if ((hh=hh-g-gh) > (f=f-gh)) f=hh;
      if ((hh=HH[j]-g-gh) > (e=DD[j]-gh)) e=hh;
      hh = s + calc_score(i,j,A,B);
      if (f>hh) hh = f;
      if (e>hh) hh = e;
      
      s = HH[j];
      HH[j] = hh;
      DD[j] = e;
    }
  }
  
  DD[0]=HH[0];
  
  RR[N]=0;
  t = -te;
  for(j=N-1;j>=0;j--) {
    RR[j] = t = t-gh;
    SS[j] = t-g;
  }
  
  t = -te;
  for(i=M-1;i>=midi;i--) {
    s = RR[N];
    RR[N] = hh = t = t-gh;
    f = t-g;
    
    for(j=N-1;j>=0;j--) {
      
      if ((hh=hh-g-gh) > (f=f-gh)) f=hh;
      if ((hh=RR[j]-g-gh) > (e=SS[j]-gh)) e=hh;
      hh = s + calc_score(i+1,j+1,A,B);
      if (f>hh) hh = f;
      if (e>hh) hh = e;
      
      s = RR[j];
      RR[j] = hh;
      SS[j] = e;
      
    }
  }
  
  SS[N]=RR[N];
  
  midh=HH[0]+RR[0];
  midj=0;
  type=1;
  for(j=0;j<=N;j++) {
    hh = HH[j] + RR[j];
    if(hh>=midh)
      if(hh>midh || (HH[j]!=DD[j] && RR[j]==SS[j])) {
	midh=hh;
	midj=j;
      }
  }
  
  for(j=N;j>=0;j--) {
    hh = DD[j] + SS[j] + g;
    if(hh>midh) {
      midh=hh;
      midj=j;
      type=2;
    }
  }
  
  /* Conquer recursively around midpoint  */
  
  
  if(type==1) {             /* Type 1 gaps  */
    diff(A,B,midi,midj,tb,g);
    diff(A+midi,B+midj,M-midi,N-midj,g,te);
  }
  else {
    diff(A,B,midi-1,midj,tb,0.0);
    del(2);
    diff(A+midi+1,B+midj,M-midi-1,N-midj,0.0,te);
  }
  
  return midh;       /* Return the score of the best alignment */
}
Ejemplo n.º 25
0
// minimax recursive func, using alpha-beta pruning
int alpha_beta_minimax(char board[BOARD_SIZE][BOARD_SIZE], COLOR player, int depth, int alpha, int beta){
	Move* move_list = get_all_moves(board, player);
	Move* curr_move = move_list;
	if (depth == 0 && curr_move == NULL){
		best_move = NULL;
		return -500;
	}
	if (curr_move == NULL && player != curr_player){
		if (!is_check(board, !curr_player)) return -450;
		else return 500;
	}
	if (curr_move == NULL && player == curr_player){
		if (!is_check(board, curr_player)) return 450;
		else return -500;
	}
	if (depth == minimax_depth || curr_move == NULL){
		clear_old_moves(move_list);
		return calc_score(board, curr_player);
	}

	if (depth == 0){
		best_move = curr_move;
		if (curr_move->next == NULL){
			best_move->score = 500;
			return 500;
		}
	}

	char init_board[BOARD_SIZE][BOARD_SIZE];
	duplicate_board(board, init_board);
	// MAX
	if (depth % 2 == 0){
		while (curr_move != NULL){
			exc_move(board, curr_move, player);
			curr_move->score = alpha_beta_minimax(board, (player == 0), depth + 1, alpha, beta);
			if (curr_move->score > alpha){
				alpha = curr_move->score;
				if (depth == 0) best_move = curr_move;
			}
			if (alpha >= beta){
				if (depth != 0) clear_old_moves(move_list);
				else moves_head = move_list;
				duplicate_board(init_board, board);
				return alpha;
			}
			curr_move = curr_move->next;
			duplicate_board(init_board, board);
		}
		if (depth != 0) clear_old_moves(move_list);
		else moves_head = move_list;
		return alpha;
	}
	// MIN
	else{
		while (curr_move != NULL){
			exc_move(board, curr_move, player);
			curr_move->score = alpha_beta_minimax(board, (player == 0), depth + 1, alpha, beta);
			if (curr_move->score < beta){
				beta = curr_move->score;
				if (depth == 0) best_move = curr_move;
			}
			if (alpha >= beta){
				if (depth != 0) clear_old_moves(move_list);
				else moves_head = move_list;
				duplicate_board(init_board, board);
				return beta;
			}
			curr_move = curr_move->next;
			duplicate_board(init_board, board);
		}
		if (depth != 0) clear_old_moves(move_list);
		else moves_head = move_list;
		return beta;
	}
}
Ejemplo n.º 26
0
/***********************************************************************
 * : 
 **********************************************************************/
int diff (int A, int B, int M, int N, int tb, int te, int *print_ptr, int *last_print, int *displ, int seq1, int seq2, int g, int gh)
{
   int i, j, f, e, s, t, hh;
   int midi, midj, midh, type;
   int HH[MAX_ALN_LENGTH];
        int DD[MAX_ALN_LENGTH];
   int RR[MAX_ALN_LENGTH];
   int SS[MAX_ALN_LENGTH];

   if (N <= 0) {if (M > 0) del(M, print_ptr, last_print, displ); return( - (int) tbgap(M)); }

   if (M <= 1) {

      if (M <= 0) {add(N, print_ptr, last_print, displ); return( - (int)tbgap(N));}

      midh = -(tb+gh) - tegap(N);
      hh   = -(te+gh) - tbgap(N);

      if (hh > midh) midh = hh;
      midj = 0;

      for (j = 1; j <= N; j++) {
         hh = calc_score(1,j,A,B,seq1,seq2) - tegap(N-j) - tbgap(j-1);
         if (hh > midh) {midh = hh; midj = j;}
      }

      if (midj == 0) {
         del(1, print_ptr, last_print, displ);
         add(N, print_ptr, last_print, displ);
      } else {
         if (midj > 1) add(midj-1, print_ptr, last_print, displ);
         displ[(*print_ptr)++] = *last_print = 0;
         if (midj < N) add(N-midj, print_ptr, last_print, displ);
      }

      return midh;
   }

   midi  = M / 2;
   HH[0] = 0.0;
   t     = -tb;

   for (j = 1; j <= N; j++) {
      HH[j] = t = t - gh;
      DD[j] = t - g;
   }

   t = -tb;

   for (i = 1; i <= midi; i++) {
      s     = HH[0];
      HH[0] = hh = t = t - gh;
      f     = t - g;
      for (j = 1; j <= N; j++) {
         if ((hh = hh - g - gh)    > (f = f - gh))    f = hh;
         if ((hh = HH[j] - g - gh) > (e = DD[j]- gh)) e = hh;
         hh = s + calc_score(i,j,A,B,seq1,seq2);
         if (f > hh) hh = f;
         if (e > hh) hh = e;

         s = HH[j];
         HH[j] = hh;
         DD[j] = e;
      }
   }

   DD[0] = HH[0];
   RR[N] = 0;
   t     = -te;

   for (j = N-1; j >= 0; j--) {RR[j] = t = t - gh; SS[j] = t - g;}

   t = -te;

   for (i = M - 1; i >= midi; i--) {
      s     = RR[N];
      RR[N] = hh = t = t-gh;
      f     = t - g;
      for (j = N - 1; j >= 0; j--) {
         if ((hh = hh - g - gh)    > (f = f - gh))     f = hh;
         if ((hh = RR[j] - g - gh) > (e = SS[j] - gh)) e = hh;
         hh = s + calc_score(i+1,j+1,A,B,seq1,seq2);
         if (f > hh) hh = f;
         if (e > hh) hh = e;

         s     = RR[j];
         RR[j] = hh;
         SS[j] = e;
      }
   }

   SS[N] = RR[N];

   midh = HH[0] + RR[0];
   midj = 0;
   type = 1;

   for (j = 0; j <= N; j++) {
      hh = HH[j] + RR[j];
      if (hh >= midh)
      if (hh > midh || (HH[j] != DD[j] && RR[j] == SS[j]))
         {midh = hh; midj = j;}
   }

   for (j = N; j >= 0; j--) {
      hh = DD[j] + SS[j] + g;
      if (hh > midh) {midh = hh;midj = j;type = 2;}
   }


   if (type == 1) {
      diff(A, B, midi, midj, tb, g, print_ptr, last_print, displ, seq1, seq2, g, gh);
      diff(A+midi, B+midj, M-midi, N-midj, g, te, print_ptr, last_print, displ, seq1, seq2, g, gh);
   } else {
      diff(A, B, midi-1, midj, tb, 0.0, print_ptr, last_print, displ, seq1, seq2, g, gh);
      del(2, print_ptr, last_print, displ);
      diff(A+midi+1, B+midj, M-midi-1, N-midj, 0.0, te, print_ptr, last_print, displ, seq1, seq2, g, gh);
   }

   return midh;
}
Ejemplo n.º 27
0
/* Move the protein to the position so the membrane is between
z=+/- half_membrane_thichness */
int mem_position(PROT *prot_p, IPECE *ipece)
{
    VECTOR *orig_r;
    ATOM **all_atoms; /* a list of pointers pointing to all atoms in prot */
    int i_res, i_conf, i_atom, na;
    ATOM *atom_p;

    VECTOR vec_orig, vec_i, vec_j, vec_k;
    vec_orig.x = 0.;    vec_orig.y = 0.;    vec_orig.z = 0.;
    vec_i.x=1.;         vec_i.y=0.;         vec_i.z=0.;
    vec_j.x=0.;         vec_j.y=1.;         vec_j.z=0.;
    vec_k.x=0.;         vec_k.y=0.;         vec_k.z=1.;
    
    idum = time(NULL);
    
    /* set up. add a residue to contain anchor vectors,
    initialize all_atoms array, backup all atom coordinates to orig_r */
    ins_res(prot_p, prot_p->n_res);
    ins_conf(&prot_p->res[prot_p->n_res-1],0,4);
    for (i_atom=0;i_atom<4;i_atom++) {
        prot_p->res[prot_p->n_res-1].conf[0].atom[i_atom].on = 1;
    }
    prot_p->res[prot_p->n_res-1].conf[0].atom[0].xyz = vec_orig;
    prot_p->res[prot_p->n_res-1].conf[0].atom[1].xyz = vector_rescale(vec_i,100.);
    prot_p->res[prot_p->n_res-1].conf[0].atom[2].xyz = vector_rescale(vec_j,100.);
    prot_p->res[prot_p->n_res-1].conf[0].atom[3].xyz = vector_rescale(vec_k,100.);
    
    na = 0;
    all_atoms = NULL;
    orig_r = NULL;
    for (i_res=0; i_res<prot_p->n_res; i_res++) {
        for (i_conf=0; i_conf<prot_p->res[i_res].n_conf; i_conf++) {
            for (i_atom=0; i_atom<prot_p->res[i_res].conf[i_conf].n_atom; i_atom++) {
                atom_p = &prot_p->res[i_res].conf[i_conf].atom[i_atom];
                if (!atom_p->on) continue;
                na++;
                orig_r = (VECTOR *) realloc(orig_r, na*sizeof(VECTOR));
                orig_r[na-1] = atom_p->xyz;
                all_atoms = (ATOM **) realloc(all_atoms, na*sizeof(ATOM *));
                all_atoms[na-1] = atom_p;
                atom_p->i_atom_prot = na-1;
            }
        }
    }
    
    /* move the center of the protein to the origin */
    VECTOR center;
    center = vec_orig;
    int ia;
    for (ia=0; ia<na; ia++) {
        center = vector_vplusv(center, all_atoms[ia]->xyz);
    }
    center = vector_rescale(center, 1./na);
    for (ia=0; ia<na; ia++) {
        all_atoms[ia]->xyz = vector_vminusv(all_atoms[ia]->xyz, center);
    }
    
    float score, min_score;
    int best_pos;
    /* get the initial score for the protein */
    probe(*prot_p, ipece);
    /* collect atoms used for calculating scores */
    get_scored_atoms(*prot_p, ipece);
    min_score = calc_score(ipece);
    best_pos = 1;
    
    /* rotate around x axis by 90� to calculate score again */
    rotate_atoms(vec_orig, vec_i, env.PI/2., ipece->n_scored_atom, ipece->scored_atoms);
    score = calc_score(ipece);
    if (score < min_score) {
        min_score = score;
        best_pos = 2;
    }
    rotate_atoms(vec_orig, vec_i, -env.PI/2., ipece->n_scored_atom, ipece->scored_atoms);
    
    /* rotate around y axis by 90� to calculate score again */
    rotate_atoms(vec_orig, vec_j, env.PI/2., ipece->n_scored_atom, ipece->scored_atoms);
    score = calc_score(ipece);
    if (score < min_score) {
        min_score = score;
        best_pos = 3;
    }
    rotate_atoms(vec_orig, vec_j, -env.PI/2., ipece->n_scored_atom, ipece->scored_atoms);
    
    /* choose the lowest scored position to start with */
    if (best_pos == 2) {
        rotate_atoms(vec_orig, vec_i, env.PI/2., na, all_atoms);
        rotate_atoms(vec_orig, vec_i, env.PI/2., ipece->n_scored_atom, ipece->scored_atoms);
    }
    if (best_pos == 3) {
        rotate_atoms(vec_orig, vec_j, env.PI/2., na, all_atoms);
        rotate_atoms(vec_orig, vec_j, env.PI/2., ipece->n_scored_atom, ipece->scored_atoms);
    }
    
    /* randomly translate the protein in z direction or rotation around an axis
    on x-y plane to find the lowest scored position.
    sampling the positions in a way similar as monte carlo */
    VECTOR vec_trans = vec_orig;
    VECTOR vec_axis = vec_orig;
    
    score = calc_score(ipece);
    min_score = score;
    for (ia=0;ia<4;ia++) {
        ipece->membrane_position[ia] = prot_p->res[prot_p->n_res-1].conf[0].atom[ia].xyz;
    }
    
    int iter;
    for (iter=0;iter<ipece->n_iteration;iter++) {
        float new_score, delta_score;
        /* translation */
        if (ran2(&idum) < 0.5) {
            vec_trans.z =  2.*(ran2(&idum) - 0.5)*ipece->translation_max;
            
            translate_atoms(vec_trans, ipece->n_scored_atom, ipece->scored_atoms);
            new_score = calc_score(ipece);
            delta_score = new_score - score;
            if (ran2(&idum) < exp(-ipece->beta * delta_score)) {
                translate_atoms(vec_trans, na, all_atoms);
                score = new_score;
            }
            else {
                vec_trans.z = -vec_trans.z;
                translate_atoms(vec_trans, ipece->n_scored_atom, ipece->scored_atoms);
            }
        }
        /* rotation */
        else {
            float phi, theta;
            phi = ran2(&idum)*2.*env.PI;
            theta = ran2(&idum)*ipece->rotation_max;    /* rotation_max has been
                                                        converted to radian in
                                                        parameter reading process */
            vec_axis.x = cos(phi);
            vec_axis.y = sin(phi);
            rotate_atoms(vec_orig, vec_axis, theta, ipece->n_scored_atom, ipece->scored_atoms);
            
            new_score = calc_score(ipece);
            delta_score = new_score - score;
            if (ran2(&idum) < exp(-ipece->beta * delta_score)) {
                rotate_atoms(vec_orig, vec_axis, theta, na, all_atoms);
                score = new_score;
            }
            else {
                vec_trans.z = -vec_trans.z;
                rotate_atoms(vec_orig, vec_axis, -theta, ipece->n_scored_atom, ipece->scored_atoms);
            }

        }
        
        if (score < min_score) {
            min_score = score;
            for (ia=0;ia<4;ia++) {
                ipece->membrane_position[ia] = prot_p->res[prot_p->n_res-1].conf[0].atom[ia].xyz;
            }
        }
        
        /*
        printf("\n");
        for (i=0;i<4;i++) {
            printf("       %10.6f %10.6f %10.6f\n",
            prot_p->res[prot_p->n_res-1].conf[0].atom[i].xyz.x,
            prot_p->res[prot_p->n_res-1].conf[0].atom[i].xyz.y,
            prot_p->res[prot_p->n_res-1].conf[0].atom[i].xyz.z);
        }
        */
    }
    
    ipece->mem_position_defined = 1;
    
    /* move the protein back to orginal position */
    for (ia=0; ia<na; ia++) {
        all_atoms[ia]->xyz = orig_r[ia];
    }

    /* free memory */
    free_scored_atoms(ipece);
    free_probe(ipece);
    free(all_atoms);
    free(orig_r);
    na = 0;
    
    /* delete the extra anchor residue */
    del_res(prot_p, prot_p->n_res-1);
    return 0;
}
Ejemplo n.º 28
0
void Note_Long::update(UI::Tracker const &tracker, KeyStatus const &stat)
{
    JScore b_temp = JScore();
    JScore e_temp = JScore();

    b_temp = tracker.cgetJudge().judge(mBTick - tracker.getCurrentTick());
    e_temp = tracker.cgetJudge().judge(mETick - tracker.getCurrentTick());


    // Remove from key-lock context if score is already set.
    // But stay alive if not past deletion point.
    if (mScore.rank != EJRank::NONE) {
        mDead = (e_temp.rank == EJRank::MISS) ? true : mDead;
        return;
    }

    //// WAIT -> Starting point not hit yet. Respond to key status.
    //// LIVE -> Starting point hit, but end point hasn't. Respond to key status.
    //// DONE -> Note::score is set, but not dead as we still need to render graphics.
    //// DEAD -> Note::dead  is set.
    //// TODO Make this prettier and less redundant.
    switch(stat)
    {
        case KeyStatus::AUTO: // [DONE] Autoplay note.
            if (mBScore.rank == EJRank::NONE) {
                am->play(mBSID, ENKey_toInteger(getKey()), mVol, mPan);
                mBScore = JScore( EJRank::AUTO, 0, b_temp.delta );
            }

            if (mEScore.rank == EJRank::NONE) {
                mEScore = JScore( EJRank::AUTO, 0, e_temp.delta );
            }

            if (e_temp.delta <= 0) {
                mScore  = JScore( EJRank::AUTO, 0, 0 );
                mDead = true;
            }

            return;

        case KeyStatus::LOCKED: // Holding Key
            if (mEScore.rank == EJRank::NONE) {         // Unscored end
                if (mBScore.rank != EJRank::NONE
                &&  mBScore.rank != EJRank::MISS
                &&  mBScore.rank != EJRank::AUTO) {     // Scored starting point
                    assert(mScore.rank == NONE && "Note logic leak.");
                    if (e_temp.rank == MISS) {          // [DONE] Too late to release
                        mEScore = e_temp;
                        calc_score();
                        mDead = true;
                        return;
                    } else {                            // [LIVE] Still waiting for end point
                        return;
                    }
                } else if (mBScore.rank == EJRank::MISS
                        || mBScore.rank == EJRank::AUTO) {      // Missed starting point
                    mEScore = mBScore;                  // This should not be needed, but someone kept forgetting to set mEScore somewhere.
                    calc_score();
                    return;
                } else {                                        // Unscored starting point
                    if (b_temp.rank == EJRank::MISS) {  // [DONE] Missed starting point.
                        mBScore = b_temp;
                        mEScore = b_temp;
                        calc_score();
                        return;
                    } else {                            // [WAIT] Still have the time to respond.
                        return;
                    }
                }
                // Key lock belongs to another note... Same effect as being OFF.
            } else { return; }                                  // [DONE] Scored end
            break;

        case KeyStatus::OFF : // Have not hit anything OR released key.
            if (mBScore.rank == EJRank::NONE) {     // Unscored starting point; not active yet.
                if (b_temp.rank == EJRank::MISS) {  // [DONE] Missed starting point.
                    mBScore = b_temp;
                    mEScore = b_temp;
                    calc_score();
                    return;
                } else {                            // [WAIT] Still have the time to respond.
                    return;
                }
            } else if (mBScore.rank == EJRank::MISS
                    || mBScore.rank == EJRank::AUTO) {      // Starting point was scored MISS or AUTO
                assert(mBScore.rank == mEScore.rank);       // Starting point and ending points must be equal.
                if (e_temp.rank == EJRank::MISS) {  // [DEAD] Past target time
                    mDead = true;
                    return;
                } else {                            // [DONE] Not past target time
                    return;
                }
            } else {                                // Starting point was scored.
                if (mEScore.rank == EJRank::NONE) {         // Ending point hasn't, so the player was holding this.
                    if (e_temp.rank == EJRank::NONE) {              // [DONE] Release too early
                        mEScore = JScore( EJRank::MISS, 0, e_temp.delta );
                        calc_score();
                        return;
                    } else {                                        // [DEAD] Release at the right time
                        mEScore = e_temp;
                        calc_score();
                        return;
                    }
                } else {                                    // Ending point was scored.
                    if (e_temp.rank == EJRank::MISS) {              // [DEAD] Past target time
                        mDead = true;
                        return;
                    } else {                                        // [DONE] Not past target time
                        return;
                    }
                }
            }

        case KeyStatus::ON: // Just hit the key or rehit after miss.
            if (mBScore.rank == EJRank::NONE) {             // Starting point was not hit
                am->play(mBSID, ENKey_isPlayer1(getKey()) ? 1 : 2, mVol, mPan);  // Play sound.
                if (b_temp.rank == EJRank::NONE) {                  // [WAIT] Hit too early
                    return;
                } else if (b_temp.rank == EJRank::MISS
                        || b_temp.rank == EJRank::AUTO) {           // [DONE] Rare case of MISS right when the key is hit.
                    mBScore = b_temp;
                    mEScore = b_temp;
                    calc_score();
                    return;
                } else {                                            // [LIVE] Staring point scores!
                    mBScore = b_temp;
                    return;                                     // DO NOT CLEAR FROM ACTIVE QUEUE
                }
            } else if (mEScore.rank == EJRank::NONE) {      // Starting point was hit, ending point hasn't
                if (e_temp.rank == EJRank::MISS) {                  // [DEAD] Past target time
                    mEScore = e_temp;
                    calc_score();
                    mDead = true;
                    return;
                } else {                                            // [DONE] Not past target time
                    am->play(mBSID, ENKey_isPlayer1(getKey()) ? 1 : 2, mVol, mPan);             // Play sound.
                    return;
                }
            } else {
                return;
            }

        default:
            return;
    }
}
Ejemplo n.º 29
0
int main (void)
{
	int game = 0, money = 1000;
	system("Color 24");//Color: Background: Green, Text: Red
	welcome_screen();
	do{//while player1 has money
	/* initialize suit array */
	const char *suit[4] = {"Hearts", "Diamonds", "Clubs", "Spades"};
	const char *suits[4] = {"\3", "\4", "\5", "\6"};
	/* initialize face array */
	const char *face[13] = {"Ace", "Deuce", "Three", "Four", "Five", "Six", "Seven", "Eight",
		"Nine", "Ten", "Jack", "Queen", "King"};
	char faces[13] = {"A234567890JQK"};
	char raise = '\0' , ten = ' ';
	Card hand1[5];
	Card hand2[5];
	/* initalize deck array */
	int deck[4][13] = {0};
	int is_pair = 0, is_two_pair = 0, is_three = 0, is_four = 0, is_full = 0, is_flush = 0, is_straight = 0, score1 = 0, score2 = 0,
		x = 0, y = 0, i = 0, j = 0, count = 10, count1 = 0, count2 = 0, bet = 0, bet2 = 0;
	srand ((unsigned) time (NULL)); /* see random-number generator */
	
	hand1[0].is_active = 1; hand1[1].is_active = 1; hand1[2].is_active = 1; hand1[3].is_active = 1; hand1[4].is_active = 1;
	hand2[0].is_active = 1; hand2[1].is_active = 1; hand2[2].is_active = 1; hand2[3].is_active = 1; hand2[4].is_active = 1;

//0 = Black 8 = Gray
//1 = Blue 9 = Light Blue
//2 = Green a = Light Green
//3 = Aqua b = Light Aqua
//4 = Red c = Light Red
//5 = Purple d = Light Purple
//6 = Yellow e = Light Yellow
//7 = White f = Bright White
	
	do{//Places blind bet	
	printf("Money: $%d\n", money);
	printf("Place your blind: \n");
	scanf("%d", &bet);
	if(bet > money)
	{
		printf("You don't have that much money!\n");
		system("Pause");
		system("cls");
	}
	}while(bet > money);
	shuffle (deck);
	deal(deck, face, faces, suit, suits, hand1, hand2, count, count1, count2);
	//Initial Deal
	printf("\nMoney: $%d", money - bet);
	bet = raise_bet(money, bet);//First round of betting - Raise before 'draw'
	count = select_cards(hand1, count);//how many cards to redeal
	count1 = count - 10;
	//deal(deck, face, suit, hand1, hand2, count);
	//Simulates Dealer, decides which cards the dealer keeps
	sort_hand(hand2);	
	is_pair = pair(hand2, face, 0);
	is_two_pair = two_pair(hand2, face, 0);
	is_three = three_of_a_kind(hand2, face, 0);
	is_four = four_of_a_kind(hand2, face, 0);
	is_full = full_house(hand2, face, 0);
	is_flush = flush(hand2, face, 0);
	is_straight = straight(hand2, face, 0);
	for(i = 0; i < 5; i++)//Counts how many cards to redeal to dealer
	{
		if(hand2[i].is_active == 1)
		{
			count++;
			count2++;
		}
	}
	//printf("\n%d %d %d %d %d\n", hand1[0].is_active, hand1[1].is_active, hand1[2].is_active, hand1[3].is_active, hand1[4].is_active);
	//printf("\n%d %d %d %d %d\n", hand2[0].is_active, hand2[1].is_active, hand2[2].is_active, hand2[3].is_active, hand2[4].is_active);
	system("Pause");
	system("cls");	
	printf("Money: $%d\n", money - bet);
	printf("Pot: $%d", 2*bet);
	deal(deck, face, faces, suit, suits, hand1, hand2, count, count1, count2);
	//Draw and Redeal
	sort_hand(hand1);
	sort_hand(hand2);

	printf("\nHand#1\n");
	for(y = 0; y < 5; y++)//Prints hand1
	{
		if(hand1[y].face == 9)//Prints '10' instead of just '0'
		{
			ten = '1';
		}
		if(hand1[y].face != 9)
		{
			ten = ' ';
		}
		printf("Card#%d %5s of %-8s %c%c%s\n", y + 1, face[hand1[y].face], suit[hand1[y].suit], ten, faces[hand1[y].face], suits[hand1[y].suit]);
	}
	//money = money - bet;
	bet = raise_bet(money, bet);//Second round of betting - before 'showdown'
	money = money - bet;
	printf("Money: $%d\n", money);
	/*SHOWDOWN!!!*/
	printf("Pot: $%d\n", 2*bet);
	system("Pause");
	system("cls");
	printf("\nHand#1\n");
	for(y = 0; y < 5; y++)
	{
		if(hand1[y].face == 9)
		{
			ten = '1';
		}
		if(hand1[y].face != 9)
		{
			ten = ' ';
		}
		printf("Card#%d %5s of %-8s %c%c%s\n", y + 1, face[hand1[y].face], suit[hand1[y].suit], ten, faces[hand1[y].face], suits[hand1[y].suit]);
	}
	printf("\nHand#2\n");
	for(j = 0; j < 5; j++)
	{
		if(hand2[j].face == 9)
		{
			ten = '1';
		}
		if(hand2[j].face != 9)
		{
			ten = ' ';
		}
		printf("Card#%d %5s of %-8s %c%c%s\n", j + 1, face[hand2[j].face], suit[hand2[j].suit], ten, faces[hand2[j].face], suits[hand2[j].suit]);
	}
	hand1[0].high_card = hand1[4].face;//Starts by assuming 'high card' is hand[4]
	hand2[0].high_card = hand2[4].face;//'high card' is changed if there is a pair, two pair, etc. 

	printf("\nPlayer #1\t"); //Evaluates Player1's hand
	is_pair = pair(hand1, face, 1);
	is_two_pair = two_pair(hand1, face, 1);
	is_three = three_of_a_kind(hand1, face, 1);
	is_four = four_of_a_kind(hand1, face, 1);
	is_full = full_house(hand1, face, 1);
	is_flush = flush(hand1, face, 1);
	is_straight = straight(hand1, face, 1);
	//printf("\nHand #1:\nPair: %d\t\tTwo Pair: %d\tThree: %d\tFour: %d\t\tFlush: %d\tStraight: %d\n", is_pair, is_two_pair, is_three, is_four, is_flush, is_straight);
	score1 = calc_score(is_pair, is_two_pair, is_three, is_four, is_flush, is_straight, face, hand1);
	
	printf("\nPlayer#2\t");//Evaluates Dealer's hand
	is_pair = pair(hand2, face, 1);
	is_two_pair = two_pair(hand2, face, 1);
	is_three = three_of_a_kind(hand2, face, 1);
	is_four = four_of_a_kind(hand2, face, 1);
	is_full = full_house(hand2, face, 1);
	is_flush = flush(hand2, face, 1);
	is_straight = straight(hand2, face, 1);
	//printf("\nHand #2:\nPair: %d\t\tTwo Pair: %d\tThree: %d\tFour: %d\t\tFlush: %d\tStraight: %d\n", is_pair, is_two_pair, is_three, is_four, is_flush, is_straight);
	score2 = calc_score(is_pair, is_two_pair, is_three, is_four, is_flush, is_straight, face, hand2);

	if(score1 == score2)//If both hands have pair, two pair, etc.
	{
		score1 = hand1[0].high_card;//Note: If a hand has a pair, the highcard is the face value of the pair
		score2 = hand2[0].high_card;
	}
	x = 4;
	do{
	if(score1 == score2)//If both hands have the same high card
	{
		score1 = hand1[x].face;
		score2 = hand2[x].face;
		if(score1 != score2)
		{
			printf("\nPlayer #1 New High Card: %5s\n", face[hand1[x].face]);
			printf("Player #2 New High Card: %5s\n", face[hand2[x].face]);
		}
	}
	x--;
	}while((x >= 0)&&(score1 == score2));
	//printf("\n\nPlayer1 Score: %d\tPlayer2 Score: %d", score1, score2);
	if(score1 > score2)
	{
		printf("\n\nPlayer1 Wins: $%d\n", 2*bet);
		money = money + 2*bet;
	}
	if(score1 < score2)
	{
		printf("\nPlayer2 Wins: $%d\n", 2*bet);
		//money = money - 2*bet;
	}
	//printf("Money: $%d\n", money);
	system("Pause");
	system("cls");
	}while(money > 0);
	if(money <= 0)
	{
		printf("Game Over. . .\n");
	}
	return 0;
}