This is a single-header-file library that provides easy-to-use connect4 strong solver written in C. This implementation is largely based on the work of Pascal Pons and his excellent guide at http://blog.gamesolver.org.
To use this library, do this in one C file:
#define C4_SOLVER_LIB_IMPLEMENTATION
#include "c4_solver.h"Additionally you may embed an openingbook directly into the binary instead of loading it at runtime by doing:
#define C4_SOLVER_LIB_EMBED_OPENINGS
#define C4_SOLVER_LIB_EMBED_OPENINGS_FILE "openingbook_depth8_sorted.bin"
#define C4_SOLVER_LIB_IMPLEMENTATION
#include "c4_solver.h"The print_board(...) function will print coloured output
if you define:
#define C4_SOLVER_LIB_COLORIZEFor a more detailed example src/main.c implements a simple commandline game.
// initialize
// position stores a representation of the current connect4 board.
// connectfour contains the implementation of the actual solver.
struct position pos = {0};
struct connectfour cf = {0};
// The openingbook is used to speed up calculation of early moves
// as they can be quite slow otherwise.
// The openingbook needs to be sorted by the key of the positions stored within.
connectfour_init(&cf, "openingbook_depth8_sorted.bin");
// Gameloop
while(1){
// print board state.
print_board(&pos);
int current_col = 3; //TODO get user input colum 0-6
if(isWinningMove(&pos, current_col)){
//TODO handle this.
}
if(!canPlay(&pos, current_col)){
//TODO handle this.
}
// Make a move
playCol(&pos, current_col);
// Calculate the best next move.
int best_move = connectfour_best_move(&cf,&pos);
// Observing cf->rating[col] will return the score of a specific move.
// Positive scores indicate a winning move, negative scores a losing move and
// a score of 0 indicates a move that will result in a draw.
if(isWinningMove(&pos, best_move)){
//TODO handle this.
}
playCol(&pos, best_move);
}
// Free memory used by the solver
connectfour_free(&cf);This c source code is published under the agpl v3 license https://www.gnu.org/licenses/agpl-3.0.en.html. see end of file for detailed license information.
Pascal Pons -- For his guide on connect4 solvers at http://blog.gamesolver.org.