Added support for quitting without ^C, and outputting to file

This commit is contained in:
AnnaSnoeijs 2025-06-13 22:51:11 +02:00
parent 6d879da5fa
commit d0c257b310
5 changed files with 68 additions and 23 deletions

View file

@ -21,13 +21,14 @@
#include <stdint.h>
#include <limits.h>
#include <getopt.h>
#include <string.h>
#include "macros.h"
#include "config.h"
#include "logic.h"
#include "types.h"
#include "ui.h"
#define VERSION 0.1.2
#define VERSION 0.2.0
#ifndef GITHASH
#define FULLVERSION VERSION
@ -50,6 +51,8 @@ int main( int argc, char *argv[] ){
.rows = BOARD_HEIGHT,
.columns = BOARD_WIDTH
};
FILE *outputfile = NULL;
char *filename = NULL;
// Parse options
for(;;){
// Allowed options
@ -59,12 +62,15 @@ int main( int argc, char *argv[] ){
{ "version", no_argument, NULL, '\0' },
{ "columns", required_argument, NULL, 'c' },
{ "rows", required_argument, NULL, 'r' },
{ "output", required_argument, NULL, 'o' },
{ 0 }
};
// Index of current option
int option_index = 0;
// Get next option
char c = getopt_long( argc, argv, "hlc:r:", long_options, &option_index );
char c = getopt_long( argc, argv, "hlc:r:o:",
long_options, &option_index
);
if( c == -1 ) break;
// Handle option
switch( c ){
@ -86,12 +92,14 @@ int main( int argc, char *argv[] ){
case 'h': // --help
printf( "Usage: %s [OPTIONS]\n\n", argv[0] );
printf(
" -h --help Print this help text\n"
" -l --license Print the LICENSE file\n"
" --version Print the version string\n"
" -h --help Print this help text\n"
" -l --license Print the LICENSE file\n"
" --version Print the version string\n"
"\n"
" -c n --columns n Set the amount of columns\n"
" -r n --rows n Set the amount of rows\n"
"\n"
" -o file --output file Ouput moves taken in game to file\n"
);
return 0;
case 'l': // --license
@ -109,6 +117,10 @@ int main( int argc, char *argv[] ){
case 'r': // --rows
playboard.rows = atoi(optarg);
break;
case 'o':
filename = strdup(optarg);
outputfile = fopen( filename, "w" );
break;
}
}
// Check for unhandled options
@ -163,10 +175,32 @@ int main( int argc, char *argv[] ){
wins.same.diagonalDown4 = calloc( playboard.columns, sizeof(column_t) );
initBoard( playboard );
// Begin loopin
if( outputfile != NULL ){
fprintf(
outputfile,
"# File generated by " VERSIONSTRING
"# First define the config\n"
"--rows %d\n"
"--columns %d\n"
"# Now follows the moves taken, zero indexed\n"
,
playboard.rows,
playboard.columns
);
}
for(;; playboard.player = !playboard.player ){
columnsint_t column = askColumn( playboard );
if( column == QUITCOLUMN ) break;
playMove( &playboard, column );
calcWins( &wins, playboard, column );
updateBoard( wins, playboard, column );
if( outputfile != NULL ){
fprintf( outputfile, "%d\n", column );
}
}
if( outputfile != NULL ){
fclose( outputfile );
printf( "Output is written to %s\n", filename );
}
exit_ui();
}