Example #1
0
int
board_load (window_board_t *win, char *fname)
{
	FILE *f;
	char buf[1024];
	if (! (f = fopen (fname, "r")))
		return 0;
	if (fgets (buf, 1023, f) == NULL)
		return 0;

	int ret;
	if (!strncmp(buf, "pn|", 3) || !strncmp(buf, "vg|", 3) ||
	    !strncmp(buf, "st|", 3) || !strncmp(buf, "qx|", 3)) {
		ret = board_parse_lin (win, buf, f);
	} else {
		board *b = board_new (win->n_boards + 1);
		ret = board_parse_line(buf, b, ' ', '.');
		if (ret)
			board_window_append_board (win, b);
		else {
			errno = EMEDIUMTYPE;
			board_free (b);
		}
	}
	int e = errno;
	fclose(f);
	if (ret) {
		if (win->filename)
			free (win->filename);
		win->filename = strdup (fname);
	}
	errno = e;
	return ret;
}
Example #2
0
void board_hash_table_free(board_hash_table_t *table)
{
    uint32_t i;

    if(table == NULL)
        return;

    for(i = 0; i < table->size; i++) {
        board_list_t *cur, *next;

        cur = table->data[i];
        if(cur == NULL)
            break;

        for(next = cur->next;
            cur != NULL;
            cur = next, next = next->next)
        {
            board_free(cur->item);
            free(cur);
        }
    }

    free(table->data);
    free(table);
}
Example #3
0
board_t *board_hash_table_insert(board_hash_table_t *table,
                                 board_t *board)
{
    board_t *board_new;
    board_list_t *list = NULL, *list_new;
    uint32_t index;
    uint64_t hash, hash2;

    if(table == NULL || board == NULL)
        return NULL;

    if(table->used >= ((table->size * 3) / 4)) {
        board_hash_table_expand(table, table->size * 2);
    }

    hash = board_hash(board, &hash2);
    index = hash & (table->size - 1);

    list = table->data[index];
    if(list != NULL) {

        for(;;) {
            if(list->hash == hash && list->hash2 == hash2
               && board_compare(list->item, board))
            {
                return list->item;
            }

            if(list->next == NULL)
                break;

            list = list->next;
        }
    }

    board_new = board_clone(board);
    if(board_new == NULL)
        return NULL;

    list_new = malloc(sizeof(*list_new));
    if(list_new == NULL) {
        board_free(board_new);
        return NULL;
    }

    list_new->item = board_new;
    list_new->hash = hash;
    list_new->hash2 = hash2;
    list_new->next = NULL;

    if(list != NULL)
        list->next = list_new;
    else
        table->data[index] = list_new;

    table->used++;

    return NULL;
}
Example #4
0
int uct_play_random_game(Board * board, Color color) {
    Color winner;
    Board * clone = board_clone(board);
    playout_random_game(clone, color);
    winner = playout_find_winner(clone);
    board_free(clone);
    return winner == color;
}
Example #5
0
int main(int argc, char **argv) {
	if (argc < 3) {
		printf("Usage: ./gol <infile> <print>\n");
		return 0;
	}

	FILE *f = fopen(argv[1], "r");
	int to_print = strtol(argv[2], NULL, 10);

	// Check if we opened the file
	if (f != NULL) { 
		int num_rows = 0;
		int num_cols = 0;
		int num_iterations = 0;
		int num_pairs = 0;
		double total_time = 0.0;
		
		// read numbers
		fscanf(f, "%d\n%d\n%d\n%d", &num_rows, &num_cols, &num_iterations, &num_pairs);

		// set up board
		board_t *board = init_board(f, num_rows, num_cols, num_pairs);

		// set up timing
		struct timeval start_time;
		struct timeval end_time;
		gettimeofday(&start_time, NULL);

		// run iterations
		int i = num_iterations;
		while (board_next(board, &i)) {
			if (to_print) {
				print_board(board, num_iterations - i);
				usleep(200000);
				clear(num_rows + 4);
			}
			i--;
		}

		// get end time
		gettimeofday(&end_time, NULL);
		total_time = ((end_time.tv_sec + (end_time.tv_usec/1000000.0)) - (start_time.tv_sec + (start_time.tv_usec/1000000.0)));

		// print final board
		print_board(board, num_iterations);

		printf("total time for %d iteration%s of %dx%d world is %f sec\n", num_iterations, (num_iterations != 1) ? "s" : "", num_rows, num_cols, total_time);
		fclose(f);
		board_free(board);
	} else {
		printf("There was an error opening '%s'\n", argv[1]);
		return 1;
	}

	return 0;
}
Example #6
0
/* tries opening a file in a temporary win structure, and displays errors if unable */
int
board_load_popup (window_board_t *win, int append, char *filename)
{
	int i;
	int ret = 0;
	window_board_t *win1 = calloc (1, sizeof (window_board_t));

	if (board_load (win1, filename)) {
		if (append) {
			int n = win->n_boards;
			for (i = 0; i < win1->n_boards; i++)
				board_window_append_board (win, win1->boards[i]);
			if (win->n_boards > n) /* set to first new board */
				win->cur = n;
		} else {
			MOVE_PTR (win->filename, win1->filename);
			MOVE_PTR (win->title, win1->title);
			MOVE_PTR (win->subtitle, win1->subtitle);
			MOVE_PTR (win->team1, win1->team1);
			MOVE_PTR (win->team2, win1->team2);

			for (i = 0; i < win->n_boards; i++)
				if (win->boards[i])
					board_free (win->boards[i]);
			win->boards = win1->boards;
			win->n_boards = win1->n_boards;
			win->n_boards_alloc = win1->n_boards_alloc;
			win->cur = 0;
		}

		card_window_update(win->boards[win->cur]->dealt_cards);
		show_board(win->boards[win->cur], REDRAW_FULL);
		recently_used_add (filename);

		ret = 1;
	} else {
		GtkWidget *error = gtk_message_dialog_new (GTK_WINDOW (win->window),
				GTK_DIALOG_DESTROY_WITH_PARENT,
				GTK_MESSAGE_ERROR,
				GTK_BUTTONS_CLOSE,
				_("Error loading file '%s': %s"),
				filename, g_strerror (errno));
		gtk_dialog_run (GTK_DIALOG (error));
		gtk_widget_destroy (error);
	}

	TRY_FREE (win1->filename);
	TRY_FREE (win1->title);
	TRY_FREE (win1->subtitle);
	TRY_FREE (win1->team1);
	TRY_FREE (win1->team2);
	free (win1);

	return ret;
}
Example #7
0
Pos uct_search(Board * board, Color color) {
    int i;
    UCTNode * root, * ptr;
    Board * clone;
    Pos best_move;

    root = uct_node_new(nil);
    create_children(root, board, color);

    LOOP(i, UCT_SIMULATIONS) {
        clone = board_clone(board);
        uct_simulate(root, clone, color);
        //board_print(clone, stdout);
        board_free(clone);
    }
AIMoves *ai_threats(const Board *original)
{
        AIMoves *moves;
        AIWEIGHT u_sum = 0;
        int i;

        b = board_new();
        board_copy(original, b);

        /* Clear threat tallys */
        for (i = 0; i < connect_k; i++) {
                threat_counts[i][0] = 0;
                threat_counts[i][1] = 0;
        }

        /* Horizontal lines */
        for (i = 0; i < board_size; i++)
                u_sum += threat_line(0, i, 1, 0);

        /* Vertical lines */
        for (i = 0; i < board_size; i++)
                u_sum += threat_line(i, 0, 0, 1);

        /* SE diagonals */
        for (i = 0; i < board_size - connect_k + 1; i++)
                u_sum += threat_line(i, 0, 1, 1);
        for (i = 1; i < board_size - connect_k + 1; i++)
                u_sum += threat_line(0, i, 1, 1);

        /* SW diagonals */
        for (i = connect_k - 1; i < board_size; i++)
                u_sum += threat_line(i, 0, -1, 1);
        for (i = 1; i < board_size - connect_k + 1; i++)
                u_sum += threat_line(board_size - 1, i, -1, 1);

        moves = ai_marks(b, PIECE_THREAT(1));
        moves->utility = u_sum;
        board_free(b);
        return moves;
}
Example #9
0
File: ui.c Project: barak/gtkboard
void ui_terminate_game ()
{
	// FIXME: are we sure -1 is an invalid value?
	if (animate_tag >= 0)
	{
		gtk_timeout_remove (animate_tag);
		animate_tag = -1;
	}
	if (game_single_player)
		prefs_save_scores (menu_get_game_name_with_level());
	board_free ();
	reset_game_params ();
	if (opt_infile)
	{
		fclose (opt_infile);
		opt_infile = NULL;
	}
	if (game_reset_uistate) game_reset_uistate();
	sb_reset_human_time ();
	sb_update();
	ui_stopped = TRUE;
	ui_cheated = FALSE;
}
Example #10
0
/*
static char
game (char **board)
{
  int round, i, j, l, ref;
  char buffer[BUFFER_SIZE];
  for (round = 0; round < (m * n); round++)
    {
      i = 0;
      system ("clear");
      printf ("Number of stone to align to win (k) = %d\n\n", k);
      board_print (board);
      do
	{
	  printf ("\nPlayer '%c' give your move 'line column' (eg: 1 2),"
		  " press 'Q' to quit:\n ",
		  (round % 2 == 0 ? PLAYER1 : PLAYER2));
	  fgets (buffer, BUFFER_SIZE, stdin);
	  clean (buffer);
	  char *clean = strtok (buffer, ",. - ");
	  while (clean != NULL)
	    {
	      if (isdigit (clean[0]))
		{
		  if (l == 0)
		    i = str2index (clean);
		  else if (l == 0)
		    j = str2index (clean);
		  else
		    printf (" Too much argument \n"
			    "The first two parameters will be used\n");
		  l++;
		}
	      if (isalpha (clean[0]))
		if (clean[0] == 'q' || clean[0] == 'Q')
		  return (EXIT_SUCCESS);
	      clean = strtok (NULL, " ,.-");
	    }
	  if (next >= 2)
	    ref =
	      board_set ((round % 2 == 0 ? PLAYER1 : PLAYER2), i, j, board);
	  else
	    printf ("Not enought argument. Try again please.\n");
	}
      while ((ctrl != 0) || (next < 2));
      if (is_winner (board) != NONE)
	return (is_winner (board));
    }
  return NONE;
}
*/
int
main (int argc, char **argv)
{
  int optc;
  static struct option long_opts[] = {
    /* These options do not set a flag.
       We distinguish them by their indices. */
    {"verbose", no_argument, NULL, 'v'},
    {"set-m", required_argument, NULL, 'm'},
    {"set-n", required_argument, NULL, 'n'},
    {"set-k", required_argument, NULL, 'k'},
    {"all-ai", no_argument, NULL, '0'},
    {"player1-ai", no_argument, NULL, '1'},
    {"player2-ai", no_argument, NULL, '2'},
    {"contest", required_argument, NULL, 'c'},
    {"version", no_argument, NULL, 'V'},
    {"help", no_argument, NULL, 'h'},
    {NULL, 0, NULL, 0},
  };

  while ((optc =
	  getopt_long (argc, argv, "m:n:k:012c:vVh", long_opts, NULL)) != -1)
    {

      switch (optc)
	{
	case 'm':
	case 'n':
	case 'k':
	  check_and_set (optc, atoi (optarg));
	  break;

	case '0':
	  printf ("set both players to be an AI\n");
	  break;

	case '1':
	  printf ("set first player as an AI\n");
	  break;

	case '2':
	  printf ("set second player as an AI\n");
	  break;

	case 'c':
	  printf ("enable 'contest mode'\n");
	  break;

	case 'v':
	  verbose = true;
	  break;

	case 'V':
	  version ();
	  break;

	case 'h':
	  usage (EXIT_SUCCESS);
	  break;

	default:
	  usage (EXIT_FAILURE);
	}
    }
  board = board_alloc ();
  //char bo = game(board);
  board_free (board);
  return (EXIT_SUCCESS);
}
Example #11
0
File: main.c Project: clinew/2048
int main(int argc, char* argv[]) {
	struct arguments arguments;
	struct board board;
	char buffer[256];
	int format;
	char input;
	char* message;
	int status; // Game status.
	struct termios term_settings;
	int valid;

	// Parse arguments.
	message = arguments_parse(&arguments, argc, argv);
	if (message) {
		usage_print(message);
	}

	// Apply arguments.
	valid = 1; // Hack; overload to determine whether to play or quit.
	if (arguments.flags & ARGUMENTS_VERSION) {
		printf("%s\n", VERSION);
		valid = 0;
	}
	if (arguments.flags & ARGUMENTS_LEGAL) {
		printf("%s\n", legal);
		valid = 0;
	}
	if (arguments.flags & ARGUMENTS_HELP) {
		usage_print(NULL);
	}
	if (!valid) {
		exit(EXIT_SUCCESS);
	}
	if (arguments.flags & ARGUMENTS_MODE) {
		if (arguments.mode == mode_format) {
			setup_signal_handlers();
			enter_alternate_buffer();
			enter_format_mode(&term_settings);
			format = 1;
		} else if (arguments.mode == mode_plain) {
			format = 0;
		}
	} else if (isatty(STDOUT_FILENO) && isatty(STDIN_FILENO)) {
		setup_signal_handlers();
		enter_alternate_buffer();
		enter_format_mode(&term_settings);
		format = 1;
	}
	if (arguments.flags & ARGUMENTS_SEED) {
		srand(arguments.seed);
	} else {
		srand(time(NULL));
	}

	// Set up the board.
	board_init(&board);
	if (!format) {
		fputs(legal, stdout);
	}

	// Play the game.
play:
	valid = 1;
	while (!(status = board_done(&board))) {
		// Set up screen for next move.
		// Sorry about this ugly call.
		screen_print(&board, valid ? (format ? "\n\n" : "") :
			"\nInvalid move.\n", format);

		// Get the player's move.
		input = yoink(format);

		// Process player's move.
		if (input == 'w' || input == 'k') {
			valid = board_move_up(&board);
		} else if (input == 's' || input == 'j') {
			valid = board_move_down(&board);
		} else if (input == 'a' || input == 'h') {
			valid = board_move_left(&board);
		} else if (input == 'd' || input == 'l') {
			valid = board_move_right(&board);
		} else if (input == 'n') {
			// Start a new game (or not) based on user input.
			printf("Start a new game? [y/N] ");
			input = yoink(format);
			if (input == 'y' || input == 'Y') {
				board_reset(&board);
			}
			continue;
		} else if (input == '?') {
			help_print();
			if (format) {
				printf("\nPress any key to continue.");
				input = yoink(format);
			}
			continue;
		} else {
			valid = 0;
		}

		// End player's move.
		if (valid) {
			board_plop(&board);
		}
	}

	// Print the final board.
	snprintf(buffer, sizeof(buffer),
		"\nGame over, you %s!\n\nPlay again? [y/n]\n",
		(status < 0) ? "LOSE" : "WIN");
	screen_print(&board, buffer, format);

	// Check for new game.
	while ((input = yoink(format)) != 'y' && input != 'Y' &&
		 input != 'n' && input != 'N') {
		 screen_print(&board, buffer, format);
	}
	if (input == 'y' || input == 'Y') {
		board_reset(&board);
		goto play;
	}

	// Restore the terminal.
	if (format) {
		restore_mode();
		leave_alternate_buffer();
	}

	// Free the board.
	board_free(&board);

	// Return success.
	return EXIT_SUCCESS;
}