Thread: coding mastermind in C, only got 2 probs..

  1. #1
    noob lepricaun's Avatar
    Join Date
    Jul 2004
    Posts
    26

    coding mastermind in C, only got 2 probs..

    hi all,

    i'm trying to code mastermind (textbased) in C, but i stumble into two problems..

    here is the code:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    
    
    int main()
    {
    	srand( (unsigned)time( NULL ) );
    	int play_or_instruct;
    	int get_random;
    	int max_tries;
    	int get_answer;
    	int print_answer;
    	int count_equal;
    	int count;
    	int correct;
    	int secret_code[5];
    	int answer[5];
    	printf("\nWelcome to mastermind.\n");
    	printf("press 1 to play, press 2 for instructions :");
    	scanf("%d",&play_or_instruct);
    	if (play_or_instruct==2)		/*check for playing the game or instructions*/
    	{   
    	        printf("\n\nThe goal of the game is to guess the secret\n");
    		printf("secret code. You have 10 tries for this.\n");
    		printf("The code contains 5 random numbers from 0 - 9.\n");
    		printf("Every \'*\' you see next to your input, \n");
    		printf("means that you have one number correct and\n");
    		printf("at the right place.\n");
    		printf("Every \'0\' you see next to your input,\n");
    		printf("means that you have one number correct, but\n");
    		printf("not at the right place.\n");
    		play_or_instruct=1;
    	}
    	if (play_or_instruct ==1)
    	{
    		printf("\nHere we go....\n\n");
    		
    		for (get_random = 0; get_random <5; get_random++) /*get the secret code with the*/
    		    	secret_code[get_random] = rand()%10;	/*random function*/
     		for(max_tries=0;max_tries<10;max_tries++)	/*count number of tries*/
    		{
    			printf("\nEnter your guess: ");
    			for(get_answer=0;get_answer<=4;get_answer++)/*get the answer given*/
    			{
    				scanf("%d",&answer[get_answer]);
    			printf("\n");
    			}
    			for(print_answer=0;print_answer<=4;print_answer++)/*print the answer*/
    				printf("%d",answer[print_answer]);/*given to the screen*/
    			printf("\t");
    			for(count_equal=0;count_equal<=4;count_equal++)	/*check if a number is*/
    			{					/*correct and at the right place*/
    				if(answer[count_equal]==secret_code[count_equal])
    					printf("*");   /*print * if correct*/
    				
    			}
    			count=0;
    			for(correct=0;correct<=4;correct++)/*check if the complete code is */
    			{					/*correct, for each digit*/
    				if(answer[correct]==secret_code[correct])/*count + 1*/
    					count++;
    			}
    			if(count==5)/*if count is equal to 5, let them know they've won, and*/
    			{			/*end the game.*/
    				printf("\nCongratulations, you've won!\n");
    				return 0;
    			}
    			
    		}
    		if(max_tries==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;
    		}
    	}
    	
    }
    /*only got two problems, 
    1st problem:
    getting to print a '0' for each character that is present, but not at the right place, and don't print it double if one character is compaired to two.
    2nd problem:
    as the code is now, the user has to press <enter> after each digit they enter, this has to change. e.g. when entering 12345, it now is 1<enter>2<enter>3<enter>4<enter>5<enter>.*/
    the problems i mean are:

    1st problem:
    getting to print a '0' for each character that is present, but not at the right place, and don't print it double if one character is compaired to two.
    2nd problem:
    as the code is now, the user has to press <enter> after each digit they enter, this has to change. e.g. when entering 12345, it now is 1<enter>2<enter>3<enter>4<enter>5<enter>.

    if anyone knows how i can solve these problems, and tell it to me of course , that would be highly appreciated..
    The path of access leads to the tower of wisdom...
    __________________________________________________ ___________________

    Code:
    
    #include <stdio.h>
    
    int main(void)
    {
            const char buf[17]="Hello everybody!";
    	printf("%s\n",buf);
            return 0;
    }
    

  2. #2
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    >>the user has to press <enter> after each digit they enter, this has to change
    You mean like this:
    http://faq.cprogramming.com/cgi-bin/...&id=1043284392

    Move the srand() call to after the variable definitions, its not allowed where you've put it, unless your using C99 or C++.

    Don't forget to return 0; at the end of main().
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  3. #3
    noob lepricaun's Avatar
    Join Date
    Jul 2004
    Posts
    26
    if it is not allowed, the srand(), then how come it worked? i compiled it on gcc and on dev-c++, on gcc i used the command "gcc -o mastermind mastermind.c" so i didn't use it as c++.

    but i will change it to below the variables to avoid problems in the future...

    as for the return 0;
    it is already inserted in the code at the points i needed it, i see no use putting return 0; at the end of main, since the code will never come to that point... (no offense by the way)

    >>the user has to press <enter> after each digit they enter, this has to change
    You mean like this:
    http://faq.cprogramming.com/cgi-bin...6&id=1043284392
    this is not what i meant, what i mean is:
    since answer[] is declared as an integer, it can take more then 0-9 as value, and since this is the only input i need for this program, i will have to press <enter> after each digit entered... this would be easy if answer[] would be a char, since then you can use the functions getch() or getchar() since these only and maximally require one keystroke (one byte), so at the next keystroke, the character is automatically put in the next place in the array. This i also want to achieve with the integer, but like i said, i haven't got the slightest clue on how to solve this...

    hope this makes things clear...
    The path of access leads to the tower of wisdom...
    __________________________________________________ ___________________

    Code:
    
    #include <stdio.h>
    
    int main(void)
    {
            const char buf[17]="Hello everybody!";
    	printf("%s\n",buf);
            return 0;
    }
    

  4. #4
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    >>then how come it worked?
    Because your compiler was kind to you. Mine wasn't, and neither would yours be if you up the warning levels:
    Code:
    $ gcc -Wall -pedantic junk1.c
    junk1.c: In function `main':
    junk1.c:9: warning: ISO C89 forbids mixed declarations and code
    junk1.c:78: warning: control reaches end of non-void function
    >>so at the next keystroke, the character is automatically put in the next place in the array
    Read the input as a string instead of an int, then process it in memory.

    >>return 0;
    Follow the logic of your code, you'll see that things can happen that cause you to bypass all of your existing return statements.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  5. #5
    noob lepricaun's Avatar
    Join Date
    Jul 2004
    Posts
    26
    ok, learned something new about the srand() function
    as for the return 0; i still don't get it, but i'll go and study it even more...

    how would i process a string in memory?
    never heared of that before...
    The path of access leads to the tower of wisdom...
    __________________________________________________ ___________________

    Code:
    
    #include <stdio.h>
    
    int main(void)
    {
            const char buf[17]="Hello everybody!";
    	printf("%s\n",buf);
            return 0;
    }
    

  6. #6
    ---
    Join Date
    May 2004
    Posts
    1,379
    about the return 0;

    i have always been taught that in each function that there should be one entry and one exit point. some people might choose to object to this but i think it is good coding practice. but return 0; being at the end of your main function, symbolises the end of your program. unless an error has occurred, your program should only exit at that single exit point.

  7. #7
    noob lepricaun's Avatar
    Join Date
    Jul 2004
    Posts
    26
    i have always been taught that in each function that there should be one entry and one exit point. some people might choose to object to this but i think it is good coding practice. but return 0; being at the end of your main function, symbolises the end of your program. unless an error has occurred, your program should only exit at that single exit point.
    that i do get, but as far as i can see in my above code, the program always runs into a return 0; if no error occurs, so i didn't saw the need to put it in the end of main.
    but let's just forget about the return 0; , it's just one line, it doesn't matter to me to put it in it...

    (b.t.w., in my other programs which do end normal, i do use return 0
    The path of access leads to the tower of wisdom...
    __________________________________________________ ___________________

    Code:
    
    #include <stdio.h>
    
    int main(void)
    {
            const char buf[17]="Hello everybody!";
    	printf("%s\n",buf);
            return 0;
    }
    

  8. #8
    Anti-Poster
    Join Date
    Feb 2002
    Posts
    1,401
    For the first question, I've always kept an array of booleans with my array of secret digits so that I can check them off as they are used.
    Code:
    for (i = 0; i < 5; i++)
       check[i] = false;
    
    for (i = 0; i < 5; i++)
    {
       if (guess[i] == secret[i])
       {
          correctplace++;
          check[i] = true;
       }
    }
    
    for (i = 0; i < 5; i++)
    {
       for (j = 0; j < 5; j++)
       {
          if ((guess[i] == secret[j]) && (check[j] == false))
          {
             correctdigit++;
             check[j] = true;
          }
       }
    }
    For the second question, you could input all five numbers at the same time into an int and then extract them using modular arithmetic. Something like:
    Code:
    if ((input_number > 9999) && (input_number < 100000))  //bounds checking
    {
       for (int i = 0; i < 5; i++)
       {
          guess[i] = input_number % 10;
          input_number /= 10;
       }
    }
    The only problem with doing it this way is that leading zeroes won't work.
    If I did your homework for you, then you might pass your class without learning how to write a program like this. Then you might graduate and get your degree without learning how to write a program like this. You might become a professional programmer without knowing how to write a program like this. Someday you might work on a project with me without knowing how to write a program like this. Then I would have to do you serious bodily harm. - Jack Klein

  9. #9
    Been here, done that.
    Join Date
    May 2003
    Posts
    1,164
    Quote Originally Posted by lepricaun
    that i do get, but as far as i can see in my above code, the program always runs into a return 0; if no error occurs, so i didn't saw the need to put it in the end of main.
    but let's just forget about the return 0; , it's just one line, it doesn't matter to me to put it in it...

    (b.t.w., in my other programs which do end normal, i do use return 0
    It should matter to you if you wish to become a programmer. Here's the reason:
    main() is an int -- always. It is not a void, not a float. Only int. Therefore, you need to start the program with
    Code:
    int main()
    You see, main is a function. It is called by the operating system (definition is good enough for this explanation). As you are probably aware, in C every function must be defined as returning a type and having a return t; at the end or a void and a return; at the end (which is optional for void only). You get to define what and how all your own functions return -- but you must always use them that way. You can't return a float from an int function.

    Well since main is a function, it is defined by the operating system as returning an int. It therefore must return an int. Period. That's the way it was designed.

    So, your signature code:
    Code:
    #include <stdio.h>
    
    main()
    {
    printf("Hello world!");
    }
    is all wrong. It really should be:
    Code:
    #include <stdio.h>
    
    int main()    // an int definition
    {
        printf("Hello world!");    // indent for readability
        return 0;    // give the OS the int it is looking for
    }
    Definition: Politics -- Latin, from
    poly meaning many and
    tics meaning blood sucking parasites
    -- Tom Smothers

  10. #10
    noob lepricaun's Avatar
    Join Date
    Jul 2004
    Posts
    26
    WaltP>> i understand what you mean, but try this site, it has a bunch of C tutorials and most of them start out without declaring main() as an int, like my signature...

    i understand that the OS should get a resonse back from a program to know if it ended as it should, or ended with a exitcode 1 or something like that, so i know what it is meant for, but as you can see in my code above, it has return 0; in it, just not at the lowest bottom of main(), but they are there...

    pianorain>>thanks for your answer, i'll go and see if i can get it to work

    i'll let you know..
    The path of access leads to the tower of wisdom...
    __________________________________________________ ___________________

    Code:
    
    #include <stdio.h>
    
    int main(void)
    {
            const char buf[17]="Hello everybody!";
    	printf("%s\n",buf);
            return 0;
    }
    

  11. #11
    ... kermit's Avatar
    Join Date
    Jan 2003
    Posts
    1,534
    Quote Originally Posted by lepricaun
    WaltP>> i understand what you mean, but try this site, it has a bunch of C tutorials and most of them start out without declaring main() as an int, like my signature...

    i understand that the OS should get a resonse back from a program to know if it ended as it should, or ended with a exitcode 1 or something like that, so i know what it is meant for, but as you can see in my code above, it has return 0; in it, just not at the lowest bottom of main(), but they are there...
    An implicit int (that is to say, if the return type int was not explicitly added to the code, the compiler would assume an int return type) used to be legal - I believe that is why on older code you could write main() without specifiying what type it was. That is no longer true. You must give the return type. And yes we see your code has a few return statements - Did you see what Hammer mentioned about that though? Look:

    Don't forget to return 0; at the end of main()

    and

    Follow the logic of your code, you'll see that things can happen that cause you to bypass all of your existing return statements.

    If your return statement is at the end of main(), it will get used at some point, provided your program does not crash. The way you have things set up, it is not guaranteed that they will be used.

    ~/

  12. #12
    ---
    Join Date
    May 2004
    Posts
    1,379
    If your return statement is at the end of main(), it will get used at some point, provided your program does not crash. The way you have things set up, it is not guaranteed that they will be used.
    hence what i said about having one exit point

  13. #13
    Quote Originally Posted by lepricaun.sig
    Code:
    #include <stdio.h>
    
    main()
    {
    printf("Hello world!");
    }
    This is plain wrong.

    C90 : the 'int' is not required, but an explicit return value is.
    C99 : the 'int' is required, but an explicit return value is not.

    In both cases, the emitted characters are not terminated by a '\n'. The result may appear or not on the display device. Add a '\n', of force the output (fflush(stdout)).

    You may upgrade your .sig the portable way:
    Code:
    #include <stdio.h>
    
    int main (void)
    {
       printf ("Hello world!\n");
       return 0;
    }
    Emmanuel Delahaye

    "C is a sharp tool"

  14. #14
    noob lepricaun's Avatar
    Join Date
    Jul 2004
    Posts
    26
    well, it's just a sig, but if it is bothering you guys i'll change it

    as for the program, i did what pianorain suggested and got to this code:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    
    #define false 0
    #define true 1
    
    
    int main()
    {
    	srand( (unsigned)time( NULL ) );
    	int play_or_instruct;
    	int get_random;
    	int max_tries;
    	int get_answer;
    	int print_answer;
    	int count_equal;
    	int correctplace=0;
    	int run,a;
    	int correctdigit=0;
    	int secret_code[5];
    	int answer[5];
    	int check[5];
    	printf("\nWelcome to mastermind.\n");
    	printf("press 1 to play, press 2 for instructions :");
    	scanf("%d",&play_or_instruct);
    	if (play_or_instruct==2)		/*check for playing the game or instructions*/
    	{   
    	        printf("\n\nThe goal of the game is to guess the secret\n");
    		printf("secret code. You have 10 tries for this.\n");
    		printf("The code contains 5 random numbers from 0 - 9.\n");
    		printf("Every \'*\' you see next to your input, \n");
    		printf("means that you have one number correct and\n");
    		printf("at the right place.\n");
    		printf("Every \'0\' you see next to your input,\n");
    		printf("means that you have one number correct, but\n");
    		printf("not at the right place.\n");
    		play_or_instruct=1;
    	}
    	if (play_or_instruct ==1)
    	{
    		printf("\nHere we go....\n\n");
    		
    		for (get_random = 0; get_random <5; get_random++) /*get the secret code with the*/
    		    	secret_code[get_random] = rand()%10;	/*random function*/
     		for(max_tries=0;max_tries<=10;max_tries++)	/*count number of tries*/
    		{
    			printf("\nEnter your guess: ");
    			for(get_answer=0;get_answer<=4;get_answer++)/*get the answer given*/
    			{
    				scanf("%d",&answer[get_answer]);
    			}
    			printf("\n");
    			for(print_answer=0;print_answer<=4;print_answer++)/*print the answer*/
    				printf("%d",answer[print_answer]);/*given to the screen*/
    			printf("\t");
    			check[get_answer] = false;
    			for (get_answer = 0; get_answer < 5; get_answer++)
    			{
       				if (answer[get_answer] == secret_code[get_answer])
       				{
          					correctplace++;
          					check[get_answer] = true;
       				}
    			}
    				
    			for (get_answer = 0; get_answer < 5; get_answer++)
    			{
    			   for (run = 0; run < 5; run++)
    			   {
    			      if ((answer[get_answer] == secret_code[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(max_tries==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;
    }
    (watch the return 0 ; )
    but somehow it looks to work fine, but when you play the program and recalculate, it just isn't right...

    any hints??
    The path of access leads to the tower of wisdom...
    __________________________________________________ ___________________

    Code:
    
    #include <stdio.h>
    
    int main(void)
    {
            const char buf[17]="Hello everybody!";
    	printf("%s\n",buf);
            return 0;
    }
    

  15. #15
    ---
    Join Date
    May 2004
    Posts
    1,379
    the logic in your game is pretty messy (although it could be a lot worse) try creating functions to simplify the flow of your program.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 9
    Last Post: 03-20-2009, 05:22 PM
  2. how to start coding for this ?
    By codomaniac in forum Networking/Device Communication
    Replies: 1
    Last Post: 11-23-2004, 03:40 PM
  3. Before Coding
    By cyberCLoWn in forum C++ Programming
    Replies: 16
    Last Post: 12-15-2003, 02:26 AM
  4. Coding Contest....
    By Koshare in forum A Brief History of Cprogramming.com
    Replies: 46
    Last Post: 10-14-2001, 04:32 PM