Hey everybody,
I was trying to create a program that simulated the game "Mastermind" using numbers 0-5 instead of the six colored pegs. I have written out the code, and it seems to work, all except for the loop I have set to see if the user wants to play again. The getchar function that I have used for a char variable to determine whether to continue the loop does not seem to be working. Any help would be appreciated.
Here's what my code is so far:
/*A game very similar to Mastermind, using numbers 0-5 instead of pegs*/
#include <stdio.h>
#include <stdlib.h>
void inputguess (int guess[]);
int rightwrong (int guess[], int key[], int control, int control2, int wrongplace);
int main()
{
int rightplace = 0;
int wrongplace = 0;
int numguess = 0;
int key[4], key2[4], guess[4];
int control = 0;
int control2 = 0;
int correct = 0;
char again = 'y';
while (again == 'y')
{
for(control = 0; control < 4; control ++)
key[control] = rand()%6;
for(control = 0; control < 4; control ++)
key2[control] = key[control];
while(correct == 0)
{
inputguess(guess);
numguess += 1;
rightplace = 0;
wrongplace = 0;
for(control = 0; control < 4; control ++)
{
{
if(guess[control] == key[control])
{
rightplace += 1;
key[control] = -1234;
guess[control] = -1235;
}
}
}
for(control = 0; control < 4; control++)
{
if(guess[control] != key[control])
wrongplace = rightwrong(guess, key, control, control2, wrongplace);
}
printf("\nright number right place: %d\n", rightplace);
printf("right number wrong place: %d\n\n", wrongplace);
if (rightplace == 4)
{
correct = 1;
printf("YOU WIN \a\a\a\a\a\n");
printf("it took you %d guesses\n", numguess);
}
for( control = 0; control < 4; control++)
key[control] = key2[control];
printf("Would you like to play again? (y/n): ");
again = getchar(); /*the program isn't stopping to let the user enter a char*/
}
}
}
void inputguess(int guess[])
{
printf("enter the first digit of your guess: ");
scanf("%d", &guess[0]);
printf("enter the second digit of your guess: ");
scanf("%d", &guess[1]);
printf("enter the third digit of your guess: ");
scanf("%d", &guess[2]);
printf("enter the fourth and final digit of your guess: ");
scanf("%d", &guess[3]);
}
int rightwrong( int guess[], int key[], int control, int control2, int wrongplace)
{
for(control2 = 0; control2 <= (control - 1); control2++)
{
if (guess[control2] == key[control])
{
wrongplace += 1;
key[control] = -1234;
guess[control2] = -1235;
}
}
for(control2 = (control + 1); control2 < 4; control2++)
{
if (guess[control2] == key[control])
{
wrongplace += 1;
key[control] = -1234;
guess[control2] = -1235;
}
}
return wrongplace;
}