Exemple #1
0
static char *boardmargin(void)
{
	static char buf[STRLEN];

	if (currbp->id)
		//% snprintf(buf, sizeof(buf), "讨论区 [%s]", currboard);
		snprintf(buf, sizeof(buf), "\xcc\xd6\xc2\xdb\xc7\xf8 [%s]", currboard);
	else {
		brc_init(currentuser.userid, DEFAULTBOARD);

		board_t board;
		get_board(DEFAULTBOARD, &board);
		change_board(&board);

		//% sprintf(buf, "讨论区 [%s]", currboard);
		sprintf(buf, "\xcc\xd6\xc2\xdb\xc7\xf8 [%s]", currboard);
	}
	return buf;
}
Exemple #2
0
void		place_pawns(t_board *board, t_surfaces *surf)
{
  SDL_Rect	pos;
  unsigned int	i;

  /* dump_board2(board); */
  /* printf("\n---\n\n"); */

  pos.w = 32;
  pos.h = 32; 

  for (i = 0; i < 19 * 19; i++)
    {
      pos.x = (i / 19) * 32 + 16;
      pos.y = (i % 19) * 32 + 16;
      switch (get_board(board, (i / 19), (i % 19)))
	{
	case BLACK:
	  SDL_BlitSurface(surf->blackstone, NULL, surf->screen, &pos);		  
	  break;
	case WHITE:
	  SDL_BlitSurface(surf->whitestone, NULL, surf->screen, &pos);
	  break;
	}
    }

  for (i = 0; i < (board->blacks*2); i++)
    {
      pos.x = -16; /* WTF */
      pos.y = i * 32;
      SDL_BlitSurface(surf->blackstone, NULL, surf->screen, &pos);
    }

  pos.x = 640 - 16;
  for (i = 0; i < (board->whites*2); i++)
    {
      pos.y = (640 - 32) - (i * 32);
      SDL_BlitSurface(surf->whitestone, NULL, surf->screen, &pos);
    }

}
Exemple #3
0
/* Does the string at (i, j) have any more liberty than the one at
 * (libi, libj)?
 */
static int
has_additional_liberty(int i, int j, int libi, int libj)
{
  int pos = POS(i, j);
  do {
    int ai = I(pos);
    int aj = J(pos);
    int k;
    for (k = 0; k < 4; k++) {
      int bi = ai + deltai[k];
      int bj = aj + deltaj[k];
      if (on_board(bi, bj) && get_board(bi, bj) == EMPTY
	  && (bi != libi || bj != libj))
	return 1;
    }

    pos = next_stone[pos];
  } while (pos != POS(i, j));

  return 0;
}
Exemple #4
0
void active_board_init(bool force)
{
	fb_time_t now = fb_time();
	if (!force) {
		fb_time_t last = mdb_integer(0, "GET", ACTIVE_BOARD_UPTIME_KEY);
		if (now - last < ACTIVE_BOARD_INIT_INTERVAL)
			return;
	}
	mdb_cmd("SET", ACTIVE_BOARD_UPTIME_KEY" %"PRIdFBT, now);

	board_t board;
	if (get_board(ACTIVE_BOARD_NAME, &board) <= 0)
		return;

	record_t record;
	if (post_record_open(board.id, &record) < 0)
		return;

	active_board_clear();
	record_foreach(&record, NULL, 0, active_board_init_callback, NULL);

	record_close(&record);
}
Exemple #5
0
bool GoBoard::is_virtual_eye(int point, int color)
{
    if (!is_surrounded(point, color)) return false;
    int nopponent = 0;
    int ai = I(point);
    int aj = J(point);
    bool at_edge = false;
    for (int i = 0; i < 4; i++) {
        int bi = ai + diag_i[i];
        int bj = aj + diag_j[i];
        if (!on_board(bi,bj))
        {
            at_edge = true;
            continue;
        }
        if( get_board(bi,bj) == OTHER_COLOR(color) ) {
            nopponent++;
        }
    }
    if(at_edge)
        ++nopponent;
    return nopponent < 2;
}
Exemple #6
0
static int
gtp_showboard(char *s)
{
  int i, j;
  int symbols[3] = {'.', 'O', 'X'};
  
  gtp_start_response(GTP_SUCCESS);
  gtp_printf("\n");

  letters();
  
  for (i = 0; i < board_size; i++) {
    printf("\n%2d", board_size - i);
    
    for (j = 0; j < board_size; j++)
      printf(" %c", symbols[get_board(i, j)]);

    printf(" %d", board_size - i);
  }
  
  printf("\n");
  letters();
  return gtp_finish_response();
}
Exemple #7
0
/* Common code for fixed_handicap and place_free_handicap. */
static int
place_handicap(char *s, int fixed)
{
  int handicap;
  int m, n;
  int first_stone = 1;

  if (!board_empty())
    return gtp_failure("board not empty");

  if (sscanf(s, "%d", &handicap) < 1)
    return gtp_failure("handicap not an integer");
  
  if (handicap < 2)
    return gtp_failure("invalid handicap");

  if (fixed && !valid_fixed_handicap(handicap))
    return gtp_failure("invalid handicap");

  if (fixed)
    place_fixed_handicap(handicap);
  else
    place_free_handicap(handicap);

  gtp_start_response(GTP_SUCCESS);
  for (m = 0; m < board_size; m++)
    for (n = 0; n < board_size; n++)
      if (get_board(m, n) != EMPTY) {
	if (first_stone)
	  first_stone = 0;
	else
	  gtp_printf(" ");
	gtp_mprintf("%m", m, n);
      }
  return gtp_finish_response();
}
int main(int argc, char * argv[])
{
    pack_item_t user;
    /* char buffer[2048]; */
    int ret;
    int board_num;
    int start_board, end_board, stop_at;
    result_t * results;
    FILE * output_fh;
    int min_depth_for_scan2;
    int iters_limit = 100000;
    int max_var_depth_to_check = 100;

#ifndef WIN32
    struct timeval tv;
    struct timezone tz;
#else
    struct _timeb tb;
#endif
    int total_num_iters = 0;
    char * error_string;
    char * scan1_to = NULL, * scan2_to = NULL;

    char * output_filename = NULL;
    fcs_state_string_t state_string;

    int arg = 1, start_from_arg = -1, end_args = -1;

    if (argc < 4)
    {
        fprintf(stderr, "Not Enough Arguments!\n");
        print_help();
        exit(-1);
    }
    start_board = atoi(argv[arg++]);
    end_board = atoi(argv[arg++]);
    stop_at = atoi(argv[arg++]);

    for (;arg < argc; arg++)
    {
        if (!strcmp(argv[arg], "--args-start"))
        {
            arg++;

            start_from_arg = arg;
            while (arg < argc)
            {
                if (!strcmp(argv[arg], "--args-end"))
                {
                    break;
                }
                arg++;
            }
            end_args = arg;
        }
        else if (!strcmp(argv[arg], "--output-to"))
        {
            arg++;
            if (arg == argc)
            {
                fprintf(stderr, "--output-to came without an argument!\n");
                print_help();
                exit(-1);
            }
            output_filename = argv[arg];
        }
        else if (!strcmp(argv[arg], "--scan1-to"))
        {
            arg++;
            if (arg == argc)
            {
                fprintf(stderr, "--scan1-to came without an argument!\n");
                print_help();
                exit(-1);
            }
            scan1_to = argv[arg];
        }
        else if (!strcmp(argv[arg], "--scan2-to"))
        {
            arg++;
            if (arg == argc)
            {
                fprintf(stderr, "--scan1-to came without an argument!\n");
                print_help();
                exit(-1);
            }
            scan2_to = argv[arg];
        }
        else if (!strcmp(argv[arg], "--iters-limit"))
        {
            arg++;
            if (arg == argc)
            {
                fprintf(stderr, "--iters-limit came without an argument!\n");
                print_help();
                exit(-1);
            }
            iters_limit = atoi(argv[arg]);
        }
        else if (!strcmp(argv[arg], "--max-var-depth"))
        {
            arg++;
            if (arg == argc)
            {
                fprintf(stderr, "--max-var-depth came without an argument!\n");
                print_help();
                exit(-1);
            }
            max_var_depth_to_check = atoi(argv[arg]);
        }
        else
        {
            fprintf(stderr, "Unknown argument - '%s'!\n", argv[arg]);
            exit(-1);
        }
    }

    if (!scan1_to)
    {
        fprintf(stderr, "--scan1-to not specified!\n");
        exit(-1);
    }
    
    if (!scan2_to)
    {
        fprintf(stderr, "--scan2-to not specified!\n");
        exit(-1);
    }

    if (!output_filename)
    {
        fprintf(stderr, "output filename not specified");
        exit(-1);
    }

    /* for(board_num=1;board_num<100000;board_num++) */
#ifndef WIN32
    gettimeofday(&tv,&tz);
    printf("Started at %li.%.6li\n",
        tv.tv_sec,
        tv.tv_usec
        );
#else
    _ftime(&tb);
    printf("Started at %li.%.6i\n",
        tb.time,
        tb.millitm*1000
        );
#endif
    fflush(stdout);

    results = malloc(sizeof(results[0]) * (end_board - start_board + 1));

    output_fh = fopen(output_filename, "wt");

    for (min_depth_for_scan2 = 0; min_depth_for_scan2 < max_var_depth_to_check ; 
            min_depth_for_scan2++)
    {
        user.instance = freecell_solver_user_alloc();

        if (start_from_arg >= 0)
        {
            freecell_solver_user_cmd_line_parse_args(
                user.instance,
                end_args,
                (freecell_solver_str_t *)argv,
                start_from_arg,
                known_parameters,
                NULL,
                &user,
                &error_string,
                &arg
            );
        }
        
        if (freecell_solver_user_set_depth_tests_order(
            user.instance,
            0,
            scan1_to,
            &error_string
            ))
        {
            fprintf(stderr, "Error! Got '%s'!\n", error_string);
            free(error_string);
            exit(-1);
        }
        if (freecell_solver_user_set_depth_tests_order(
            user.instance,
            min_depth_for_scan2,
            scan2_to,
            &error_string
            ))
        {
            fprintf(stderr, "Error! Got '%s'!\n", error_string);
            free(error_string);
            exit(-1);
        }


        ret = 0;

        total_num_iters = 0;

        for(board_num=start_board;board_num<=end_board;board_num++)
        {
            get_board(board_num, state_string);

            freecell_solver_user_limit_iterations(
                user.instance,
                iters_limit
            );

#ifndef WIN32
                gettimeofday(
                    &(results[board_num - start_board].start_tv), 
                    &tz
                );
#else
                _ftime(&(results[board_num - start_board].start_tb));
#endif
            
            results[board_num-start_board].verdict = ret =
                freecell_solver_user_solve_board(
                    user.instance,
                    state_string
                    );

#ifndef WIN32
                gettimeofday(
                    &(results[board_num - start_board].end_tv), 
                    &tz
                );
#else
                _ftime(&(results[board_num - start_board].end_tb));
#endif

            total_num_iters += 
                (results[board_num - start_board].num_iters
                    = freecell_solver_user_get_num_times(user.instance)
                );

            freecell_solver_user_recycle(user.instance);
        }

        freecell_solver_user_free(user.instance);

        printf("Reached depth %d\n", min_depth_for_scan2);
        
        fprintf(output_fh, "Depth == %d\n\n", min_depth_for_scan2);
        for(board_num=start_board;board_num<=end_board;board_num++)
        {
            fprintf(output_fh, "board[%d].ret == %d\n", board_num, results[board_num-start_board].verdict);
            fprintf(output_fh, "board[%d].iters == %d\n", board_num, results[board_num-start_board].num_iters);
            fprintf(output_fh, "board[%d].start = %li.%.6li\n", board_num, results[board_num-start_board].start_tv.tv_sec, results[board_num-start_board].start_tv.tv_usec);
            fprintf(output_fh, "board[%d].end = %li.%.6li\n", board_num, results[board_num-start_board].end_tv.tv_sec, results[board_num-start_board].end_tv.tv_usec);
        }
        fflush(output_fh);
    }

    fclose(output_fh);

    return 0;
}
Exemple #9
0
char		pose(t_board *board, t_pos *move, char current, char rules)
{
    int		i;
    char		get;
    int		iget;


    /* printf("At %i-%i: ", cor.move->x, cor.move->y); */

    // Pose
    get = get_board(board, move->x, move->y);
    if ((get == EMPTY) &&
            (!(rules & RULE3) || (rule3(board, move->x, move->y, current))))
    {
        set_board(board, move->x, move->y, current);
        printf("Placed a ");
        if (current == BLACK)
        {
            printf("Black");
            current = WHITE;
        }
        else
        {
            printf("White");
            current = BLACK;
        }
        printf(" Stone at %i:%i\n", move->x, move->y);

        // Prise
        iget = getprise(board, move->x, move->y, current);
        if (iget)
        {
            printf("Taken %i ", iget*2);
            if (current == BLACK)
            {
                board->blacks += iget;
                printf("Black Stones (%i total)\n", board->blacks*2);
            }
            else
            {
                board->whites += iget;
                printf("Whites Stones (%i total)\n", board->whites*2);
            }
            prise(board, move->x, move->y, current);
        }

        // Règle de 5
        // (rules & RULE5) &&
        for (i = 0; i < 19*19; i++)
        {
            move->x = i / 19;
            move->y = i % 19; //
            if ((get_board(board, move->x, move->y) == OPPOSITE(current)) && (rule5(board, move->x, move->y, OPPOSITE(current), rules)))
            {
                if (current == WHITE)
                    printf("Blacks wins with a row!\n");
                if (current == BLACK)
                    printf("Whites wins with a row!\n");
                return (OPPOSITE(current) + 10);
            }
        }

    }
    else
    {
        printf("There's ");
        switch (get)
        {
        case BLACK:
            printf("a Black Stone");
            break;
        case WHITE:
            printf("a White Stone");
            break;
        case EMPTY:
            printf("nothing");
            break;
        }
        printf(" at %i:%i\n", move->x, move->y);
    }


    return (current);
}
Exemple #10
0
/*******************************************************************
 *	根據 URLParaType 執行 POST 的要求
 *
 *	return HttpRespondType
 *******************************************************************/
int 
DoPostRequest(REQUEST_REC * r, BOARDHEADER * board, POST_FILE * pf)
{
	int result, URLParaType;
	char *form_data, *boardname;

	result = WEB_ERROR;
	URLParaType = r->URLParaType;
	boardname = board->filename;

	/* Get FORM data */
	if ((form_data = GetFormBody(r->content_length, WEBBBS_ERROR_MESSAGE)) == NULL)
		return WEB_ERROR;

#ifdef DEBUG
	weblog_line(server->debug_log, form_data);
	fflush(server->debug_log);
#endif

	if (PSCorrect == nLogin && URLParaType == PostSend)
	{
		/* PostSend allow username&password in form body without login */
		char pass[PASSLEN * 3];

		GetPara2(username, "Name", form_data, IDLEN, "");	/* get userdata from form */
		GetPara2(pass, "Password", form_data, PASSLEN * 3, "");
		Convert(pass, password);
		PSCorrect = CheckUserPassword(username, password);
	}

	if (URLParaType == PostSend
	    || URLParaType == TreaSend
	    || URLParaType == PostEdit
	    || URLParaType == TreaEdit
	    || URLParaType == PostForward
	    || URLParaType == TreaForward
	    || URLParaType == PostDelete
	    || URLParaType == TreaDelete
	    || URLParaType == SkinModify
	    || URLParaType == AccessListModify
		)
	{
		int perm;
		/* boardname should set in advance, now in ParseURI() */
		if (get_board(board, boardname) <= 0 || board->filename[0] == '\0')
			return WEB_BOARD_NOT_FOUND;
		if ((perm = CheckBoardPerm(board, &curuser)) != WEB_OK)
			return perm;
	}

	if (PSCorrect == Correct
	    || (PSCorrect == gLogin && (URLParaType == PostSend || URLParaType == TreaSend))
	    || URLParaType == UserNew)
	{
		int start, end;
		char path[PATHLEN];

		switch (URLParaType)
		{
			case PostSend:
			case TreaSend:
				if ((result = PostArticle(form_data, board, pf)))
				{
#if 1
					if (URLParaType == TreaSend)
					{
						if (strlen(pf->POST_NAME))
							sprintf(skin_file->filename, "/%streasure/%s/%s/$",
								BBS_SUBDIR, boardname, pf->POST_NAME);
						else
							sprintf(skin_file->filename, "/%streasure/%s/$",
								BBS_SUBDIR, boardname);
					}
					else
					{
						sprintf(skin_file->filename, "/%sboards/%s/",
						     BBS_SUBDIR, boardname);
					}
#endif

					if (PSCorrect == Correct)
						UpdateUserRec(URLParaType, &curuser, board);
				}
				break;

			case MailSend:
				if ((result = PostArticle(form_data, board, pf)))
				{
					sprintf(skin_file->filename, "/%smail/", BBS_SUBDIR);
					UpdateUserRec(URLParaType, &curuser, NULL);
				}
				break;

			case PostEdit:
			case TreaEdit:
				if ((result = EditArticle(form_data, board, pf)))
				{
					sprintf(skin_file->filename, "/%s%s.html",
						BBS_SUBDIR, pf->POST_NAME);
				}
				break;

			case PostForward:
			case TreaForward:
			case MailForward:
				if ((result = ForwardArticle(form_data, board, pf)))
				{
					find_list_range(&start, &end, pf->num, DEFAULT_PAGE_SIZE, pf->total_rec);
					setdotfile(path, pf->POST_NAME, NULL);
					sprintf(skin_file->filename, "/%s%s%d-%d",
					      BBS_SUBDIR, path, start, end);
				}
				break;

			case PostDelete:
			case TreaDelete:
			case MailDelete:
				if ((result = DeleteArticle(form_data, board, pf)))
				{
					if (URLParaType == PostDelete)
					{
						find_list_range(&start, &end, pf->num, DEFAULT_PAGE_SIZE, pf->total_rec);
						sprintf(skin_file->filename, "/%sboards/%s/%d-%d",
							BBS_SUBDIR, boardname, start, end);
					}
					else if (URLParaType == TreaDelete)
					{
						setdotfile(path, pf->POST_NAME, NULL);
						sprintf(skin_file->filename, "/%s%s",
							BBS_SUBDIR, path);
					}
					else
						/* MailDelete */
					{
						sprintf(skin_file->filename, "/%smail/", BBS_SUBDIR);
					}
				}
				break;

			case UserNew:
				if ((result = NewUser(form_data, &curuser)))
					sprintf(skin_file->filename, "%s%s%s",
						HTML_PATH, BBS_SUBDIR, HTML_UserNewOK);
				break;

			case UserIdent:
				if ((result = DoUserIdent(form_data, &curuser)))
					sprintf(skin_file->filename, "%s%s%s",
						HTML_PATH, BBS_SUBDIR, HTML_UserIdentOK);
				break;

			case UserData:
				if ((result = UpdateUserData(form_data, &curuser)))
					sprintf(skin_file->filename, "/%susers/%s",
						BBS_SUBDIR, HTML_UserData);
				break;

			case UserPlan:
				if ((result = UpdateUserPlan(form_data, &curuser)))
					sprintf(skin_file->filename, "/%susers/%s",
						BBS_SUBDIR, HTML_UserPlan);
				break;

			case UserSign:
				if ((result = UpdateUserSign(form_data, &curuser)))
					sprintf(skin_file->filename, "/%susers/%s",
						BBS_SUBDIR, HTML_UserSign);
				break;

			case UserFriend:
				if ((result = UpdateUserFriend(form_data, &curuser)))
					sprintf(skin_file->filename, "/%susers/%s",
						BBS_SUBDIR, HTML_UserFriend);
				break;

#ifdef WEB_ADMIN
			case BoardModify:	/* admin function */
				if (!HAS_PERM(PERM_SYSOP)
#ifdef NSYSUBBS
				    || !strstr(request_rec->fromhost, "140.17.12.")
#endif
					)
				{
					sprintf(WEBBBS_ERROR_MESSAGE,
					"%s 沒有權限修改看板設定", username);
					result = WEB_ERROR;
				}
				else if ((result = ModifyBoard(form_data, board)))
					sprintf(skin_file->filename, "/%sboards/%s/%s",
						BBS_SUBDIR, boardname, HTML_BoardModify);
				break;
#endif

			case SkinModify:	/* customize board skins */
				if (strcmp(username, board->owner) && !HAS_PERM(PERM_SYSOP))
				{
					sprintf(WEBBBS_ERROR_MESSAGE,
						"%s 沒有權限修改討論區介面", username);
					result = WEB_ERROR;
				}
				else if (!(board->brdtype & BRD_WEBSKIN))
				{
					sprintf(WEBBBS_ERROR_MESSAGE,
						"討論區 [%s] 尚未打開自定介面功\能", board->filename);
					result = WEB_ERROR;
				}
				else if ((result = ModifySkin(form_data, board, pf)))
Exemple #11
0
char		game_loop(t_board *board, t_surfaces *surf, char mode)
{
    t_pos		moveIA;
    t_pos		moveHint;
    t_pos		move;
    char		rules;
    char		hint;

    SDL_Rect	pos; // Pour les placements dans la fenêtre
    SDL_Rect	cor; // Pour les placements dans le board

    SDL_Event     event;
    char		current;

    current = BLACK;
    SDL_ShowCursor(0);
    init_board(board);
    rules = RULE3 | RULE5;

    cor.x = 0;
    cor.y = 0;
    hint = 0;

    SDL_WaitEvent(&event);
    printf("New Game\n");
    while (current)
    {
        // Fuite
        if (((event.type == SDL_KEYDOWN) && (event.key.keysym.sym == SDLK_ESCAPE)) ||
                (event.type == SDL_QUIT))
            current = 0;

        // Background
        show_background(surf->background, surf->screen);

        // Click
        if (event.type == SDL_MOUSEBUTTONUP)
        {
            // Mouvements sur le board: position du curseur
            if ((cor.x >= 0) && (cor.x < 19) && (cor.y >= 0) && (cor.y < 19))
            {
                move.x = cor.x;
                move.y = cor.y;
                current = pose(board, &move, current, rules);

                // IA
                if (mode && (current == WHITE))
                {
                    callIA(board, rules, &moveIA, current);
                    current = pose(board, &moveIA, current, rules);
                }

                if (hint)
                    hint = 2;
            }
            // Mouvements en bas du board: sélection des règles
            else if (event.motion.y > 632)
            {
                if (event.motion.x < 160)
                    rules = rules ^ RULE3;
                else if (event.motion.x < 320)
                    rules = rules ^ RULE5;
                else if (event.motion.x < 480)
                {
                    hint = !hint;
                    if (hint)
                        hint++;
                }
                else if (event.motion.x < 640)
                    return (42);
            }

            // Calcul du hint
            if ((hint > 1) && (current < 3))
            {
                callIA(board, rules, &moveHint, current);
                /* printf("Hint at %i:%i\n", moveHint.x, moveHint.y); */
                hint--;
            }
        }

        // Affichage de l'état des règles
        pos.w = 320;
        pos.h = 56;
        pos.y = 630;

        if (rules & RULE3)
        {
            pos.x = 1;
            SDL_BlitSurface(surf->rule3, NULL, surf->screen, &pos);
        }
        if (rules & RULE5)
        {
            pos.x = 161;
            SDL_BlitSurface(surf->rule5, NULL, surf->screen, &pos);
        }
        if (hint)
        {
            pos.x = 320;
            SDL_BlitSurface(surf->hint, NULL, surf->screen, &pos);
        }


        // Affichage du Hint
        if (hint)
        {
            pos.x = moveHint.x * 32 +16;
            pos.y = moveHint.y * 32 +16;
            pos.w = 32;
            pos.h = 32;
            SDL_BlitSurface(surf->cursor, NULL, surf->screen, &pos);
        }

        // Affichage des pions
        place_pawns(board, surf);

        // Move
        if ((event.type == SDL_MOUSEMOTION) || (event.type == SDL_MOUSEBUTTONUP))
        {
            pos.w = 32;
            pos.h = 32;
            pos.x = (event.motion.x / 32) * 32 - 16;
            pos.y = (event.motion.y / 32) * 32 - 16;
            cor.x = event.motion.x / 32 - 1;
            cor.y = event.motion.y / 32 - 1;
            /* printf("x:%i y:%i\n", pos.x / 32, pos.y / 32); */

            if ((cor.x >= 0) && (cor.x < 19) && (cor.y >= 0) && (cor.y < 19))
            {
                if (get_board(board, cor.x, cor.y) == EMPTY)
                {

                    if (!getprise(board, cor.x, cor.y, current) && (rules & RULE3)
                            && (!rule3(board, cor.x, cor.y, current)))
                        SDL_BlitSurface(surf->nopestone, NULL, surf->screen, &pos);
                    else if (current == BLACK)
                    {
                        SDL_BlitSurface(surf->blackstone, NULL, surf->screen, &pos);
                        SDL_BlitSurface(surf->cursor, NULL, surf->screen, &pos);
                    }
                    else
                    {
                        SDL_BlitSurface(surf->whitestone, NULL, surf->screen, &pos);
                        SDL_BlitSurface(surf->cursor, NULL, surf->screen, &pos);
                    }
                }
                else
                    SDL_BlitSurface(surf->nopestone, NULL, surf->screen, &pos);
                SDL_ShowCursor(0);
            }
            else if (event.motion.y > 632)
                SDL_ShowCursor(1);
        }

        SDL_Flip(surf->screen);

        // Victoire par capture
        if (board->whites >= 5)
        {
            printf("Blacks wins with captures!\n");
            current = BLACK + 10;
        }
        if (board->blacks >= 5)
        {
            printf("Whites wins with captures!\n");
            current = WHITE + 10;
        }

        // Quit de victoire
        while (current > 10)
        {
            SDL_ShowCursor(1);
            show_background(surf->exit, surf->screen);
            place_pawns(board, surf);
            SDL_Flip(surf->screen);
            SDL_WaitEvent(&event);
            if (event.type == SDL_MOUSEBUTTONUP)
                return (current - 10);
            if (((event.type == SDL_KEYDOWN) && (event.key.keysym.sym == SDLK_ESCAPE)) ||
                    (event.type == SDL_QUIT))
            {
                current -= 10;
                current = OPPOSITE(current);
                break;
            }
        }

        SDL_WaitEvent(&event);

    }
    return (42);
}
Exemple #12
0
int monitor(int argc, char *argv[])
{
    ty_board *board = NULL;
    int outfd = -1;
    int r;

    int c;
    while ((c = getopt_long(argc, argv, short_options, long_options, NULL)) != -1) {
        switch (c) {
        HANDLE_COMMON_OPTIONS(c, print_monitor_usage);

        case 's':
            terminal_flags |= TY_TERMINAL_SILENT;
            break;
        case 'r':
            terminal_flags |= TY_TERMINAL_RAW;
            break;

        case 'D':
            if (strcmp(optarg, "input") == 0) {
                directions = DIRECTION_INPUT;
            } else if (strcmp(optarg, "output") == 0) {
                directions = DIRECTION_OUTPUT;
            } else if (strcmp(optarg, "both") == 0) {
                directions = DIRECTION_INPUT | DIRECTION_OUTPUT;
            } else {
                ty_log(TY_LOG_ERROR, "--direction must be one off input, output or both");
                print_monitor_usage(stderr);
                return EXIT_FAILURE;
            }
            break;

        case 'b':
            errno = 0;
            device_rate = (uint32_t)strtoul(optarg, NULL, 10);
            if (errno) {
                ty_log(TY_LOG_ERROR, "--baud requires a number");
                print_monitor_usage(stderr);
                return EXIT_FAILURE;
            }
            break;
        case 'd':
           device_flags &= ~HS_SERIAL_MASK_CSIZE;
            if (strcmp(optarg, "5") == 0) {
                device_flags |= HS_SERIAL_CSIZE_5BITS;
            } else if (strcmp(optarg, "6") == 0) {
                device_flags |= HS_SERIAL_CSIZE_6BITS;
            } else if (strcmp(optarg, "7") == 0) {
                device_flags |= HS_SERIAL_CSIZE_7BITS;
            } else if (strcmp(optarg, "8") != 0) {
                ty_log(TY_LOG_ERROR, "--databits must be one off 5, 6, 7 or 8");
                print_monitor_usage(stderr);
                return EXIT_FAILURE;
            }
        case 'f':
            device_flags &= ~HS_SERIAL_MASK_FLOW;
            if (strcmp(optarg, "x") == 0 || strcmp(optarg, "xonxoff") == 0) {
                device_flags |= HS_SERIAL_FLOW_XONXOFF;
            } else if (strcmp(optarg, "h") == 0 || strcmp(optarg, "rtscts") == 0) {
                device_flags |= HS_SERIAL_FLOW_RTSCTS;
            } else if (strcmp(optarg, "n") != 0 && strcmp(optarg, "none") == 0) {
                ty_log(TY_LOG_ERROR, "--flow must be one off x (xonxoff), h (rtscts) or n (none)");
                print_monitor_usage(stderr);
                return EXIT_FAILURE;
            }
            break;
        case MONITOR_OPTION_NORESET:
            device_flags |= HS_SERIAL_CLOSE_NOHUP;
            break;
        case 'p':
            device_flags &= ~HS_SERIAL_MASK_PARITY;
            if (strcmp(optarg, "o") == 0 || strcmp(optarg, "odd") == 0) {
                device_flags |= HS_SERIAL_PARITY_ODD;
            } else if (strcmp(optarg, "e") == 0 || strcmp(optarg, "even") == 0) {
                device_flags |= HS_SERIAL_PARITY_EVEN;
            } else if (strcmp(optarg, "n") != 0 && strcmp(optarg, "none") != 0) {
                ty_log(TY_LOG_ERROR, "--parity must be one off o (odd), e (even) or n (none)");
                print_monitor_usage(stderr);
                return EXIT_FAILURE;
            }
            break;

        case 'R':
            reconnect = true;
            break;

        case MONITOR_OPTION_TIMEOUT_EOF:
            errno = 0;
            timeout_eof = (int)strtol(optarg, NULL, 10);
            if (errno) {
                ty_log(TY_LOG_ERROR, "--timeout requires a number");
                print_monitor_usage(stderr);
                return EXIT_FAILURE;
            }
            if (timeout_eof < 0)
                timeout_eof = -1;
            break;
        }
    }

    if (argc > optind) {
        ty_log(TY_LOG_ERROR, "No positional argument is allowed");
        print_monitor_usage(stderr);
        return EXIT_FAILURE;
    }

    if (ty_standard_get_modes(TY_STANDARD_INPUT) & TY_DESCRIPTOR_MODE_TERMINAL) {
#ifdef _WIN32
        if (terminal_flags & TY_TERMINAL_RAW && !(terminal_flags & TY_TERMINAL_SILENT)) {
            terminal_flags |= TY_TERMINAL_SILENT;

            if (ty_standard_get_modes(TY_STANDARD_OUTPUT) & TY_DESCRIPTOR_MODE_TERMINAL)
                fake_echo = true;
        }

        /* Unlike POSIX platforms, Windows does not implement the console line editing behavior
         * at the tty layer. Instead, ReadFile() takes care of it and blocks until return is hit.
         * The problem is that the Wait functions will return the stdin descriptor as soon as
         * something is typed but then, ReadFile() will block until return is pressed.
         * Overlapped I/O cannot be used because it is not supported on console descriptors.
         *
         * So the best way I found is to have a background thread handle the blocking ReadFile()
         * and pass the lines in a buffer. When a new line is entered, the input_available
         * event is set to signal the poll in loop(). I also tried to use an anonymous pipe to
         * make it simpler, but the Wait functions do not support them. */
        if (directions & DIRECTION_OUTPUT && !(terminal_flags & TY_TERMINAL_RAW)) {
            r = start_stdin_thread();
            if (r < 0)
                goto cleanup;
        }
#endif

        r = ty_terminal_setup(terminal_flags);
        if (r < 0)
            goto cleanup;
    }

    r = redirect_stdout(&outfd);
    if (r < 0)
        goto cleanup;

    r = get_board(&board);
    if (r < 0)
        goto cleanup;

    r = loop(board, outfd);

cleanup:
#ifdef _WIN32
    stop_stdin_thread();
#endif
    ty_board_unref(board);
    return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
}
Exemple #13
0
/*******************************************************************
 *	根據 URLParaType 執行 GET 的要求
 *
 *	
 *	return WebRespondType
 *******************************************************************/
int 
DoGetRequest(REQUEST_REC * rc, BOARDHEADER * board, POST_FILE * pf)
{
	char *p, *boardname;
	int URLParaType = rc->URLParaType;
	char fname[PATHLEN];

	boardname = board->filename;

	if (URLParaType == Redirect)
	{
		/* redirect target must set in ParseURI() */
		return WEB_REDIRECT;
	}

	if (PSCorrect != Correct
	    && (URLParaType == MailList
		|| URLParaType == MailRead
		|| URLParaType == SkinModify))
	{
		return WEB_USER_NOT_LOGIN;
	}

	if (URLParaType == PostList
	    || URLParaType == PostRead
	    || URLParaType == TreaList
	    || URLParaType == TreaRead
	    || URLParaType == SkinModify
	    || URLParaType == Board)
	{
		int perm;

		if (get_board(board, boardname) <= 0 || board->filename[0] == '\0')
			return WEB_BOARD_NOT_FOUND;

		if ((perm = CheckBoardPerm(board, &curuser)) != WEB_OK)
			return perm;

		if (board->brdtype & BRD_WEBSKIN)	/* Board has custom html skin */
		{
			char *skin, web_board_dir[PATHLEN];

			if (URLParaType == SkinModify)
			{
				if (strlen(pf->POST_NAME) != 0)
				{
					xstrncpy(web_board_dir, pf->POST_NAME, PATHLEN);
					skin = strrchr(web_board_dir, '/') + 1;
					setskinfile(pf->POST_NAME, boardname, skin);
				}
			}
			else if (!strstr(skin_file->filename, HTML_BoardModify))
			{
				/* set specfic skin file to custom file */
				xstrncpy(web_board_dir, skin_file->filename, PATHLEN);
				skin = strrchr(web_board_dir, '/') + 1;
				setskinfile(skin_file->filename, boardname, skin);
			}
		}
		else
		{
			if (strstr(skin_file->filename, HTML_SkinModify))
				return WEB_FILE_NOT_FOUND;
		}
	}

	if (strstr(skin_file->filename, HTML_BoardModify)
	    && (!HAS_PERM(PERM_SYSOP) || PSCorrect != Correct))
	{
		return WEB_FILE_NOT_FOUND;
	}

	switch (URLParaType)
	{
		case TreaRead:
		case PostRead:
			if (GetPostInfo(board, pf) != WEB_OK)
				return WEB_FILE_NOT_FOUND;

			break;

		case TreaList:
		case PostList:
			pf->total_rec = get_num_records(pf->POST_NAME, FH_SIZE);

			break;

		case MailList:
			if (PSCorrect == Correct)
				pf->total_rec = get_num_records(pf->POST_NAME, FH_SIZE);
			else
				pf->total_rec = 0;
			break;

		case MailRead:
			if (PSCorrect == Correct)
			{
				int RESULT = GetPostInfo(board, pf);

				if (RESULT != WEB_OK)
					return RESULT;
			}
			break;

		case UserList:
		case BoardList:
		case TreaBoardList:
		case UserData:
		case SkinModify:
			/* do nothing here.. */

			break;

		case UserQuery:
			/* put USER_REC in curuser for query */
			if (!get_passwd(&curuser, username))
			{
				bzero(&curuser, sizeof(USEREC));
				return WEB_USER_NOT_FOUND;
			}
			break;

		case Board:	/* cuscom webboard */
		case Mail:	/* ?? */
#if 0
			fprintf(fp_out, "DoGetRequest Board,Mail:[%s]", skin_file->filename);
			fflush(fp_out);
#endif
			if (CacheState(skin_file->filename, NULL) < 0
			    && !isfile(skin_file->filename))
			{
				return WEB_FILE_NOT_FOUND;
			}
			break;

		default:
#if 0
			fprintf(fp_out, "DoGetRequest default:[%s]\r\n", skin_file->filename);
			fflush(fp_out);
#endif

			xstrncpy(fname, skin_file->filename, sizeof(fname));

			if (isBadURI(fname))
			{
				BBS_SUBDIR[0] = 0x00;
				return WEB_BAD_REQUEST;
			}

			sprintf(skin_file->filename, "%s%s", HTML_PATH, fname + 1);

			if (CacheState(skin_file->filename, NULL) == -1)	/* file not in cache */
			{
				if (isdir(skin_file->filename))
				{
					p = skin_file->filename + strlen(skin_file->filename) - 1;
					if (*p == '/')
					{
						strcat(skin_file->filename, DEFAULT_HTML);
					}
					else
					{
						sprintf(skin_file->filename, "%s/", fname);
						return WEB_REDIRECT;
					}
				}
				else
				{
					if ((p = strrchr(fname + 1, '/')) == NULL)
						p = fname;
					if (!strcmp(p, "/boards")
					    || !strcmp(p, "/treasure")
					    || !strcmp(p, "/mail")
					    || !strcmp(p, "/users"))
					{
						sprintf(skin_file->filename, "%s/", fname);
						return WEB_REDIRECT;
					}
				}

				if (!isfile(skin_file->filename))
				{
					BBS_SUBDIR[0] = 0x00;
					return WEB_FILE_NOT_FOUND;
				}
			}

#ifdef WEB_LOGIN_CHECK
			return WebLoginCheck();
#endif

	}

	return WEB_OK;

}
Exemple #14
0
int get_move()
{
    int retval = -1;
    int mousex, mousey;
    static Sint16 rotx, roty;
    SDL_Event event;
    Uint8 *keystate = SDL_GetKeyState(NULL);
    Uint8 mousestate = SDL_GetMouseState(&mousex, &mousey);

    if( mousestate & SDL_BUTTON_MIDDLE )
    {
        move_camera( -(mousey-last_mousey)*MOUSE_CAM_SPEED, -(mousex-last_mousex)*MOUSE_CAM_SPEED);
        last_mousex=mousex;
        last_mousey=mousey;
    }
    else
    {
        last_mousex=mousex;
        last_mousey=mousey;
    }

    if (keystate[SDLK_LCTRL])
    {
        if (keystate[SDLK_DOWN])
            move_camera(-KEYBOARD_CAM_SPEED, 0.0f);
        if (keystate[SDLK_LEFT])
            move_camera(0.0f, -KEYBOARD_CAM_SPEED);
        if (keystate[SDLK_RIGHT])
            move_camera(0.0f, KEYBOARD_CAM_SPEED);
        if (keystate[SDLK_UP])
            move_camera(KEYBOARD_CAM_SPEED, 0.0f);

        while (SDL_PollEvent( &event ))
            if (event.type == SDL_QUIT)
                /* FIXME */
                exit(0);
    }

    if ((roty < -3000) || (roty > 3000))
        move_camera(-roty / (float) 32768 * KEYBOARD_CAM_SPEED, 0.0f);

    if ((rotx < -3000) || (rotx > 3000))
        move_camera(0.0f, -rotx / (float) 32768 * KEYBOARD_CAM_SPEED);

    while ( SDL_PollEvent( &event ) )
    {
        gg_event_t gg_event;

        if (event.type == SDL_QUIT)
            /* FIXME */
            exit(0);

        if (event.type == SDL_MOUSEMOTION)
            set_mouse_pos( event.motion.x, event.motion.y );

        if (!gg_dialog_get_active() && event.type == SDL_MOUSEBUTTONDOWN &&
                event.button.button == SDL_BUTTON_LEFT)
        {
            retval = get_mouse_square();
            if (retval != -1)
                select_piece(retval);

            continue;
        }

        if (!gg_dialog_get_active() && event.type == SDL_MOUSEBUTTONDOWN &&
                event.button.button == SDL_BUTTON_RIGHT)
        {
            gg_dialog_open(dialog_system_create());

            continue;
        }

        if ((event.type == SDL_JOYAXISMOTION) && (event.jaxis.axis == AXIS_VIEW_X))
        {
            rotx = event.jaxis.value;
            continue;
        }

        if ((event.type == SDL_JOYAXISMOTION) && (event.jaxis.axis == AXIS_VIEW_Y))
        {
            roty = event.jaxis.value;
            continue;
        }

        if ( (event.type == SDL_KEYDOWN && event.key.keysym.mod & KMOD_ALT &&
            event.key.keysym.sym == SDLK_RETURN) || (event.type == SDL_KEYDOWN &&
            event.key.keysym.sym == SDLK_F11) )
        {
            DBG_LOG( "toggled fullscreen" );
            toggle_fullscreen();
            continue;
        }

        gg_event = convert_event(&event);

        if (gg_event.type == GG_EVENT_NONE)
            continue;

        if (gg_dialog_get_active())
            gg_dialog_input_current(gg_event);

        /* In the promote dialog */
        else if (gg_event.type == GG_EVENT_KEY)
            switch (gg_event.key)
            {
            case GG_KEY_LEFT:
                move_selector(SELECTOR_LEFT);
                break;
            case GG_KEY_RIGHT:
                move_selector(SELECTOR_RIGHT);
                break;
            case GG_KEY_UP:
                move_selector(SELECTOR_UP);
                break;
            case GG_KEY_DOWN:
                move_selector(SELECTOR_DOWN);
                break;
            case GG_KEY_ACTION:
                retval = get_selector();
                select_piece(retval);
                break;
            case GG_KEY_ESCAPE:
                gg_dialog_open(dialog_system_create());
                break;
            case 'g':
            case GG_KEY_EXTRA3:
                /* gg_dialog_open(dialog_ingame_create()); */
                break;
            case 'p':
                game_view_prev();
                break;
            case 'n':
                game_view_next();
                break;
            case 'u':
                game_undo();
                break;
            case 's':
                fen_encode(get_board());
                /* game_save(); */
                break;
            case 'l':
                /* load_game(); */
                break;
            default:
                break;
            }
    }
    return retval;
}
 // send a mavlink message to the comm port
 void sendMessage(const mavlink_message_t & msg) {
     uint8_t buf[MAVLINK_MAX_PACKET_LEN];
     uint16_t len = mavlink_msg_to_send_buffer(buf, &msg);
     get_board()->get_serial()->write((const char *)buf, len);
 }
Exemple #16
0
int bbs0an_main(void)
{
	char path[512];
	board_t board;
	int bid = strtol(web_get_param("bid"), NULL, 10);
	if (bid <= 0) {
		strlcpy(path, web_get_param("path"), sizeof(path));
		if (strstr(path, "..") || strstr(path, "SYSHome"))
			return BBS_EINVAL;
		char *bname = getbfroma(path);
		if (*bname != '\0') {
			if (!get_board(bname, &board) || !has_read_perm(&board))
				return BBS_ENODIR;
		}
	} else {
		if (!get_board_by_bid(bid, &board) || !has_read_perm(&board))
			return BBS_ENOBRD;
		if (board.flag & BOARD_FLAG_DIR)
			return BBS_EINVAL;

		path[0] = '\0';
		FILE *fp = fopen("0Announce/.Search", "r");
		if (fp == NULL)
			return BBS_EINTNL;
		char tmp[256];
		int len = strlen(board.name);
		while (fgets(tmp, sizeof(tmp), fp) != NULL) {
			if (!strncmp(tmp, board.name, len) && tmp[len] == ':'
					&& tmp[len + 1] == ' ') {
				tmp[len + 1] = '/';
				strlcpy(path, tmp + len + 1, sizeof(path));
				path[strlen(path) - 1] = '\0';
				break;
			}
		}
		fclose(fp);
		if (path[0] == '\0')
			return BBS_ENODIR;
	}
	char names[512];
	snprintf(names, sizeof(names), "0Announce%s/.Names", path);
	FILE *fp = fopen(names, "r");
	if (fp == NULL)
		return BBS_ENODIR; // not indicating hidden directories.
	char buf[512], *title;
	// check directory permission.
	while (true) {
		if (fgets(buf, sizeof(buf), fp) == NULL) {
			fclose(fp);
			return BBS_ENODIR;
		}
		if(!strncmp(buf, "# Title=", 8)) {
			title = buf + 8;
			if (!hasannperm(title, &currentuser, &board)) {
				fclose(fp);
				return BBS_ENODIR;
			}
			break;
		}
	}

	xml_header(NULL);
	printf("<bbs0an path='%s' v='%d' ", path, 1030);
	if (board.id)
		printf(" brd='%s'", board.name);
	printf(">");
	print_session();
	
	char name[STRLEN], fpath[1024], *id = NULL, *ptr;
	struct stat st;
	while (fgets(buf, sizeof(buf), fp) != NULL) {
		if (!strncmp(buf, "Name=", 5)) {
			strlcpy(name, trim(buf + 5), sizeof(name));
			if (strlen(name) > ANN_TITLE_LENGTH) {
				id = name + ANN_TITLE_LENGTH;
				if (!hasannperm(name + ANN_TITLE_LENGTH, &currentuser, &board))
					continue;
				name[ANN_TITLE_LENGTH -  1] = '\0';
				if (!strncmp(id, "BM: ", 4))
					id += 4;
				if ((ptr = strchr(id, ')')) != NULL)
					*ptr = '\0';
			} else {
				id = NULL;
			}
			if (fgets(buf, sizeof(buf), fp) == NULL || strncmp(buf, "Path=~", 6)) {
				break;
			} else {
				printf("<ent path='%s' t='", trim(buf + 6));
				snprintf(fpath, sizeof(fpath), "0Announce%s%s", path, buf + 6);
				if (stat(fpath, &st) != 0 || (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))) {
					printf("e'");
				} else if (S_ISREG(st.st_mode)) {
					printf("f'");
				} else {
					printf("d'");
				}
				if (id != NULL)
					printf(" id='%s'", id);
				printf(" time='%s'>", format_time(st.st_mtime, TIME_FORMAT_XML));
				xml_fputs4(trim(name), 0);
				printf("</ent>");
			}
		}
	}
	fclose(fp);
	puts("</bbs0an>");
	return 0;
}
Exemple #17
0
int web_sector(void)
{
	int sid = 0;
	board_t parent = { .id = 0 };
	db_res_t *res = NULL;

	const char *sname = web_get_param("s");
	if (*sname) {
		res = db_query("SELECT id, descr"
				" FROM board_sectors WHERE name = %s", sname);
		if (!res || db_res_rows(res) < 1) {
			db_clear(res);
			return BBS_EINVAL;
		}
	} else {
		const char *pname = web_get_param("board");
		if (*pname)
			get_board(pname, &parent);
		else
			get_board_by_bid(strtol(web_get_param("bid"), NULL, 10), &parent);
		if (!parent.id || !(parent.flag & BOARD_FLAG_DIR)
				|| !has_read_perm(&parent))
			return BBS_ENOBRD;
	}

	xml_header(NULL);
	printf("<bbsboa link='%sdoc' ", get_post_list_type_string());

	if (*sname) {
		char path[HOMELEN];
		sprintf(path, "%s/info/egroup%d/icon.jpg", BBSHOME,
				(int) strtol(sname, NULL, 16));
		if (dashf(path))
			printf(" icon='%s'", path);
		
		const char *utf8_sector = db_get_value(res, 0, 1);
		if (web_request_type(UTF8)) {
			printf(" title='%s'>", utf8_sector);
		} else {
			GBK_BUFFER(sector, BOARD_SECTOR_NAME_CCHARS);
			convert_u2g(utf8_sector, gbk_sector);
			printf(" title='%s'>", gbk_sector);
		}
		sid = db_get_integer(res, 0, 0);
		db_clear(res);
	} else {
		if (web_request_type(UTF8)) {
			printf(" dir= '1' title='%s'>", parent.descr);
		} else {
			GBK_BUFFER(descr, BOARD_DESCR_CCHARS);
			convert_u2g(parent.descr, gbk_descr);
			printf(" dir= '1' title='%s'>", gbk_descr);
		}
	}

	if (sid)
		res = db_query(BOARD_SELECT_QUERY_BASE "WHERE b.sector = %d", sid);
	else
		res = db_query(BOARD_SELECT_QUERY_BASE "WHERE b.parent = %d", parent.id);

	if (res && db_res_rows(res) > 0)
		show_board(res);
	db_clear(res);

	print_session();
	printf("</bbsboa>");
	return 0;
}

int bbsclear_main(void)
{
	if (!session_id())
		return BBS_ELGNREQ;

	board_t board;
	if (!get_board(web_get_param("board"), &board)
			|| !has_read_perm(&board))
		return BBS_ENOBRD;
	session_set_board(board.id);

	const char *start = web_get_param("start");
	brc_init(currentuser.userid, board.name);
	brc_clear_all();
	brc_sync(currentuser.userid);
	char buf[STRLEN];
	snprintf(buf, sizeof(buf), "doc?board=%s&start=%s", board.name, start);
	http_header();
	refreshto(0, buf);
	printf("</head></html>");
	return 0;
}

int bbsnot_main(void)
{
	board_t board;
	if (!get_board(web_get_param("board"), &board)
			|| !has_read_perm(&board))
		return BBS_ENOBRD;

	if (board.flag & BOARD_FLAG_DIR)
		return BBS_EINVAL;
	session_set_board(board.id);

	char fname[HOMELEN];
	snprintf(fname, sizeof(fname), "vote/%s/notes", board.name);
	mmap_t m;
	m.oflag = O_RDONLY;
	if (mmap_open(fname, &m) < 0)
		return BBS_ENOFILE;
	xml_header(NULL);
	printf("<bbsnot brd='%s'>", board.name);
	xml_fputs2((char *) m.ptr, m.size);
	mmap_close(&m);
	print_session();
	printf("</bbsnot>");
	return 0;
}
Exemple #18
0
/* Play at (i, j) for color. No legality check is done here. We need
 * to properly update the board array, the next_stone array, and the
 * ko point.
 */
static void
play_move(int i, int j, int color)
{
  int pos = POS(i, j);
  int captured_stones = 0;
  int k;

  /* Reset the ko point. */
  ko_i = -1;
  ko_j = -1;

  /* Nothing more happens if the move was a pass. */
  if (pass_move(i, j))
    return;

  /* If the move is a suicide we only need to remove the adjacent
   * friendly stones.
   */
  if (suicide(i, j, color)) {
    for (k = 0; k < 4; k++) {
      int ai = i + deltai[k];
      int aj = j + deltaj[k];
      if (on_board(ai, aj)
	  && get_board(ai, aj) == color)
	remove_string(ai, aj);
    }
    return;
  }

  /* Not suicide. Remove captured opponent strings. */
  for (k = 0; k < 4; k++) {
    int ai = i + deltai[k];
    int aj = j + deltaj[k];
    if (on_board(ai, aj)
	&& get_board(ai, aj) == OTHER_COLOR(color)
	&& !has_additional_liberty(ai, aj, i, j))
      captured_stones += remove_string(ai, aj);
  }

  /* Put down the new stone. Initially build a single stone string by
   * setting next_stone[pos] pointing to itself.
   */
  board[pos] = color;
  next_stone[pos] = pos;

  /* If we have friendly neighbor strings we need to link the strings
   * together.
   */
  for (k = 0; k < 4; k++) {
    int ai = i + deltai[k];
    int aj = j + deltaj[k];
    int pos2 = POS(ai, aj);
    /* Make sure that the stones are not already linked together. This
     * may happen if the same string neighbors the new stone in more
     * than one direction.
     */
    if (on_board(ai, aj) && board[pos2] == color && !same_string(pos, pos2)) {
      /* The strings are linked together simply by swapping the the
       * next_stone pointers.
       */
      int tmp = next_stone[pos2];
      next_stone[pos2] = next_stone[pos];
      next_stone[pos] = tmp;
    }
  }

  /* If we have captured exactly one stone and the new string is a
   * single stone it may have been a ko capture.
   */
  if (captured_stones == 1 && next_stone[pos] == pos) {
    int ai, aj;
    /* Check whether the new string has exactly one liberty. If so it
     * would be an illegal ko capture to play there immediately. We
     * know that there must be a liberty immediately adjacent to the
     * new stone since we captured one stone.
     */
    for (k = 0; k < 4; k++) {
      ai = i + deltai[k];
      aj = j + deltaj[k];
      if (on_board(ai, aj) && get_board(ai, aj) == EMPTY)
	break;
    }
    
    if (!has_additional_liberty(i, j, ai, aj)) {
      ko_i = ai;
      ko_j = aj;
    }
  }
}