Hi guys this is my first post and also I should mention that I am a novice programmer so please try to be as patient with me as possible.
So the game I am trying make is the Mastermind game. It is a 2 player game in which one player makes a code and the other player tries to guess it in a number of tries. After each try the program returns 'b' to show the there is a character in the right place, 'w' to show there is an occurring character in the wrong place, and '.' for every character that does not occur at all, My code runs but then crashes after the guess is inputted. Please help me figure out why this is. Here is the code:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
bool ifWin(char*result, int guesslength)/*checks if the user won*/
{
int i;
bool win=true;
for (i=0; i<=guesslength; i++)
{
if(result[i]!='b')
{
win=false;
}
}
return win;
}
char**createPattern(int patternlength, int guesses)
{
int i;
char**pattern;
pattern = (char**)malloc(sizeof(char*)*guesses+1);
for (i=0;i<guesses;i++)
{
pattern[i] = (char*)malloc(sizeof(char)*patternlength);
}
return pattern;
}
char*compare(char**pattern, int guessnumber, int guesses)
{
int c=0, i, n;
char*result=(char*)malloc(sizeof(char)*guesses);
for (i=0;i<=guesses;i++)
{
if(pattern[0][i]==pattern[guessnumber][i])
{
result[c]='b';
pattern[0][i]='z';
c++;
}
for (n=0;n<=guesses; n++)
{
if(pattern[0][n]==pattern[guessnumber][i])
{
result[c]='w';
c++;
}
}
}
int j;
for (j=0;j<guesses;j++)
{
if (result[j]!='b'||'w')
{
result[j]='.';
}
}
return result;
}
int main(void)
{
char**pattern;
char*result;
bool win=false;
int patternlength, guesses;
printf("Enter the length of the pattern: ");
scanf("%d",&patternlength);
printf("Enter the number of guesses: ");
scanf("%d",&guesses);
pattern=createPattern(patternlength,guesses);
printf("Enter the key pattern: ");
scanf("%s",&pattern[0]);
int c=1;
do
{
printf("Enter a guess: ");
scanf("%s",&pattern[1]);
result=compare(pattern, c, guesses);
win=ifWin(result, patternlength);
printf("%s\n",result);
c++;
}while(c<=guesses||win==true);
if (win==true)
{
printf("You Won!!");
}
else
{
printf("You Lost!!");
}
return 0;
}
Thanks for any help.