Thread: First Text based game.

  1. #1
    Registered User
    Join Date
    Dec 2012
    Posts
    15

    First Text based game.

    So this is my first text based game, I didn't bother completing it because i felt like my coding was very inefficient. Please give me some comments on what you all think and what i can do to simply what I am trying to do or what to do to improve my work.

    Code:
    #include <stdio.h>#include <stdlib.h>
    #include <time.h>
    #include <string.h>
    
    
    int
    main()
    {
          int player, attack, monster, attack2, initiate, retal, ogre, gold, n, d, sword;
          int loot, selection, direction, mask, m, def, wizard;
          int cont, potion, boss;
          char name[100];
          
          boss = 1000;
          ogre = 150;
          wizard = 300;
          potion = 0;
          monster = 100;
          player = 1000;
          gold = 0;
          n = 0;//sword att
          d = 0;//sword def
          m = 0;//bear mask att
          def = 0;//bear mask def
         
         
         
         
          
          
          
          
          printf("----------------------------------------------------------------------------\n");
          printf("----------------------------------------------------------------------------\n");
          printf(" III       III      II       IIIIIIII  III     IIIIIIII IIIIIIII  IIIIIII  \n");
          printf(" III       III     IIII      III  III  III     IIIIIIII III  III  III  IIII \n");
          printf(" III   I   III    II  II     IIIIIIII  III     II    II IIIIIIII  III   III \n");
          printf(" III II II III   IIIIIIII    III III   III     II    II III III   III   III \n");
          printf(" IIIII   IIIII  III    III   III  III  IIIIIII IIIIIIII III  III  III  IIII \n");
          printf(" III       III III      III  III   III IIIIIII IIIIIIII III   III IIIIIII   \n");
          printf("-----------------------------------------------------------------------------\n");
          printf("-----------------------------------------------------------------------------\n");
          printf("By, Hool\n\n\n\n\n");
          
          
          printf("                           PRESS ENTER TO CONTINUE!\n\n\n\n\n\n\n\n");
          
          printf("TIP: Press 1, 2, or 3 then enter when making selections.\n");
          getch();
          system("cls");
          
          printf("What is your name> ");
          scanf("%s", &name);
          system("cls");
          printf("Well nice too meet you %s, you look like a mighty fine warrior!", name);
          getch();
          system("cls");
          //Introduction
          sleep(1000);
          printf("%s have entered the world of Sindaria!\n\nThe land of mystical beings and ferocious creatures!\n\n\n", name);
          sleep(1000);
          printf("This land has been ruled by an evil Emperor known as Jarhuvis\n");
          sleep(1000);
          printf("You are our last hope for destroying this evil creature\n");
          getch();
          system("cls");
          
          printf("\n\n\n\n\n\n\n                               %s please save us\n");
          
          getch();
          system("cls");
           //Beginning of journey
          printf("Which direction would you like to start your journey?\n");
          printf("1.North\n2.South\n3.East\n4.West\n");
          scanf("%d", &direction);
          if (direction == 4 || direction == 3){
                        printf("This path is blocked try another route\n");
                        system("pause");
                        return(0);
                        }
          if (direction == 1){
          printf("You have chosen to head North\n");
          sleep(1000);
          printf("You begin your journey north down an old dirt road\n\n");
          sleep(1000);
          printf("You come across a group of woods known as the Fernot forest\n");
          sleep(1000);
          printf("From inside a voice calls to you\n");
          sleep(1000);
          printf("%s cccommmmeeee clooosssseerrrr\n", name);
          sleep(1000);
          printf("You enter the forest and come across an old wrinkly man\n");
                       sleep(1000);
                       printf("'Hello traveler, what is your reason for entering my forest?'\n");
                       sleep(1000);
                       printf("'Uuuhh.. I..'\n");
                       sleep(2000);
                       printf("'Ha nevermind why! We will see how you hold up in my domain!'\n");
                       sleep(1000);
                       printf("With a sudden flash\nBANGG!\n");
                       sleep(1000);
                       printf("You notice the old man has disappeared\n");
                       sleep(1000);
                       printf("Whats that noise?!");
                       getch();
                       system("cls");
                       
          
          
          
          //----------------------------------------------------------------------------------------------
          sleep(2000);
          printf("\n\n\n\n\n\n\n                            Suddenly a Bear appears!\n");
          
          sleep(2000);
          printf("\n\n                            What should you do?!\n\n");
                   
                      while (monster <= 100 && monster > 0 && player <= 1000 && player > 0){
                      printf("1.Attack\n2.Defend\n");
                      scanf("%d", &attack2);
                      //Monsters Health & Damage recieved
                      if (attack2 == 1){
                      srand((unsigned)time(NULL));
                      int attack = rand() % 50 + n;
                      monster = monster - attack;
                      //Players Health & Damage recieved
                      srand((unsigned)time(NULL));
                      int retal = rand() % 38 ;
                      player = player - retal;
                      printf("You attack the Bear!\n");
                      printf("It attacks you back!\n");
                      printf("Bear's health: %d\n", monster);
                      printf("Your health: %d\n", player); 
                      getch();
                      system("cls");
                      }
                      else if (attack2 == 2){
                      //Monster Health & Damage Recieved
                      srand((unsigned)time(NULL));
                      int attack2 = rand()% 25 + (n/2);
                      monster = monster - attack2;
                      //Player health & damage recieved
                      srand((unsigned)time(NULL));
                      int retal = rand() % 25 - d;
                      player = player - retal;
                      printf("You defend against the Bear!\n");
                      printf("The bear bites into your armor!\n");
                      printf("Bear's health: %d\n", monster);
                      printf("Your health: %d\n", player); 
                      getch();
                      system("cls");
                      }
                      if (monster <=0 ){
                      printf("You have slayed the Bear!\n");
                      //Loot system
                      srand((unsigned)time(NULL));
                      int loot = rand()% 50;
                      printf("You have loot %d gold off the body\n", loot);
                      gold += loot;
                      printf("Current gold: %d\n", gold);
                      }
                      else if (player == 0 || player <0){
                                 printf("Player is dead\n");
                                 printf("                 GAME OVER\n");
                                 system("pause");
                                 return(0);
                                 }        
                      }
                      
                   getch();
                   system("cls");
                   printf("Would you like to take the bears head and wear it as a mask?\n\n");
                   sleep(2000);
                   printf("This new mask will increase attack but lower your defense.\n");
                   printf("\n\n\n\n\n\n\n                              1.Yes\n                               2.No\n");
                   scanf("%d", &mask);
                   if (mask == 1){
                            m = 15;
                            def = 15;
                            printf("You now have the eyes of the BEAR!\n");
                            }
                   else if (mask == 2){
                        printf("Sucks to be normal\n");
                        }
                   getch();
                   system("cls");
                   
                   printf("You continue down the path of the forest leaving the dead bear carcass behind you\n");
                   sleep(1000);
                   printf("A wooden chest is off in the distance sitting on a stump\n");
                   sleep(1000);
                   printf("Making your way over to it you hear a laughter from behind you\n");
                   getch();
                   system("cls");
                   printf("\n\n\n\n                                          HA!\n\n");
                   sleep(500);
                   printf("                                          HA!\n\n");
                   sleep(500);
                   printf("                                          HA!\n\n");
                   getch();
                   system("cls");
                   printf("\n\n\n\n\n\n                              The old man from earlier appears!\n");
                   getch();
                   system("cls");
                   printf("\n\n\n\n                        'I WARNED YOU WOULDN'T SURVIVE IN MY FOREST!'\n\n");
                   sleep(1000);
                   printf("\n       ' I AM THE ALL POWERFUL ZUCHOR, YOU WILL BE MY NEXT VICTIM!!!'\n");
                   getch();
                   system("cls");
                   //----------------------------------------------------------------------------------------------------------------------------------             
    
    
                   while (wizard <= 300 && wizard > 0 && player <= 1000 && player > 0){
                      printf("1.Attack\n2.Defend\n");
                      scanf("%d", &attack2);
                      //Wizards Health & Damage recieved
                      if (attack2 == 1){
                      srand((unsigned)time(NULL));
                      int attack = rand() % 50 + (n + m);
                      wizard = wizard - attack;
                      //Players Health & Damage recieved
                      srand((unsigned)time(NULL));
                      int retal = rand() % 80 ;
                      player = player - retal;
                      printf("You attack the Zuchor!\n");
                      printf("He cast a spell back at you!\n");
                      printf("Zuchor's health: %d\n", wizard);
                      printf("Your health: %d\n", player); 
                      getch();
                      system("cls");
                      }
                      if (attack2 == 2){
                      //Monster Health & Damage Recieved
                      srand((unsigned)time(NULL));
                      int attack2 = rand()% 35 + (((n+m)/2));
                      wizard = wizard - attack2;
                      //Player health & damage recieved
                      srand((unsigned)time(NULL));
                      int retal = rand() % 55 - (d+def);
                      player = player - retal;
                      printf("You defend against the Zuchor's spells!\n");
                      printf("He cast a fire ball!\n");
                      printf("Zuchor's health: %d\n", wizard);
                      printf("Your health: %d\n", player); 
                      getch();
                      system("cls");
                      }
                      if (wizard <=0 ){
                      printf("You have destroyed Zuchor!\n");
                      //Loot system
                      srand((unsigned)time(NULL));
                      int loot = rand()% 100;
                      printf("You have loot %d gold off the body\n", loot);
                      gold += loot;
                      printf("Current gold: %d\n", gold);
                      sleep(1000);
                      printf("You obtain a health potion\n");
                      potion = 1;
                      }
                      else if (player == 0 || player <0){
                                 printf("Player is dead\n");
                                 printf("                 GAME OVER\n");
                                 system("pause");
                                 return(0);
                                 }        
                                 }
                   
                //--------------------------------------------------------------------------------------------------------
                //Merchant   
                   
                      getch();
                      system("cls");
                      printf("You feel exhausted after your battle but you can see the light at the end of the woods\n");
                      sleep(1000);
                      printf("As you finally break through the last of the trees you feel a sudden surge of relief\n");
                      sleep(1000);
                      printf("You start making your way down the a brick path that exist the woods\n\n");
                      sleep(1000);
                      printf("You hear a man's voice calling out");
                      sleep(1000);
                      printf("\n\n\n\n                       'Ahoy ey mate!'\n\n");
                      getch();
                      system("cls");
                      printf("Its a man with a cart of items displayed");
                      getch();
                      system("cls");
                      printf("\n\n\n\n          'Hey traveler you want to have a look at my goods?'");
                      getch();
                      system("cls");
                      printf("%s- 'Sure why not'", name);      
                      getch();
                      system("cls"); 
                      
                      
                      printf("What would you like to purchase?\n");
                                  printf("1.Sword of Fury\n2.Steel Shield\n3.Exit\n");
                                  scanf("%d", &selection);
                                              if(selection == 1 && gold > 50){
                                              n += 10;
                                              gold -= 50;
                                              sword = 1;
                                              printf("You purchased: The Sword of Fury!\n");
                                              sleep(1000);
                                              printf("Current gold: %d\n", gold);
                                              }
                                              if(selection == 1 && gold < 50){ 
                                              printf("Sorry you do not have enough gold\n");
                                              }
                                              if (selection == 2 && gold > 50){
                                              d += 10;
                                              gold -=50;
                                              printf("You have purchased a Steel Shield!\n");
                                              }
                                              if (selection == 3){
                                                                               }
                      getch();
                      system("cls");
                      printf("You see a dark castle with ominous clouds lingering over it\n");
                      sleep(1000);
                      printf("A chill runs through your spine...\n\n");
                      getch();
                      system("cls");
                      printf("\n\n\n\n\n\n\n      ITS TIME TO HEAD TO THE FINAL BATTLE");
                      getch();
                      system("cls");
                    //---------------------------------------------------------------------------
                    //FINAL BATTLE!
                      printf("\n\n\n\n\n\n You find yourself at the gates of Jarhuvis' Castle");
                      getch();
                      system("cls");
                      
                      printf("Pushing the gate with all your might the large doors swing open.\n\n");
                      sleep(1000);
                      printf("As you through the main hall your hear a menancing but powerful voice");
                      getch();
                      system("cls");
                      printf("\n\n\n\n\n\n\n                 I'VE BEEN EXPECTING YOU %s!!", name);
                      getch();
                      system("cls");
                      printf("\n\n\n\n\n\n\n                 SINDARIA IS MINE!");
                      getch();
                      system("cls");
                      printf("\n\n\n\n\n\n\n                 FINAL BATTLE!");
                      sleep(500);
                      printf("\n                FINAL BATTLE!");
                      sleep(500);
                      printf("\n               FINAL BATTLE!");  
                      sleep(500);
                      printf("\n             FINAL BATTLE!");
                      sleep(500);
                      printf("\n            FINAL BATTLE!");
                      sleep(500);
                      printf("\n          FINAL BATTLE!");
                      getch();
                      system("cls");
                      
                      //End of Second Combat
                      while (boss <= 1000 && boss > 0 && player <= 2000 && player > 0){
                      printf("1.Attack\n2.Defend\n3.Potion\n");
                      scanf("%d", &attack2);
                      //ogres Health & Damage recieved
                      if (attack2 == 1){
                      srand((unsigned)time(NULL));
                      int attack = rand() % 50 + (n+m);
                      boss = boss - attack;
                      //Players Health & Damage recieved
                      srand((unsigned)time(NULL));
                      int retal = rand() % 90;
                      player = player - retal;
                      printf("You attack the Jarhuvis!\n");
                      printf("It attacks you back!\n");
                      printf("Jarhuvis' health: %d\n", boss);
                      printf("Your health: %d\n", player); 
                      getch();
                      system("cls");
                      }
                      else if (attack2 == 2){
                      //Boss Health & Damage Recieved
                      srand((unsigned)time(NULL));
                      int attack2 = rand()% 25 + (((m+n)/2));
                      boss = boss - attack2;
                      //Player health & damage recieved
                      srand((unsigned)time(NULL));
                      int retal = rand() % 75 - d;
                      player = player - retal;
                      printf("You defend against the Jarhuvis'!\n");
                      printf("It attacks you back!\n");
                      printf("Jarhuvis' health: %d\n", boss);
                      printf("Your health: %d\n", player); 
                      getch();
                      system("cls");
                      }
                      if (attack2 == 3 && potion != 0){
                           potion -= 1;
                           player += 200;
                           printf("You used your potion\n");
                           printf("You have healed yourself 200 life points\n");
                           printf("Current Health: %d\n", player);
                           }
                           else if (attack2 == 3 && potion == 0){
                           printf("You have no more potions sorry\n");
                           
                           }
                      if (player <= 0){
                                 printf("You are dead\n");
                                 getch();
                                 system("cls");
                                 printf("\n\n\n\n\n                       GAME OVER!");
                                 system("pause");
                                 return(0);
                                 }
                      if (boss <= 0){
                      printf("You have killed Jaharvis!!!\n");
                      }
                      }
                
                      sleep(1000);
                      getch();
                      system("cls");
                      printf("\n\n\n\n                YOU HAVE SAVED SANDARIA!");
                      getch();
                      system("cls");
                      printf("\n\n\n\n\n\n                       YOU HAVE WON!");
                      getch();
                      printf("\n\n\n\n\n\n                  Programmed by, Hool");
                      printf("\n                   Story by, Hool\n");
                      system("pause");
                      return(0);
                      }
                      
                      
            if (direction == 2){
                          printf("You head south\n");
                          sleep(2000);
                          printf("A wild ogre appears\n");
                          getch();
                          system("cls");      
                       
                  //-----------------------------------------------------------------------------------------                            
                                    
    
    
                      //End of Second Combat
                      while (ogre <= 150 && ogre > 0 && player <= 1000 && player > 0){
                      printf("1.Attack\n2.Defend\n");
                      scanf("%d", &attack2);
                      //ogres Health & Damage recieved
                      if (attack2 == 1){
                      srand((unsigned)time(NULL));
                      int attack = rand() % 50 + n;
                      ogre = ogre - attack;
                      //Players Health & Damage recieved
                      srand((unsigned)time(NULL));
                      int retal = rand() % 40;
                      player = player - retal;
                      printf("You attack the Ogre!\n");
                      printf("It attacks you back!\n");
                      printf("Ogre's health: %d\n", ogre);
                      printf("Your health: %d\n", player); 
                      getch();
                      system("cls");
                      }
                      else if (attack2 == 2){
                      //Monster Health & Damage Recieved
                      srand((unsigned)time(NULL));
                      int attack2 = rand()% 25 + (n/2);
                      ogre = ogre - attack2;
                      //Player health & damage recieved
                      srand((unsigned)time(NULL));
                      int retal = rand() % 25 - d;
                      player = player - retal;
                      printf("You defend against the ogre!\n");
                      printf("It attacks you back!\n");
                      printf("ogre's health: %d\n", ogre);
                      printf("Your health: %d\n", player); 
                      getch();
                      system("cls");
                      }
                      if (ogre <= 0){
                      printf("You have slayed the monster!\n");
                      srand((unsigned)time(NULL));
                      //loot system
                      int loot = rand()% 20;
                      printf("You have loot %d gold off the body\n", loot);
                      gold += loot;
                      printf("Current gold: %d\n", gold);
                      
                      }
                      else if (player == 0 || player <0){
                                 printf("Player is dead\n");
                                 printf("                 GAME OVER\n");
                                                          }
                                                          }
                      printf("Would you like to proceed?\n");
                      printf("1.Yes\n2.No Check health and gold first\n3.Shop\n");
                      scanf("%d", &cont);
                                  if (cont == 1){
                                  printf("Continuing\n");//Continue Journey
                                  }
                                  if (cont == 2){//Stats Check
                                  printf("Your current health: %d\nYour current Gold: %d\n", player, gold);
                                  }
                                  if (cont == 3){//shop
                                  printf("What would you like to purchase?\n");
                                  printf("1.Sword of Fury\n2.Steel Shield\n3.Exit\n");
                                  scanf("%d", &selection);
                                              if(selection == 1 && sword ==1){
                                                           printf("Sorry you already own this weapon\n");
                                                           }
                                              else if(selection == 1 && gold > 50){
                                              n += 10;
                                              gold -= 50;
                                              sword = 1;
                                              printf("You purchased: The Sword of Fury!");
                                              sleep(2000);
                                              printf("Current gold: %d\n", gold);
                                              }
                                              if(selection == 1 && gold < 50){ 
                                              printf("Sorry you do not have enough gold\n");
                                              }
                                              if (selection == 2 && gold > 50){
                                              d += 10;
                                              gold -=50;
                                              printf("You have purchased a Steel Shield!\n");
                                              }
                                              if (selection == 3){
                                                            
                                                            }
                                                            
                                                            printf("Go north for longer story\n");
                                                            } 
                                                            system("pause");
                         return(0); }               
                  //------------------------------------------------------------------------------------------------                                    
                       
                       
                                                                                                                                                      }
    here is the .exe

    Warlord alpha.exe download - 2shared

  2. #2
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    First more functions, second only call srand once. Third more functions. Forth find an indentation style you like and use it consistently. Finally more functions.

    Jim

  3. #3
    Registered User
    Join Date
    Dec 2012
    Posts
    15
    Quote Originally Posted by jimblumberg View Post
    First more functions, second only call srand once. Third more functions. Forth find an indentation style you like and use it consistently. Finally more functions.

    Jim
    lol yeah i'm still very knew to this thanks for the comment, With more functions do you mean just so i can replace sets of code?

  4. #4
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    You use functions to both eliminate code duplications and more importantly to improve program readability, functionality, and simplify future modifications. These functions can add structure that your current program lacks.

    Jim

  5. #5
    Registered User
    Join Date
    Dec 2012
    Posts
    15
    Quote Originally Posted by jimblumberg View Post
    You use functions to both eliminate code duplications and more importantly to improve program readability, functionality, and simplify future modifications. These functions can add structure that your current program lacks.

    Jim
    i guess ill read up so more on function implication

  6. #6
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    Let me just say that this little game shows a lot of work and creativity. It seems you're passionate about your programming, and that is great.

    jimblumberg already mentioned functions.

    In addition, when you learn structures (if you haven't already), those come in handy for these types of programs. You can define the attributes of an entity (with variables), and create as many instances of that entity as you need. For instance, if all your entities (player, monsters, bosses) have common attributes (hit points, max damage, etc), these variables can be grouped into a structure. Then you can simply declare a variable of that structure type to create a new entity.

  7. #7
    Registered User
    Join Date
    Dec 2012
    Posts
    15
    Quote Originally Posted by Matticus View Post
    Let me just say that this little game shows a lot of work and creativity. It seems you're passionate about your programming, and that is great.

    jimblumberg already mentioned functions.

    In addition, when you learn structures (if you haven't already), those come in handy for these types of programs. You can define the attributes of an entity (with variables), and create as many instances of that entity as you need. For instance, if all your entities (player, monsters, bosses) have common attributes (hit points, max damage, etc), these variables can be grouped into a structure. Then you can simply declare a variable of that structure type to create a new entity.
    Thanks , i just finished my intro to computer science class today; we were using the book problem solving and program design. We never got to the structures section of this book but i'm going to start looking at that now. When yall say i need more functions, like can you give me an example? i know basic functions but not sure entirely what you both mean.

  8. #8
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    I hope this helps illustrate our point. Consider a program that calculates a sum three times and prints it to the screen each time. All crammed into "main()," it might look something like this:

    Code:
    #include <stdio.h>
    
    int main(void)
    {
       int x,y,sum;
    
       x = 3;
       y = 4;
       sum = x + y;
       printf("%d + %d = %d\n",x,y,sum);
    
       x = 6;
       y = 7;
       sum = x + y;
       printf("%d + %d = %d\n",x,y,sum);
    
       x = 20;
       y = 30;
       sum = x + y;
       printf("%d + %d = %d\n",x,y,sum);
    
       return 0;
    }
    But now let's put the adding and printing into a function we can reuse:

    Code:
    #include <stdio.h>
    
    void printSum(int x, int y);
    
    int main(void)
    {
        int x,y,sum;
    
        printSum(3,4);
        printSum(6,7);
        printSum(20,30);
    
        return 0;
    }
    
    void printSum(int x, int y)
    {
        int sum = x + y;
        printf("%d + %d = %d\n",x,y,sum);
    }

  9. #9
    Registered User
    Join Date
    Dec 2012
    Posts
    15
    Quote Originally Posted by Matticus View Post
    I hope this helps illustrate our point. Consider a program that calculates a sum three times and prints it to the screen each time. All crammed into "main()," it might look something like this:

    Code:
    #include <stdio.h>
    
    int main(void)
    {
       int x,y,sum;
    
       x = 3;
       y = 4;
       sum = x + y;
       printf("%d + %d = %d\n",x,y,sum);
    
       x = 6;
       y = 7;
       sum = x + y;
       printf("%d + %d = %d\n",x,y,sum);
    
       x = 20;
       y = 30;
       sum = x + y;
       printf("%d + %d = %d\n",x,y,sum);
    
       return 0;
    }
    But now let's put the adding and printing into a function we can reuse:

    Code:
    #include <stdio.h>
    
    void printSum(int x, int y);
    
    int main(void)
    {
        int x,y,sum;
    
        printSum(3,4);
        printSum(6,7);
        printSum(20,30);
    
        return 0;
    }
    
    void printSum(int x, int y)
    {
        int sum = x + y;
        printf("%d + %d = %d\n",x,y,sum);
    }

    okay so pretty much in layman's terms, you are just building a function at the bottom of your code and naming it ex. FunctionA so then everytime you need to use FunctionA you just use it like how you displayed instead of typing out an entire set of code multiple times

    edit: Also with doing this work with functions; do people just say write a set of functions for a certain task and save it as example1.h so that when the are working on their main program they can just call that header file and reuse those functions and keep their code less crammed?
    Last edited by skatenjoi922; 12-11-2012 at 05:40 PM.

  10. #10
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    okay so pretty much in layman's terms, you are just building a function at the bottom of your code and naming it ex. FunctionA so then everytime you need to use FunctionA you just use it like how you displayed instead of typing out an entire set of code multiple times
    Yes, exactly. That example was contrived, and over-simplified, but you get the idea.

    You're already using functions all over your code (like "printf()"), though they are standard functions which means the source code for them already exists. The only difference is when using your own functions, you get to write the code yourself.

    But functions would not be as useful if they didn't have ways of varying the specifics. Good functions will be more generalized, allowing them to be used for different values of data. This is why they were designed to accept arguments.

    For instance:

    Code:
    /* poor function design */
    
    void printWin(void)
    {
        printf("You win the battle!\n");
    }
    
    void printLose(void)
    {
        printf("You lose the battle!\n");
    }
    
    void printRun(void)
    {
        printf("You run away from the battle!\n");
    }
    
    /* ------------------------------------------------ */
    
    /* better function design */
    
    void printMessage(char *msg)
    {
        printf("%s\n",msg);
    }
    
    /*
        In the second example, you have a single function that can print whatever
        string you pass to it as an argument, instead of separate functions that
        contained hard-coded data.
    */
    edit: Also with doing this work with functions; do people just say write a set of functions for a certain task and save it as example1.h so that when the are working on their main program they can just call that header file and reuse those functions and keep their code less crammed?
    Yes, you can write your own header/source files for common functions that you want to reuse. It's a better alternative to "reinventing the wheel" each time you write a program that requires similar functions.

    For instance, let's say that you write a game like this with a "die rolling" function to determine the outcome of events randomly.

    Then, later on, you want to create a "character generator" program that needs a "die rolling" function. You can reuse the code as you hinted at.

    (Normally, you would create a header file with the function prototypes, and a source file with the function definitions - I'm trying to keep this on a more broad level so I won't get into too much detail on this.)

    One more example, based on the "die rolling" function and my own personal experience. A long time ago, I made a simple die rolling function:

    Code:
    int rollDie(void)
    {
        int result;
    
        result = (rand() % 6) + 1;
    
        return result;
    }
    Looks good, right? But what if you play a game that uses several types of die? When faced with that, I improved my function to be more generic:

    Code:
    int rollDie(int maxValue)
    {
        int result;
    
        result = (rand() % maxValue) + 1;
    
        return result;
    }
    Now I can roll a D6 ("rollDie(6)"), a D20, ("rollDie(20)"), etc. These are the sorts of things you get better at judging when you get experience (not "experience points"!) with programming.
    Last edited by Matticus; 12-11-2012 at 07:01 PM.

  11. #11
    Registered User
    Join Date
    Dec 2012
    Posts
    15
    Quote Originally Posted by Matticus View Post

    For instance:

    Code:
    /* poor function design */
    
    void printWin(void)
    {
        printf("You win the battle!\n");
    }
    
    void printLose(void)
    {
        printf("You lose the battle!\n");
    }
    
    void printRun(void)
    {
        printf("You run away from the battle!\n");
    }
    
    /* ------------------------------------------------ */
    
    /* better function design */
    
    void printMessage(char *msg)
    {
        printf("%s\n",msg);
    }
    
    /*
        In the second example, you have a single function that can print whatever
        string you pass to it as an argument, instead of separate functions that
        contained hard-coded data.
    */
    Thanks for all the help you have been giving me, I understand developing my own functions now. I was looking at the above code you posted and was trying to use it but for some reason i keep getting <null>, what is wrong with the code i am using? I tried so many different variations but keep getting the same result. Here is the code I am inputing

    Code:
    #include <strings.h>#include <stdio.h>
    
    
    
    
    int
    main()
    { 
          char msg;
          char win[20] = "You won";
    
    
    void printMessage(char *msg);
    {
        printf("%s\n", msg);
    }
         
     
         void printMessage(char win[20]);
         
     system("pause");
     return(0);
    
    
    
    
    }
    Lastly what is the * for in *msg?

    I looked through my book but could not find an answer.

  12. #12
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    One function should never be defined in another function. The braces are used to indicate scope ... but don't worry too much about that yet. Just remember that all the code that makes up a function should be separate from all the other code that make up functions. And they are separated by braces.

    Code:
    /* first function */
    return-type function1(return-type variable)
    {
        // code
    }
    
    /* second function */
    return-type function2(return-type variable)
    {
        // code
    }
    The reason your code is failing (and here's the kicker) ... is because "main()" itself is just another (albeit special) function. Just like your program calls functions, other programs (i.e. the OS) are calling yours in the same manner.

    Follow my formula [second code of post #8] a little more closely, being sure to keep functions separated.

    As for what the '*' means - that refers to a pointer. Wait until you get there, it should be covered soon.

  13. #13
    Registered User
    Join Date
    Dec 2012
    Posts
    15
    I'm sorry man but I just can't seem to get this to work. I've tried everything. I don't know how to run this program without main() but this is what i have, i've been going off your code

    Code:
    #include <string.h>#include <stdio.h>
    
    
    
    
    void printMessage(char *msg)
    {
         printf("%s\n", msg);
    }
    
    
    int
    main(void)
    {
              char win[100] = "You won";
    
    
              void printMessage(char win);
    
    
    system("pause");
    return 0;
    }

  14. #14
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    No, "main()" is required. And don't just throw around code - understand what you're coding. Functions in C - Cprogramming.com

    Code:
    #include <stdio.h>
    
    void printMessage(char *msg)
    {
         printf("%s\n", msg);
    }
    
    int main(void)
    {
        char win[100] = "You won";
    
        //void printMessage(char win);  // incorrect way to call a function
        printMessage(win);              // correct way to call a function
    
        //system("pause");  // not needed - "getchar()" would work for this
        return 0;
    }
    If you spent a little more time study the clear example from post #8 (second bit of code), you should have seen how functions are declared/defined and called.

  15. #15
    Registered User
    Join Date
    Dec 2012
    Posts
    15
    Quote Originally Posted by Matticus View Post
    No, "main()" is required. And don't just throw around code - understand what you're coding. Functions in C - Cprogramming.com

    Code:
    #include <stdio.h>
    
    void printMessage(char *msg)
    {
         printf("%s\n", msg);
    }
    
    int main(void)
    {
        char win[100] = "You won";
    
        //void printMessage(char win);  // incorrect way to call a function
        printMessage(win);              // correct way to call a function
    
        //system("pause");  // not needed - "getchar()" would work for this
        return 0;
    }
    If you spent a little more time study the clear example from post #8 (second bit of code), you should have seen how functions are declared/defined and called.
    sorry i'm so difficult, i need to read over my book more. Thanks again. I should've noticed the void wasn't needed when calling the function, and same with the char. I sometimes don't recognize the obvious

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Text based game
    By wipeout4wh in forum C Programming
    Replies: 12
    Last Post: 03-26-2009, 04:39 PM
  2. text based game
    By PippinofTook in forum Game Programming
    Replies: 5
    Last Post: 08-24-2005, 06:56 PM
  3. Text-Based Game Help
    By Sentral in forum Game Programming
    Replies: 6
    Last Post: 07-01-2005, 01:08 PM
  4. Text based game..
    By MipZhaP in forum C++ Programming
    Replies: 8
    Last Post: 02-28-2005, 08:35 AM
  5. Text Based Game
    By drdroid in forum C++ Programming
    Replies: 2
    Last Post: 02-18-2002, 06:21 PM