Exemple #1
0
static bool check_draw(Pos *pos, Move m)
{
  do_move(pos, m, gives_check(pos, pos->st, m));
  bool draw = is_draw(pos); // 64
  undo_move(pos, m);

  return draw;
}
Exemple #2
0
Move pb_probe(Pos *pos)
{
  Move m1 = 0;

  if (!enabled) return m1;
  if (!check_do_search(pos)) return m1;

  if (book_depth_count >= max_book_depth)
    return m1;

  Key key = polyglot_key(pos);

  int n = find_first_key(key);

  if (n < 1) {
    search_counter++;
    if (search_counter > 4) {
      // Stop searching after 4 times not in the book till position changes
      // according to check_do_search()
      do_search = false;
      search_counter = 0;
      book_depth_count = 0;
    }

    return m1;
  }

  book_depth_count++;

  ssize_t idx1 = use_best_book_move ? index_best : index_rand;

  m1 = pg_move_to_sf_move(pos, from_be_u16(polyhash[idx1].move));

  if (!is_draw(pos)) return m1; // 64
  if (n == 1) return m1;

  // Special case draw position and 2 moves available

  if (!check_draw(pos, m1))
    return m1;

  ssize_t idx2 = index_first;
  if (idx1 == idx2) idx2++;

  Move m2 = pg_move_to_sf_move(pos, from_be_u16(polyhash[idx2].move));

  if (!check_draw(pos, m2))
    return m2;

  return 0;
}
Exemple #3
0
void loop(char *input, render_callback render_board){
	
	/* case where it's the computer's turn to move: */
	if (!is_edit_mode && (comp_color == white_to_move || automode) 
		&& !force_mode && !must_sit && !result) {
		
		/* whatever happens, never allow pondering in normal search */
		is_pondering = FALSE_C;
		
		cpu_start = clock ();
		comp_move = think ();
		cpu_end = clock();
		
		ply = 0;
		
		/* must_sit can be changed by search */
		if (!must_sit || must_go != 0)
		{
			/* check for a game end: */
			if ((
				 ((Variant == Losers || Variant == Suicide)
				  && 
				  ((result != white_is_mated) && (result != black_is_mated)))
				 || 
				 ((Variant == Normal || Variant == Crazyhouse || Variant == Bughouse)
				  && ((comp_color == 1 && result != white_is_mated) 
					  ||
					  (comp_color == 0 && result != black_is_mated)
					  ))) 
				&& result != stalemate 
				&& result != draw_by_fifty 
				&& result != draw_by_rep) 
			{
				
				comp_to_coord (comp_move, output);
				
				hash_history[move_number] = hash;
				
				game_history[move_number] = comp_move;
				make (&comp_move, 0);
				
				/* saves state info */
				game_history_x[move_number++] = path_x[0];
				
				userealholdings = 0;
				must_go--;
				
				/* check to see if we draw by rep/fifty after our move: */
				if (is_draw ()) {
					result = draw_by_rep;
				}
				else if (fifty > 100) {
					result = draw_by_fifty;
				}
				
				root_to_move ^= 1;
				
				reset_piece_square ();
				
				if (book_ply < 40) {
					if (!book_ply) {
						strcpy(opening_history, output);
					}
					else {
						strcat(opening_history, output);
					}
				}
				
				book_ply++;
				
				printf ("\nNodes: %d (%0.2f%% qnodes)\n", nodes,
						(float) ((float) qnodes / (float) nodes * 100.0));
				
				elapsed = (cpu_end-cpu_start)/(double) CLOCKS_PER_SEC;
				nps = (float) nodes/(float) elapsed;
				
				if (!elapsed)
					printf ("NPS: N/A\n");
				else
					printf ("NPS: %d\n", (int32_t) nps);
				
				printf("ECacheProbes : %d   ECacheHits : %d   HitRate : %f%%\n", 
					   ECacheProbes, ECacheHits, 
					   ((float)ECacheHits/((float)ECacheProbes+1)) * 100);
				
				printf("TTStores : %d TTProbes : %d   TTHits : %d   HitRate : %f%%\n", 
					   TTStores, TTProbes, TTHits, 
					   ((float)TTHits/((float)TTProbes+1)) * 100);
				
				printf("NTries : %d  NCuts : %d  CutRate : %f%%  TExt: %d\n", 
					   NTries, NCuts, (((float)NCuts*100)/((float)NTries+1)), TExt);
				
				printf("Check extensions: %d  Razor drops : %d  Razor Material : %d\n", ext_check, razor_drop, razor_material);
				
				printf("EGTB Hits: %d  EGTB Probes: %d  Efficiency: %3.1f%%\n", EGTBHits, EGTBProbes,
					   (((float)EGTBHits*100)/(float)(EGTBProbes+1)));
				
				printf("Move ordering : %f%%\n", (((float)FHF*100)/(float)(FH+1)));
				
				printf("Material score: %d   Eval : %d  White hand: %d  Black hand : %d\n", 
					   Material, (int)eval(), white_hand_eval, black_hand_eval);
				
				printf("Hash : %X  HoldHash : %X\n", (unsigned)hash, (unsigned)hold_hash);
				
				/* check to see if we mate our opponent with our current move: */
				if (!result) {
					if (xb_mode) {
						
						/* safety in place here */
						if (comp_move.from != dummy.from || comp_move.target != dummy.target)
							printf ("move %s\n", output);
						
						if (Variant == Bughouse)
						{
							CheckBadFlow(FALSE_C);
						}	
					}
					else {
						if (comp_move.from != dummy.from || comp_move.target != dummy.target)
							printf ("\n%s\n", output);
					}
				}
				else {
					if (xb_mode) {
						if (comp_move.from != dummy.from || comp_move.target != dummy.target)
							printf ("move %s\n", output);
					}
					else {
						if (comp_move.from != dummy.from || comp_move.target != dummy.target)
							printf ("\n%s\n", output);
					}
					if (result == white_is_mated) {
						printf ("0-1 {Black Mates}\n");
					}
					else if (result == black_is_mated) {
						printf ("1-0 {White Mates}\n");
					}
					else if (result == draw_by_fifty) {
						printf ("1/2-1/2 {Fifty move rule}\n");
					}
					else if (result == draw_by_rep) {
						printf ("1/2-1/2 {3 fold repetition}\n");
					}
					else {
						printf ("1/2-1/2 {Draw}\n");
					}
					automode = 0;
				}
			}
			/* we have been mated or stalemated: */
			else {
				if (result == white_is_mated) {
					printf ("0-1 {Black Mates}\n");
				}
				else if (result == black_is_mated) {
					printf ("1-0 {White Mates}\n");
				}
				else if (result == draw_by_fifty) {
					printf ("1/2-1/2 {Fifty move rule}\n");
				}
				else if (result == draw_by_rep) {
					printf ("1/2-1/2 {3 fold repetition}\n");
				}
				else {
					printf ("1/2-1/2 {Draw}\n");
				}
				automode = 0;
			}
		}
	}
	
	/* get our input: */
	if (!xb_mode) {
		if (show_board) {
			printf ("\n");
			display_board (stdout, 1-comp_color);
			render_board(1-comp_color);
		}
		if (!automode)
		{
			printf ("Sjeng: ");
			//readStr(input, STR_BUFF);
			//			rinput (input, STR_BUFF, stdin);
		}
	}
	else {
		/* start pondering */
		
		if ((must_sit || (allow_pondering && !is_edit_mode && !force_mode &&
						  move_number != 0) || is_analyzing) && !result && !automode)
		{
			is_pondering = TRUE_C;
			think();
			is_pondering = FALSE_C;
			
			ply = 0;
		}
		if (!automode)
		{
			//rinput (input, STR_BUFF, stdin);
		}
	}
	
	/* check to see if we have a move.  If it's legal, play it. */
	if (!is_edit_mode && is_move (&input[0])) {
		if (verify_coord (input, &human_move)) {
			
			if (confirm_moves) printf ("Legal move: %s\n", input);
			
			game_history[move_number] = human_move;
			hash_history[move_number] = hash;
			
			make (&human_move, 0);
			game_history_x[move_number++] = path_x[0];
			
			reset_piece_square ();
			
			root_to_move ^= 1;
			
			if (book_ply < 40) {
				if (!book_ply) {
					strcpy(opening_history, input);
				}
				else {
					strcat(opening_history, input);
				}
			}
			
			book_ply++;
			
			if (show_board) {
				printf ("\n");
				display_board (stdout, 1-comp_color);
				render_board(1-comp_color);
			}
		}
		else {
			printf ("Illegal move: %s\n", input);
		}
	}
	else {
		
		/* make everything lower case for convenience: */
		/* GCP: except for setboard, which is case sensitive */
		if (!strstr(input, "setboard")){
			for (p = input; *p; p++) {
				*p = tolower (*p);
			}
		}
		
		/* command parsing: */
		if (!strcmp (input, "quit") || (!input[0] && feof(stdin))) {
			safe_fclose(lrn_standard);
			safe_fclose(lrn_zh);
			safe_fclose(lrn_suicide);
			safe_fclose(lrn_losers);
			free_hash();
			free_ecache();
			exit (EXIT_SUCCESS);
		}
		else if (!strcmp (input, "exit"))
		{
			if (is_analyzing)
			{
				is_analyzing = FALSE_C;
				is_pondering = FALSE_C;
				time_for_move = 0;
			}
			else
			{
				safe_fclose(lrn_standard);
				safe_fclose(lrn_zh);
				safe_fclose(lrn_suicide);
				safe_fclose(lrn_losers);
				free_hash();
				free_ecache();
				exit (EXIT_SUCCESS);
			}
		}
		else if (!strcmp (input, "diagram") || !strcmp (input, "d")) {
			toggle_bool_c (&show_board);
		}
		else if (!strncmp (input, "perft", 5)) {
			sscanf (input+6, "%d", &depth);
			raw_nodes = 0;
			xstart_time = rtime();
			perft (depth);
			printf ("Raw nodes for depth %d: %d\n", depth, raw_nodes);
			printf("Time : %.2f\n", (float)rdifftime(rtime(), xstart_time)/100.);
		}
		else if (!strcmp (input, "confirm_moves")) {
			confirm_moves = TRUE_C;
			printf("Will now confirm moves.\n");
		}
		else if (!strcmp (input, "new")) {
			
			if (xb_mode)
			{
				printf("tellics set 1 Sjeng " VERSION " (2001-9-28/%s)\n", setcode);
			}
			
			if (!is_analyzing)
			{	
				memcpy(material, std_material, sizeof(std_material));
				Variant = Normal;
				
				// memcpy(material, zh_material, sizeof(zh_material));
				//Variant = Crazyhouse;
				
				init_game ();
				initialize_hash();
				
				if (!braindeadinterface)
				{
					clear_tt();
					init_book();
					reset_ecache();
				}
				
				force_mode = FALSE_C;
				must_sit = FALSE_C;
				go_fast = FALSE_C;
				piecedead = FALSE_C;
				partnerdead = FALSE_C;
				kibitzed = FALSE_C;
				fixed_time = FALSE_C;
				
				root_to_move = WHITE;
				
				comp_color = 0;
				move_number = 0;
				hash_history[move_number] = 0;
				bookidx = 0;
				my_rating = opp_rating = 2000;
				must_go = 0;
				tradefreely = 1;
				automode = 0;
				
				CheckBadFlow(TRUE_C);
				ResetHandValue();
			}
			else
			{
				init_game ();
				move_number = 0;
			}
			
		}
		else if (!strcmp (input, "xboard")) {
			xb_mode = TRUE_C;
			toggle_bool_c (&show_board);
			signal (SIGINT, SIG_IGN);
			printf ("\n");
			
			/* Reset f5 in case we left with partner */
			printf("tellics set f5 1=1\n");
			
			BegForPartner();
		}
		else if (!strcmp (input, "nodes")) {
			printf ("Number of nodes: %d (%0.2f%% qnodes)\n", nodes,
					(float) ((float) qnodes / (float) nodes * 100.0));
		}
		else if (!strcmp (input, "nps")) {
			elapsed = (cpu_end-cpu_start)/(double) CLOCKS_PER_SEC;
			nps = (float) nodes/(float) elapsed;
			if (!elapsed)
				printf ("NPS: N/A\n");
			else
				printf ("NPS: %d\n", (int32_t) nps);
		}
		else if (!strcmp (input, "post")) {
			toggle_bool_c (&post);
			if (xb_mode)
				post = TRUE_C;
		}
		else if (!strcmp (input, "nopost")) {
			post = FALSE_C;
		}
		else if (!strcmp (input, "random")) {
			return;
		}
		else if (!strcmp (input, "hard")) {
			
			allow_pondering = TRUE_C;
			
			return;
		}
		else if (!strcmp (input, "easy")) {
			
			allow_pondering = FALSE_C;
			
			return;
		}
		else if (!strcmp (input, "?")) {
			return;
		}
		else if (!strcmp (input, "white")) {
			white_to_move = 1;
			root_to_move = WHITE;
			comp_color = 0;
		}
		else if (!strcmp (input, "black")) {
			white_to_move = 0;
			root_to_move = BLACK;
			comp_color = 1;
		}
		else if (!strcmp (input, "force")) {
			force_mode = TRUE_C;
		}
		else if (!strcmp (input, "eval")) {
			check_phase();
			printf("Eval: %d\n", (int)eval());
		}
		else if (!strcmp (input, "go")) {
			comp_color = white_to_move;
			force_mode = FALSE_C;
		}
		else if (!strncmp (input, "time", 4)) {
			sscanf (input+5, "%d", &time_left);
		}
		else if (!strncmp (input, "otim", 4)) {
			sscanf (input+5, "%d", &opp_time);
		}
		else if (!strncmp (input, "level", 5)) {
			if (strstr(input+6, ":"))
			{
				/* time command with seconds */
				sscanf (input+6, "%d %d:%d %d", &moves_to_tc, &min_per_game, 
						&sec_per_game, &inc);
				time_left = (min_per_game*6000) + (sec_per_game * 100);
				opp_time = time_left;
			}
			else
			{
				/* extract the time controls: */
				sscanf (input+6, "%d %d %d", &moves_to_tc, &min_per_game, &inc);
				time_left = min_per_game*6000;
				opp_time = time_left;
			}
			fixed_time = FALSE_C;
			time_cushion = 0; 
		}
		else if (!strncmp (input, "rating", 6)) {
			sscanf (input+7, "%d %d", &my_rating, &opp_rating);
			if (my_rating == 0) my_rating = 2000;
			if (opp_rating == 0) opp_rating = 2000;
		}
		else if (!strncmp (input, "holding", 7)) {
			ProcessHoldings(input);     
		}
		else if (!strncmp (input, "variant", 7)) {
			if (strstr(input, "normal"))
			{
				Variant = Normal;
				memcpy(material, std_material, sizeof(std_material));
				init_book();
			}
			else if (strstr(input, "crazyhouse"))
			{
				Variant = Crazyhouse;
				memcpy(material, zh_material, sizeof(zh_material));
				init_book();
			}
			else if (strstr(input, "bughouse"))
			{
				Variant = Bughouse;
				memcpy(material, zh_material, sizeof(zh_material));
				init_book();
			}
			else if (strstr(input, "suicide"))
			{
				Variant = Suicide;
				Giveaway = FALSE_C;
				memcpy(material, suicide_material, sizeof(suicide_material));
				init_book();
			}
			else if (strstr(input, "giveaway"))
			{
				Variant = Suicide;
				Giveaway = TRUE_C;
				memcpy(material, suicide_material, sizeof(suicide_material));
				init_book();
			}
			else if (strstr(input, "losers"))
			{
				Variant = Losers;
				memcpy(material, losers_material, sizeof(losers_material));
				init_book();
			}
			
			initialize_hash();
			clear_tt();
			reset_ecache();
			
		}
		else if (!strncmp (input, "analyze", 7)) {
			is_analyzing = TRUE_C;
			is_pondering = TRUE_C;
			think();
			ply = 0;
		}
		else if (!strncmp (input, "undo", 4)) {
			printf("Move number : %d\n", move_number);
			if (move_number > 0)
			{
				path_x[0] = game_history_x[--move_number];
				unmake(&game_history[move_number], 0);
				reset_piece_square();
				root_to_move ^= 1;
			}
			result = 0;
		}
		else if (!strncmp (input, "remove", 5)) {
			if (move_number > 1)
			{
				path_x[0] = game_history_x[--move_number];
				unmake(&game_history[move_number], 0);
				reset_piece_square();
				
				path_x[0] = game_history_x[--move_number];
				unmake(&game_history[move_number], 0);
				reset_piece_square();
			}
			result = 0;
		}
		else if (!strncmp (input, "edit", 4)) {
			is_edit_mode = TRUE_C;
			edit_color = WHITE;
		}
		else if (!strncmp (input, ".", 1) && is_edit_mode) {
			is_edit_mode = FALSE_C;
			if (wking_loc == 30) white_castled = no_castle;
			if (bking_loc == 114) black_castled = no_castle;
			book_ply = 50;
			ep_square = 0;
			move_number = 0;
			memset(opening_history, 0, sizeof(opening_history));
			clear_tt();
			initialize_hash();
			reset_piece_square();
		}
		else if (is_edit_mode && !strncmp (input, "c", 1)) {
			if (edit_color == WHITE) edit_color = BLACK; else edit_color = WHITE;
		}
		else if (is_edit_mode && !strncmp (input, "#", 1)) {
			reset_board();
			move_number = 0;
		}
		else if (is_edit_mode 
				 && isalpha(input[0]) 
				 && isalpha(input[1]) 
				 && isdigit(input[2])) {
			PutPiece(edit_color, input[0], input[1], input[2]);
		}
		else if (!strncmp (input, "partner", 7)) {
			HandlePartner(input+7);
		}
		else if (!strncmp (input, "$partner", 8)) {
			HandlePartner(input+8);
		}
		else if (!strncmp (input, "ptell", 5)) {
			HandlePtell(input);
		}
		else if (!strncmp (input, "test", 4)) {
			run_epd_testsuite();
		}
		else if (!strncmp (input, "st", 2)) {
			sscanf(input+3, "%d", &fixed_time);
			fixed_time = fixed_time * 100;
		}
		else if (!strncmp (input, "book", 4)) {
			build_book();
		}
		else if (!strncmp (input, "speed",  5)) {
			speed_test();
		}
		else if (!strncmp (input, "result", 6)) {
			if (cfg_booklearn)
			{
				if (strstr (input+7, "1-0"))
				{
					if (comp_color == 1)
						book_learning(WIN);
					else
						book_learning(LOSS);
				}
				else if (strstr(input+7, "0-1"))
				{
					if (comp_color == 1)
						book_learning(LOSS);
					else
						book_learning(WIN);
				}
				else if (strstr(input+7, "1/2-1/2"))
				{
					book_learning(DRAW);
				};
			}
		}
		else if (!strncmp (input, "prove", 5)) {
			printf("\nMax time to search (s): ");
			start_time = rtime();
			rinput(readbuff, STR_BUFF, stdin);
			pn_time = atoi(readbuff) * 100;
			printf("\n");
			proofnumbersearch();      
		}
		else if (!strncmp (input, "ping", 4)) {
			sscanf (input+5, "%d", &pingnum);
			printf("pong %d\n", pingnum);
		}
		else if (!strncmp (input, "fritz", 5)) {
			braindeadinterface = TRUE_C;
		}
		else if (!strncmp (input, "reset", 5)) {
			
			memcpy(material, std_material, sizeof(std_material));
			Variant = Normal;
			
			init_game ();
			initialize_hash();
			
			clear_tt();
			init_book();
			reset_ecache();       
			
			force_mode = FALSE_C;
			fixed_time = FALSE_C;
			
			root_to_move = WHITE;
			
			comp_color = 0;
			move_number = 0;
			bookidx = 0;
			my_rating = opp_rating = 2000;
		}
		else if (!strncmp (input, "setboard", 8)) {
			setup_epd_line(input+9);
		}
		else if (!strncmp (input, "buildegtb", 9)) {
			Variant = Suicide;
			gen_all_tables();
		}
		else if (!strncmp (input, "lookup", 6)) {
			Variant = Suicide;
			printf("Value : %d\n", egtb(white_to_move));
		}
		else if (!strncmp (input, ".", 1)) {
			/* periodic updating and were not searching */
			/* most likely due to proven mate */
			return;
		}
		else if (!strncmp (input, "sd", 2)) {
			sscanf(input+3, "%d", &maxdepth);
			printf("New max depth set to: %d\n", maxdepth);
			return;
		}
		else if (!strncmp (input, "auto", 4)) {
			automode = 1;
			return;
		}
		else if (!strncmp (input, "protover", 8)) {
			printf("feature ping=1 setboard=1 playother=0 san=0 usermove=0 time=1\n");
			printf("feature draw=0 sigint=0 sigterm=0 reuse=1 analyze=1\n");
			printf("feature myname=\"Sjeng " VERSION "\"\n");
			printf("feature variants=\"normal,bughouse,crazyhouse,suicide,giveaway,losers\"\n");
			printf("feature colors=1 ics=0 name=0 pause=0 done=1\n");
			xb_mode = 2;
		}
		else if (!strncmp (input, "accepted", 8)) {
			/* do nothing as of yet */
		}
		else if (!strncmp (input, "rejected", 8)) {
			printf("Interface does not support a required feature...expect trouble.\n");
		}
		else if (!strncmp (input, "warranty", 8)) {
			printf("\n  BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY\n"
				   "FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN\n"
				   "OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES\n"
				   "PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED\n"
				   "OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n"
				   "MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS\n"
				   "TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE\n"
				   "PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,\n"
				   "REPAIR OR CORRECTION.\n"
				   "\n");
			printf("  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\n"
				   "WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR\n"
				   "REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,\n"
				   "INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING\n"
				   "OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED\n"
				   "TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY\n"
				   "YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER\n"
				   "PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE\n"
				   "POSSIBILITY OF SUCH DAMAGES.\n\n");
			
		}
		else if (!strncmp (input, "distribution", 12)) {
			printf("\n  You may copy and distribute verbatim copies of the Program's\n"
				   "source code as you receive it, in any medium, provided that you\n"
				   "conspicuously and appropriately publish on each copy an appropriate\n"
				   "copyright notice and disclaimer of warranty; keep intact all the\n"
				   "notices that refer to this License and to the absence of any warranty;\n"
				   "and give any other recipients of the Program a copy of this License\n"
				   "along with the Program.\n"
				   "\n"
				   "You may charge a fee for the physical act of transferring a copy, and\n"
				   "you may at your option offer warranty protection in exchange for a fee.\n\n");
			
		}
		else if (!strcmp (input, "help")) {
			printf ("\n%s\n\n", divider);
			printf ("diagram/d:       toggle diagram display\n");
			printf ("exit/quit:       terminate Sjeng\n");
			printf ("go:              make Sjeng play the side to move\n");
			printf ("new:             start a new game\n");
			printf ("level <x>:       the xboard style command to set time\n");
			printf ("  <x> should be in the form: <a> <b> <c> where:\n");
			printf ("  a -> moves to TC (0 if using an ICS style TC)\n");
			printf ("  b -> minutes per game\n");
			printf ("  c -> increment in seconds\n");
			printf ("nodes:           outputs the number of nodes searched\n");
			printf ("nps:             outputs Sjeng's NPS in search\n");
			printf ("perft <x>:       compute raw nodes to depth x\n");
			printf ("post:            toggles thinking output\n");
			printf ("xboard:          put Sjeng into xboard mode\n");
			printf ("test:            run an EPD testsuite\n");
			printf ("speed:           test movegen and evaluation speed\n");
			printf ("warranty:        show warranty details\n");
			printf ("distribution:    show distribution details\n");
			printf( "proof:           try to prove or disprove the current pos\n");
			printf( "sd <x>:          limit thinking to depth x\n");
			printf( "st <x>:          limit thinking to x centiseconds\n");
			printf( "setboard <FEN>:  set board to a specified FEN string\n");
			printf( "undo:            back up a half move\n");
			printf( "remove:          back up a full move\n");
			printf( "force:           disable computer moving\n");
			printf( "auto:            computer plays both sides\n");
			printf ("\n%s\n\n", divider);
			
			show_board = 0;
		}
		else if (!xb_mode) {
			printf ("Illegal move: %s\n", input);
		}
		
	}
	
}
Exemple #4
0
int main (int argc, char *argv[]) {

  char input[STR_BUFF], *p, output[STR_BUFF];
  move_s move, comp_move;
  int depth = 4, comp_color;
  bool force_mode, show_board;
  double nps, elapsed;
  clock_t cpu_start = 0, cpu_end = 0;

  parse_cmdline (argc, argv);
  start_up ();
  init_hash_values ();
  init_hash_tables ();
  init_game ();
  init_book ();
  xb_mode = FALSE;
  force_mode = FALSE;
  comp_color = 0;
  show_board = TRUE;
  
  setbuf (stdout, NULL);
  setbuf (stdin, NULL);

  /* keep looping for input, and responding to it: */
  while (TRUE) {

    /* case where it's the computer's turn to move: */
    if (comp_color == white_to_move && !force_mode) {
      nodes = 0;
      qnodes = 0;
      ply = 0;

      start_time = rtime ();
      cpu_start = clock ();
      comp_move = think ();
      cpu_end = clock ();

      /* check for a game end: */
      if (((comp_color == 1 && result != white_is_mated) ||
	  (comp_color == 0 && result != black_is_mated)) &&
	  result != stalemate && result != draw_by_fifty &&
	  result != draw_by_rep) {
	
	comp_to_coord (comp_move, output);

	make (&comp_move, 0);

	/* check to see if we draw by rep/fifty after our move: */
	if (is_draw ()) {
	  result = draw_by_rep;
	}
	else if (fifty > 100) {
	  result = draw_by_fifty;
	}

	reset_piece_square ();
	/* check to see if we mate our opponent with our current move: */
	if (!result) {
	  if (xb_mode) {
	    printf ("move %s\n", output);
	  }
	  else {
	    printf ("\n%s\n", output);
	  }
	}
	else {
	  if (xb_mode) {
	    printf ("move %s\n", output);
	  }
	  else {
	    printf ("\n%s\n", output);
	  }
	  if (result == white_is_mated) {
	    printf ("0-1 {Black Mates}\n");
	  }
	  else if (result == black_is_mated) {
	    printf ("1-0 {White Mates}\n");
	  }
	  else if (result == draw_by_fifty) {
	    printf ("1/2-1/2 {Fifty move rule}\n");
	  }
	  else if (result == draw_by_rep) {
	    printf ("1/2-1/2 {3 fold repetition}\n");
	  }
	  else {
	    printf ("1/2-1/2 {Draw}\n");
	  }
	}
      }
      /* we have been mated or there is a draw: */
      else {
	if (result == white_is_mated) {
	  printf ("0-1 {Black Mates}\n");
	}
	else if (result == black_is_mated) {
	  printf ("1-0 {White Mates}\n");
	}
	else if (result == stalemate) {
	  printf ("1/2-1/2 {Stalemate}\n");
	}
	else if (result == draw_by_fifty) {
	  printf ("1/2-1/2 {Fifty move rule}\n");
	}
	else if (result == draw_by_rep) {
	  printf ("1/2-1/2 {3 fold repetition}\n");
	}
	else {
	  printf ("1/2-1/2 {Draw}\n");
	}
      }

    }

    /* get our input: */
    if (!xb_mode) {
      if (show_board && strcmp (input, "help")) {
	printf ("\n");
	display_board (stdout, 1-comp_color);
      }
      printf ("Faile> ");
      rinput (input, STR_BUFF, stdin);
    }
    else {
      rinput (input, STR_BUFF, stdin);
    }

    /* check to see if we have a move.  If it's legal, play it. */
    if (is_valid_comp (pgn_to_comp (input))) {
      /* good SAN input style move */
      move = pgn_to_comp (input);
      make (&move, 0);
      reset_piece_square ();
      if (show_board) {
	printf ("\n");
	display_board (stdout, 1-comp_color);
      }
    }
    else if (is_move (&input[0])) {
      /* good coordinate style input move */
      if (verify_coord (input, &move)) {
	make (&move, 0);
	reset_piece_square ();
	if (show_board) {
	  printf ("\n");
	  display_board (stdout, 1-comp_color);
	}
      }
      else {
	printf ("Illegal move: %s\n", input);
      }
    }
    else {

      /* make everything lower case for convenience: */
      for (p = input; *p; p++) *p = tolower (*p);

      /* command parsing: */
      if (!strcmp (input, "quit") || !strcmp (input, "exit")) {
	shut_down (EXIT_SUCCESS);
      }
      else if (!strcmp (input, "diagram") || !strcmp (input, "d")) {
	toggle_bool (&show_board);
      }
      else if (!strncmp (input, "perft", 5)) {
	sscanf (input+6, "%d", &depth);
	raw_nodes = 0;
	perft (depth);
	printf ("Raw nodes for depth %d: %ld\n", depth, raw_nodes);
      }
      else if (!strcmp (input, "new")) {
	init_game ();
	/* refresh our hash tables: */
	refresh_hash ();
	force_mode = FALSE;
	comp_color = 0;
      }
      else if (!strcmp (input, "xboard")) {
	xb_mode = TRUE;
	toggle_bool (&show_board);
	signal (SIGINT, SIG_IGN);
	printf ("\n");
      }
      else if (!strcmp (input, "nodes")) {
	printf ("Number of nodes: %li (%0.2f%% qnodes)\n", nodes,
		(float) ((float) qnodes / (float) nodes * 100.0));
      }
      else if (!strcmp (input, "nps")) {
	elapsed = (cpu_end-cpu_start)/(double) CLOCKS_PER_SEC;
	nps = (float) nodes/(float) elapsed;
	if (!elapsed)
	  printf ("NPS: N/A\n");
	else
	  printf ("NPS: %ld\n", (long int) nps);
      }
      else if (!strcmp (input, "post")) {
	toggle_bool (&post);
	if (xb_mode)
	  post = TRUE;
      }
      else if (!strcmp (input, "nopost")) {
	post = FALSE;
      }
      else if (!strcmp (input, "random")) {
	continue;
      }
      else if (!strcmp (input, "hard")) {
	continue;
      }
      else if (!strcmp (input, "easy")) {
	continue;
      }
      else if (!strcmp (input, "?")) {
	continue;
      }
      else if (!strcmp (input, "white")) {
	white_to_move = 1;
	comp_color = 0;
      }
      else if (!strcmp (input, "black")) {
	white_to_move = 0;
	comp_color = 1;
      }
      else if (!strcmp (input, "force")) {
	force_mode = TRUE;
      }
      else if (!strcmp (input, "go")) {
	comp_color = white_to_move;
	force_mode = FALSE;
      }
      else if (!strncmp (input, "time", 4)) {
	sscanf (input+5, "%ld", &time_left);
      }
      else if (!strncmp (input, "otim", 4)) {
	sscanf (input+5, "%ld", &opp_time);
      }
      else if (!strncmp (input, "level", 5)) {
	/* extract the time controls: */
	sscanf (input+6, "%ld %ld %ld", &moves_to_tc, &min_per_game, &inc);
	time_left = min_per_game*6000;
	opp_time = time_left;
	inc *= 100;
      }
      else if (!strncmp (input, "result", 6)) {
	ics_game_end ();
	init_game ();
	force_mode = FALSE;
	comp_color = 0;
      }
      else if (!strcmp (input, "help")) {
	printf ("\n%s\n\n", divider);
	printf ("diagram/d: toggle diagram display\n");
	printf ("exit/quit: terminate Faile\n");
	printf ("go:        make Faile play the side to move\n");
	printf ("new:       start a new game\n");
	printf ("level <x>: the xboard style command to set time\n");
	printf ("  <x> should be in the form: <a> <b> <c> where:\n");
	printf ("  a -> moves to TC (0 if using an ICS style TC)\n");
	printf ("  b -> minutes per game\n");
	printf ("  c -> increment in seconds\n");
	printf ("nodes:     outputs the number of nodes searched\n");
	printf ("nps:       outputs Faile's NPS in search\n");
	printf ("perft <x>: compute raw nodes to depth x\n");
	printf ("post:      toggles thinking output\n");
	printf ("xboard:    put Faile into xboard mode\n");
	printf ("\n%s\n\n", divider);
      }
      else if (!xb_mode) {
	printf ("Illegal move: %s\n", input);
      }

    }

  }

  return 0;

}
Exemple #5
0
/**
 * Principle Variation Search (fail-soft)
 * @param alpha lowerbound value
 * @param beta upperbound value
 * @param depth remaining search depth
 * @return score for the current node
 */
int search_t::pvs(int alpha, int beta, int depth) {

    assert(alpha < beta);
    assert(alpha >= -score::INF);
    assert(beta <= score::INF);

    stack->pv_count = 0;
    sel_depth = MAX(brd.ply, sel_depth);
    stack->best_move.clear();

    /*
     * If no more depth remaining, return quiescence value
     */

    if (depth < 1) {
        const int score = qsearch(alpha, beta, 0);
        return score;
    }

    /*
     * Stop conditions
     */

    //time 
    nodes++;
    if (abort()) {
        return alpha;
    }

    //ceiling
    if (brd.ply >= (MAX_PLY - 1)) {
        return evaluate(this);
    }

    assert(depth > 0 && depth <= MAX_PLY);
    int alpha1 = alpha;

    //mate distance pruning: if mate(d) in n don't search deeper
    if ((score::MATE - brd.ply) < beta) {
        beta = score::MATE - brd.ply;
        if (alpha >= beta) {
            return beta;
        }
    }
    if ((-score::MATE + brd.ply) > alpha) {
        alpha = -score::MATE + brd.ply;
        if (beta <= alpha) {
            return alpha;
        }
    }

    //draw by lack of material or fifty quiet moves
    if (is_draw()) {
        return draw_score();
    }

    /*
     * Transposition table lookup
     */

    const bool pv = alpha + 1 < beta;
    stack->tt_key = brd.stack->tt_key; //needed for testing repetitions
    int tt_move = 0, tt_flag = 0, tt_score;
    if (trans_table::retrieve(stack->tt_key, brd.ply, depth, tt_score, tt_move, tt_flag)) {
        if (pv && tt_flag == score::EXACT) {
            return tt_score;
        } else if (!pv && tt_score >= beta && tt_flag == score::LOWERBOUND) {
            return tt_score;
        } else if (!pv && tt_score <= alpha && tt_flag == score::UPPERBOUND) {
            return tt_score;
        }
    }
    stack->tt_move.set(tt_move);

    /*
     * Node pruning
     */

    const bool in_check = stack->in_check;
    const int eval = evaluate(this);
    const bool do_prune_node = eval >= beta && !in_check && !pv && !score::is_mate(beta) && brd.has_pieces(brd.us());

    // beta pruning
    if (do_prune_node && depth < 4 && beta_pruning) {
        int bp_score = eval - 50 * depth;
        if (bp_score >= beta) {
            return bp_score;
        }
    }

    //null move pruning
    if (do_prune_node && null_enabled) {
        int R = 3;
        forward();
        int null_score = -pvs(-beta, -alpha, depth - 1 - R);
        backward();
        if (stop_all) {
            return alpha;
        } else if (null_score >= beta) {
            const int RV = 5;
            if (null_verify && depth > RV && material::is_eg(this)) {
                //verification
                int verified_score = pvs(alpha, beta, depth - 1 - RV);
                if (verified_score >= beta) {
                    return verified_score;
                }
            } else {
                //no verification
                return null_score;
            }
        }
    }

    /*
     * Internal iterative deepening (IID)
     */

    if (pv && depth > 2 && tt_move == 0) {
        int iid_score = pvs(alpha, beta, depth - 2);
        if (score::is_mate(iid_score)) {
            return iid_score;
        } else if (stack->best_move.piece) {
            stack->tt_move.set(&stack->best_move);
        }
    }

    /*
     * Moves loop
     */

    //if there is no first move, it's checkmate or stalemate
    move_t * move = move::first(this, depth);
    if (!move) {
        return in_check ? -score::MATE + brd.ply : draw_score();
    }

    //set futility pruning delta value
    bool do_ffp = false;
    int delta = score::INVALID;
    if (depth <= 8 && !in_check && !score::is_mate(alpha) && !material::is_eg(this) && ffp_enabled) {
        int ffp_score = eval + 40 * depth;
        if (ffp_score <= alpha) {
            do_ffp = true;
            delta = ffp_score + 50;
        }
    }

    //prepare and do the loop
    int best = -score::INF;
    int searched_moves = 0;
    const int score_max = score::MATE - brd.ply - 1;
    stack->best_move.clear();
    do {

        assert(brd.valid(move) && brd.legal(move));
        assert(stack->best_move.equals(move) == false);
        assert(in_searched(move, searched_moves) == false);

        const int gives_check = brd.gives_check(move);
        assert(gives_check == 0 || gives_check == 1 || gives_check == 2);

        /*
         * Move pruning: skip all futile moves
         */

        const bool is_dangerous = in_check || gives_check || move->capture || move->promotion || move->castle || is_advanced_passed_pawn(move);

        bool pruned = false;
        if (do_ffp && searched_moves > 0) {
            pruned = !is_dangerous;
            pruned |= gives_check == 0 && (move->capture || move->promotion) && brd.max_gain(move) + delta <= alpha;
            if (pruned) {
                pruned_nodes++;
                continue;
            }
        }


        /*
         * Move extensions
         */

        int extend = extension(move, depth, pv, gives_check);

        /*
         * Move Reductions (Late Move Reductions, LMR) 
         */

        int reduce = reduction(depth, searched_moves, is_dangerous);

        /*
         * Go forward and search next node
         */

        forward(move, gives_check);
        int score;
        if (searched_moves == 0) {
            score = -pvs(-beta, -alpha, depth - 1 + extend);
        } else {
            score = -pvs(-alpha - 1, -alpha, depth - 1 - reduce + extend);
            if (score > alpha && (pv || reduce > 0)) { //open window research without reductions
                score = -pvs(-beta, -alpha, depth - 1 + extend);
            }
        }
        backward(move);

        /*
         * Handle results: update the best value / do a beta cutoff
         */

        if (stop_all) {
            return alpha;
        } else if (score > best) {
            stack->best_move.set(move);
            if (score >= beta) {
                trans_table::store(stack->tt_key, brd.root_ply, brd.ply, depth, score, move->to_int(), score::LOWERBOUND);
                if (!move->capture && !move->promotion && !move->castle) {
                    update_killers(move);
                    update_history(move);
                    for (int i = 0; i < searched_moves; i++) {
                        move_t * m = &stack->searched[i];
                        if (!m->capture && !m->promotion && !m->castle) {
                            history[m->piece][m->tsq] >>= searched_moves;
                        }
                    }
                }
Exemple #6
0
Value name_NT_InCheck(qsearch)(Pos* pos, Stack* ss, Value alpha, BETA_ARG
                               Depth depth)
{
  assert(InCheck == !!pos_checkers());
  assert(alpha >= -VALUE_INFINITE && alpha < beta && beta <= VALUE_INFINITE);
  assert(PvNode || (alpha == beta - 1));
  assert(depth <= DEPTH_ZERO);

  Move pv[MAX_PLY+1];
  TTEntry *tte;
  Key posKey;
  Move ttMove, move, bestMove;
  Value bestValue, value, ttValue, futilityValue, futilityBase, oldAlpha;
  int ttHit, ttPv, givesCheck, evasionPrunable;
  Depth ttDepth;
  int moveCount;

  if (PvNode) {
    oldAlpha = alpha; // To flag BOUND_EXACT when eval above alpha and no available moves
    (ss+1)->pv = pv;
    ss->pv[0] = 0;
  }

  bestMove = 0;
  moveCount = 0;

  // Check for an instant draw or if the maximum ply has been reached
  if (is_draw(pos) || ss->ply >= MAX_PLY)
    return ss->ply >= MAX_PLY && !InCheck ? evaluate(pos) : VALUE_DRAW;

  assert(0 <= ss->ply && ss->ply < MAX_PLY);

  // Decide whether or not to include checks: this fixes also the type of
  // TT entry depth that we are going to use. Note that in qsearch we use
  // only two types of depth in TT: DEPTH_QS_CHECKS or DEPTH_QS_NO_CHECKS.
  ttDepth = InCheck || depth >= DEPTH_QS_CHECKS ? DEPTH_QS_CHECKS
                                                : DEPTH_QS_NO_CHECKS;

  // Transposition table lookup
  posKey = pos_key();
  tte = tt_probe(posKey, &ttHit);
  ttValue = ttHit ? value_from_tt(tte_value(tte), ss->ply) : VALUE_NONE;
  ttMove = ttHit ? tte_move(tte) : 0;
  ttPv = ttHit ? tte_is_pv(tte) : 0;

  if (  !PvNode
      && ttHit
      && tte_depth(tte) >= ttDepth
      && ttValue != VALUE_NONE // Only in case of TT access race
      && (ttValue >= beta ? (tte_bound(tte) &  BOUND_LOWER)
                          : (tte_bound(tte) &  BOUND_UPPER)))
    return ttValue;

  // Evaluate the position statically
  if (InCheck) {
    ss->staticEval = VALUE_NONE;
    bestValue = futilityBase = -VALUE_INFINITE;
  } else {
    if (ttHit) {
      // Never assume anything on values stored in TT
      if ((ss->staticEval = bestValue = tte_eval(tte)) == VALUE_NONE)
         ss->staticEval = bestValue = evaluate(pos);

      // Can ttValue be used as a better position evaluation?
      if (ttValue != VALUE_NONE)
        if (tte_bound(tte) & (ttValue > bestValue ? BOUND_LOWER : BOUND_UPPER))
          bestValue = ttValue;
    } else
      ss->staticEval = bestValue =
      (ss-1)->currentMove != MOVE_NULL ? evaluate(pos)
                                       : -(ss-1)->staticEval + 2 * Tempo;

    // Stand pat. Return immediately if static value is at least beta
    if (bestValue >= beta) {
      if (!ttHit)
        tte_save(tte, posKey, value_to_tt(bestValue, ss->ply), ttPv,
                 BOUND_LOWER, DEPTH_NONE, 0, ss->staticEval,
                 tt_generation());

      return bestValue;
    }

    if (PvNode && bestValue > alpha)
      alpha = bestValue;

    futilityBase = bestValue + 128;
  }

  ss->history = &(*pos->counterMoveHistory)[0][0];

  // Initialize move picker data for the current position, and prepare
  // to search the moves. Because the depth is <= 0 here, only captures,
  // queen promotions and checks (only if depth >= DEPTH_QS_CHECKS) will
  // be generated.
  mp_init_q(pos, ttMove, depth, to_sq((ss-1)->currentMove));

  // Loop through the moves until no moves remain or a beta cutoff occurs
  while ((move = next_move(pos, 0))) {
    assert(move_is_ok(move));

    givesCheck = gives_check(pos, ss, move);

    moveCount++;

    // Futility pruning
    if (   !InCheck
        && !givesCheck
        &&  futilityBase > -VALUE_KNOWN_WIN
        && !advanced_pawn_push(pos, move)) {
      assert(type_of_m(move) != ENPASSANT); // Due to !advanced_pawn_push

      futilityValue = futilityBase + PieceValue[EG][piece_on(to_sq(move))];

      if (futilityValue <= alpha) {
        bestValue = max(bestValue, futilityValue);
        continue;
      }

      if (futilityBase <= alpha && !see_test(pos, move, 1)) {
        bestValue = max(bestValue, futilityBase);
        continue;
      }
    }

    // Detect non-capture evasions that are candidates to be pruned
    evasionPrunable =    InCheck
                     && (depth != DEPTH_ZERO || moveCount > 2)
                     &&  bestValue > VALUE_MATED_IN_MAX_PLY
                     && !is_capture(pos, move);

    // Don't search moves with negative SEE values
    if (  (!InCheck || evasionPrunable)
        &&  !see_test(pos, move, 0))
      continue;

    // Speculative prefetch as early as possible
    prefetch(tt_first_entry(key_after(pos, move)));

    // Check for legality just before making the move
    if (!is_legal(pos, move)) {
      moveCount--;
      continue;
    }

    ss->currentMove = move;
    ss->history = &(*pos->counterMoveHistory)[moved_piece(move)][to_sq(move)];

    // Make and search the move
    do_move(pos, move, givesCheck);
#if PvNode
    value =  givesCheck
           ? -qsearch_PV_true(pos, ss+1, -beta, -alpha, depth - ONE_PLY)
           : -qsearch_PV_false(pos, ss+1, -beta, -alpha, depth - ONE_PLY);
#else
    value =  givesCheck
           ? -qsearch_NonPV_true(pos, ss+1, -beta, depth - ONE_PLY)
           : -qsearch_NonPV_false(pos, ss+1, -beta, depth - ONE_PLY);
#endif
    undo_move(pos, move);

    assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);

    // Check for a new best move
    if (value > bestValue) {
      bestValue = value;

      if (value > alpha) {
        bestMove = move;

        if (PvNode) // Update pv even in fail-high case
          update_pv(ss->pv, move, (ss+1)->pv);

        if (PvNode && value < beta) // Update alpha here!
          alpha = value;
        else
          break; // Fail high
      }
    }
  }

  // All legal moves have been searched. A special case: If we're in check
  // and no legal moves were found, it is checkmate.
  if (InCheck && bestValue == -VALUE_INFINITE)
    return mated_in(ss->ply); // Plies to mate from the root

  tte_save(tte, posKey, value_to_tt(bestValue, ss->ply), ttPv,
           bestValue >= beta ? BOUND_LOWER :
           PvNode && bestValue > oldAlpha  ? BOUND_EXACT : BOUND_UPPER,
           ttDepth, bestMove, ss->staticEval, tt_generation());

  assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);

  return bestValue;
}
void E_scene_main_game::update_result()
{
	
	/* check for draw by the 50 move rule: */
	if (fifty > 100) 
	{
		result = draw_by_fifty;
		return;		
	}
	else if (is_draw ()) 
	{
		result = draw_by_rep;
		return;
	}
	
	
	move_s moves[MOVE_BUFF];
	int num_moves, i, ep_temp;
	d_long temp_hash;

	ep_temp = ep_square;
	temp_hash = cur_pos;
	num_moves = 0;
	gen (&moves[0], &num_moves);
	
	// for all possible moves for all pieces
	for (i = 0; i < num_moves; i++) 
	{
		// if the move is from the side of the current player
		bool color=moves[i].from%2;
		if (current_color==WHITE)
			color=!color;
		
		// if the selected piece is not owned by the current player, continue
		if (!color) 
			continue;
		
		// test if the move is legal
		make (&moves[0], i);
		bool legal=check_legal (&moves[0], i); 
		
		unmake (&moves[0], i);
		ep_square = ep_temp;
		cur_pos = temp_hash;
		
		// if we find a legal move, game can continue
		if (legal)
			return;
	}	
	
	
	// if we are here, it means that there is no
	// move avaible for the current player
	if (in_check ())
	{
		if (white_to_move == 1)
			result = white_is_mated;
		else 
			result = black_is_mated;
	}
	else 
	{
		result = stalemate;
	}
	
}
Exemple #8
0
void test_board_is_draw() {
  Board* board = draw_board();
  assert(is_draw(board));
  destroy_board(board);
}