// A band of marauding orcs is attacking!
// A very simple fantasy simulator to show use of structs
// as well as structs within structs and arrays of structs
// Marc Chee (marcchee@cse.unsw.edu.au)
// April 2019

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define NUM_GRUNTS 5

struct fighter {
    char name[20];
    int strength;
    int health;
};

struct warband {
    char name[20];
    struct fighter grunts[NUM_GRUNTS];
};

int attack(struct fighter *attacker, struct fighter *target);

int main (int argc, char *argv[]) {
    if (argc > 1) {
        // if we received a command line argument, use that as our random seed
        srand(atoi(argv[1]));
    }
    
    // Set up defender
    struct fighter defender;
    // defender.name = "Anduin Lothar"; // This line won't work! Can't dump multiple
                                 // elements into an array all at once
    strcpy(defender.name, "Anduin Lothar");
    defender.strength = 5;
    defender.health = 5;
    
    // Set up attackers
    struct warband orcs;
    strcpy(orcs.name, "Blackrock Orcs"); 
    int i = 0;
    while(i < NUM_GRUNTS) {
        strcpy(orcs.grunts[i].name, "Grunt");
        orcs.grunts[i].strength = 3;
        orcs.grunts[i].health = (rand() % 6) + 1;
        i++;
    }
    
    // Fight through the grunts, one at a time
    int front = 0;
    while (defender.health > 0 && front < NUM_GRUNTS) {
        if(attack(&defender, &orcs.grunts[front])) {
            // Orc didn't die, allow it to counterattack
            attack(&orcs.grunts[front], &defender);
        } else {
            // Orc at the front has died, move on to the next
            front++;
        }
    }
    
    // Who won?
    if(defender.health > 0) {
        printf("%s is Victorious!\n", defender.name);
    } else {
        printf("%s have overrun the village!\n", orcs.name);
    }
}

int attack(struct fighter *attacker, struct fighter *target) {
    printf("%s attacks %s for %d damage.\n", attacker->name, target->name, 
                                                        attacker->strength);
    target->health -= attacker->strength;
    if (target->health <= 0) {
        // target has died
        printf("%s has died.\n", target->name);
        return 0;
    } else {
        return 1;
    }
}



Resource created Thursday 04 April 2019, 04:55:57 AM, last modified Saturday 06 April 2019, 06:33:12 PM.

file: structs.c


Back to top

COMP1511 19T1 (Programming Fundamentals) is powered by WebCMS3
CRICOS Provider No. 00098G