I have an assignment to create a mastermind game where the player has 10 attempts to find the secret code. After each input, the game indicates to the player the number of well placed pieces and the number of misplaced pieces.
Pieces will be '0' '1' '2' '3' '4' '5' '6' '7' '8'.
If the player finds the code, he wins, and the game stops. A misplaced piece is a piece that is present in the secret code but that is not in a good position.
You must read the player's input from the standard input.
and here is my code
Code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "headers.h"
#define false 0
#define true 1
char* input() {
char* buffer = malloc(5);
buffer[5] = '\0';
fflush(stdout);
read(0, buffer, 5);
return buffer;
}
int main()
{
srand( time( NULL ) );
int getRandom;
int maxTries;
int getAnswer;
int printAnswer;
int correctPlace=0;
int run;
int correctDigit=0;
int secretCode[5];
char* answer;
int check[5];
printf("\n Welcome to my mastermind");
printf("\n Will you find the secret code?");
printf("\t");
for(getRandom = 0; getRandom < 5; getRandom++)
secretCode[getRandom] = rand()%10;
for(maxTries = 0; maxTries <= 10; maxTries++) {
printf("\n Please enter a valid guess ");
for (getAnswer = 0; getAnswer <=4; getAnswer++) {
//scanf("%d", &answer[getAnswer]);
answer = input();
}
printf("\n");
for(printAnswer = 0; printAnswer <= 4; printAnswer++)
printf("%d", answer[printAnswer]);
printf("\t");
check[getAnswer] = false;
for (getAnswer = 0; getAnswer < 5; getAnswer++) {
if (answer[getAnswer] == secretCode[getAnswer]) {
correctPlace++;
check[getAnswer] = true;
}
}
for (getAnswer = 0; getAnswer < 5; getAnswer++) {
for (run = 0; run < 5; run++){
if ((answer[getAnswer] == secretCode[run]) && (check[run] == false)){
correctDigit++;
check[run] = true;
}
}
}
if(correctPlace ==5){
printf("\nCongratulations, you've won!\n");
return 0;
}
for(; correctPlace >=0; correctPlace--)
printf("*");
for(; correctDigit >=0; correctDigit--)
printf("0");
printf("\n");
if(maxTries==10)/*if maximum number of tries have passed, let them know*/{
/*they didn't made it and end the game*/
printf("\nUnfortunately you did not make it.\n");
return 0;
}
}
return 0;
}