Code:
#include<stdio.h>
//Prototypes//
void Codemaker(char CodePegs[4][10]); // 4 being the size of the array and 10 being the size of the string stored//
void guess(char guessCodePegs[4][10]);
void codeCheck(char CodePegs[4][10], char guessCodePegs[4][10], int *blackPeg, int *whitePeg);
void answer(char guessCodePegs[4][10], int blackPeg, int whitePeg);
int main()
{
srand(time(NULL));
int i, blackPeg, whitePeg, wrongGuess;
char CodePegs[4][10], guessCodePegs[4][10];
printf("Mastermind game! \n");
printf("Enter using letters Y,W,R,O,G,B \n");
printf("Where Y=Yellow\n");
printf(" W=White\n");
printf(" R=Red\n");
printf(" O=Orange\n");
printf(" G=Green\n");
printf(" B=Black\n\n");
printf("Press Enter after each letter. \n");
Codemaker(CodePegs);
for(wrongGuess=1; wrongGuess<=12; wrongGuess++) //gives player 12 guesses
{
guess(guessCodePegs);
codeCheck(CodePegs, guessCodePegs, &blackPeg, &whitePeg);
answer(guessCodePegs, blackPeg, whitePeg);
if(blackPeg == 4) //if player guess all correct then the game finishes
{
printf("Congratulations!\n\n\n\n");
break;
}
}
if(wrongGuess == 13) //if player cannot guess all colours correctly in 12 rounds, he loses
printf("\nYou Lost!\nSecret Code: %s %s %s %s\n\n\n\n\n", CodePegs[0], CodePegs[1], CodePegs[2], CodePegs[3]);
else
exit(1);
}
//Functions//
void Codemaker(char CodePegs[4][10])
{
int i, randColor;
for(i=0; i<4; i++)
{
randColor = 1 + rand() % 6; //creates a number
switch(randColor) //converts number created to a string
{
case 1: strcpy(CodePegs[i], "Y"); //stringcopy replaces string with respective letters
break;
case 2: strcpy(CodePegs[i], "W");
break;
case 3: strcpy(CodePegs[i], "R");
break;
case 4: strcpy(CodePegs[i], "O");
break;
case 5: strcpy(CodePegs[i], "G");
break;
case 6: strcpy(CodePegs[i], "B");
break;
}
}
}
void guess(char guessCodePegs[4][10])
{
int i;
printf("\nEnter your guess:\n");
for( i=0; i<4; i++)
scanf("%s", guessCodePegs[i]);
}
void codeCheck(char CodePegs[4][10], char guessCodePegs[4][10], int *blackPeg, int *whitePeg)
{
int i, j, checkSecret[4] = {1,1,1,1}, checkGuess[4] = {1,1,1,1};
*blackPeg = *whitePeg = 0;
for(i=0; i<4; i++) //if secret and guess's position and color are same, blackpeg increases and mark "check"
if(strcmp(guessCodePegs[i], CodePegs[i]) == 0)
{
++*blackPeg;
checkSecret[i] = checkGuess[i] = 0;
}
for(i=0; i<4; i++)
for(j=0; j<4; j++)
if(strcmp(CodePegs[i],guessCodePegs[j]) == 0 && checkGuess[i] && checkSecret[j] && i != j)
{// determines crushes and eliminates extra whitePegs
++*whitePeg;
checkSecret[j] = checkGuess[i] = 0;
}
}
void answer(char guessCodePegs[4][10], int blackPeg, int whitePeg)
{
int i;
printf("\nYour Guess\t\t\t\tYour Score\n");
for(i=0; i<4; i++)
printf("%s ", guessCodePegs[i]);
printf("\t\t");
for(i=0; i<blackPeg; i++)
printf("black ");
for(i=0; i<whitePeg; i++)
printf("white ");
printf("\n\n");
}