Thread: Question about variables in structures

  1. #1
    Registered User
    Join Date
    Mar 2008
    Posts
    3

    Question about variables in structures

    Is there a way to write a general chunk of code and then have the program determine which variables to use depending on some condition?
    One thing I'm trying to experiment with is a combat system for a text RPG; I have all the enemy variables in a structure like

    Code:
     
    struct enemy {
         int eatk;
         int edef;
         int maxehp;
         int ehp;
         int XPworth;
    };
    and then several kinds of monsters declared with different values for each variable.

    What I'd like to do is have the program generate a random number and then send out a monster based on that; I have a general "battle mode" that has stuff like

    Code:
    ...
    printf("You attack the enemy for %d damage!\n", patk-edef);
    ehp = ehp - patk + edef;
    printf("The enemy has %d HP remaining.\n", ehp);
    
    ...
    How could I make it so if, for example, a function returned a random number '2' (I know how to do this part), all the instances of 'edef' would be set equal to (for example) 'rat.edef'? I know I can have a switch or if statements than set edef = rat.edef but if I have more than a few monsters that seems like it would be quite huge
    Last edited by Donarstan; 03-23-2008 at 04:35 AM. Reason: Clairification

  2. #2
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    It depends on how/what you want to do. The easiest way is just an if.
    Code:
    if (num == 2)
    	edef = rat.edef;
    If you want something more complex, you can use an array and initialize it:
    Code:
    int myarray[]= { /* something */, /* something */, &rat.edef, /* something */ };
    /* ... */
    edef = *myarray[num];
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 8
    Last Post: 01-23-2008, 04:22 AM
  2. Using pointers to access variables in structures
    By Desolation in forum C++ Programming
    Replies: 5
    Last Post: 07-27-2006, 12:10 PM
  3. Pointers to structures - Beginner question
    By RobJ in forum C Programming
    Replies: 6
    Last Post: 04-10-2006, 05:57 PM
  4. Structures: a yes/no question.
    By Matt13 in forum C Programming
    Replies: 2
    Last Post: 07-29-2004, 08:33 AM
  5. Question about Structures in Code
    By Satellite in forum C++ Programming
    Replies: 5
    Last Post: 01-14-2004, 05:05 PM