/* ========================================================================== mastermind.c - a simple text-based C program to play the game "mastermind" Copyright (c) 2003 by Jeffrey S. Rosenthal (jeff@math.toronto.edu). Available from http://probability.ca/jeff/comp/ Licensed for general copying, distribution and modification according to the GNU General Public License (http://www.gnu.org/copyleft/gpl.html). Compile with "cc mastermind.c -lm -o mastermind". ========================================================================== */ #include #include #include #include #include #define WIDTH 4 #define NUMCOLS 6 #define MAXGUESSES 100 char colour[NUMCOLS+1]; int invalid; char inputline[161]; char inputstring[WIDTH+1]; int numexact; int nummissed; int i,j; int MAXNUMTRIES; main() { int true[WIDTH]; int guess[WIDTH]; int guessnum; char c; seedrand(); colour[0] = 'R'; colour[1] = 'G'; colour[2] = 'B'; colour[3] = 'Y'; colour[4] = 'O'; colour[5] = 'P'; MAXNUMTRIES = 1000*pow(NUMCOLS, WIDTH); printf("\n\nWelcome to mastermind, by Jeffrey Rosenthal.\n"); while (1) { printf("\nChoose [p]layer or [c]omputer to guess: "); fgets(inputline, 160, stdin); if ( (sscanf(inputline, "%c", &c)) > 0 ) { if ( (c=='p') || (c=='P') ) playerguess(); else if ( (c=='c') || (c=='C') ) computerguess(); else printf("Invalid response!\n"); } } exit(0); } playerguess() { int true[WIDTH]; int guess[WIDTH]; int guessnum = 0; /* Make up random true. */ randnorep(true); /* output(true); REMOVE THIS LATER! */ printf("\nOkay, I've made up a secret length-%d code. ", WIDTH); showcolours(); numexact=-1; while (numexact= MAXNUMTRIES) { printf("\nHm ... I think you're lying ... I give up!\n\n"); giveup = 1; break; } randnorep(guesses[guessnum]); possible = 1; if (guessnum>1) { for(compnum=1; compnumWIDTH) ) { printf("Input number matching exactly (followed by return): "); fgets(inputline, 160, stdin); if ( (sscanf(inputline, "%d", &numexact) == 0) || (numexact<0) || (numexact>WIDTH) ) printf("\nInvalid response!\n\n"); } while ( (numexactWIDTH)) ) { printf("Input number matching colour but not position (followed by return): "); fgets(inputline, 160, stdin); if ( (sscanf(inputline, "%d", &nummissed) == 0) || (nummissed<0) || (nummissed>WIDTH) ) printf("\nInvalid response!\n\n"); } printf("Thank you.\n"); matchhistory[guessnum][0] = numexact; matchhistory[guessnum][1] = nummissed; } } if (giveup==0) printf("\nI win, in %d guesses!\n\n", guessnum); } convert(char string[WIDTH+1], int result[WIDTH]) { invalid = 0; for (i=0; i= '0') && (string[i] < '0'+NUMCOLS) ) { result[i] = string[i] - '0'; } else { for (j=0; j0) { for (j=0; j