// On a rooftop somewhere in New York
// Ninjas are fighting!
// This is a small game-like simulation
// involving a team of ninjas in combat
// with their nemesis
// It is intended to show use of structs
// as well as pointers
// Marc Chee (marc.chee@unsw.edu.au)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_LENGTH 50
#define TEAM_SIZE 4
struct ninja {
char name[MAX_LENGTH];
char phrase[MAX_LENGTH];
int power;
int health;
};
void attack(struct ninja *attacker, struct ninja *target);
int stillAlive(struct ninja *solo, struct ninja team[TEAM_SIZE]);
int main(int argc, char *argv[]) {
if (argc > 1) {
// if we received a command line argument,
// use that as our random seed
srand(strtol(argv[1], NULL, 10));
}
// Setup the array of ninjas
struct ninja turtles[TEAM_SIZE];
strcpy(turtles[0].name, "Leonardo");
strcpy(turtles[0].phrase, "Leonardo leads");
turtles[0].power = 8;
turtles[0].health = 8;
strcpy(turtles[1].name, "Donatello");
strcpy(turtles[1].phrase, "Donatello does machines");
turtles[1].power = 6;
turtles[1].health = 7;
strcpy(turtles[2].name, "Raphael");
strcpy(turtles[2].phrase, "Raphael is cool but crude");
turtles[2].power = 6;
turtles[2].health = 9;
strcpy(turtles[3].name, "Michelangelo");
strcpy(turtles[3].phrase, "Michelangelo is a party dude");
turtles[3].power = 8;
turtles[3].health = 6;
struct ninja shredder;
strcpy(shredder.name, "The Shredder");
strcpy(shredder.phrase, "Tonight I dine on turtle soup");
shredder.power = 20;
shredder.health = 20;
// main game loop
int turtleCount = 0;
struct ninja *turtle = &turtles[turtleCount];
printf("%s\n", turtle->phrase);
struct ninja *shred = &shredder;
while (stillAlive(shred, turtles)) {
if (turtle->health <= 0) {
// this turtle is knocked out, move on
turtleCount++;
turtle = &turtles[turtleCount];
printf("%s\n", turtle->phrase);
} else {
attack(shred, turtle);
attack(turtle, shred);
}
}
}
// The attacker will reduce the health of the target
// based on their power
void attack(struct ninja *attacker, struct ninja *target) {
int damage = rand() % attacker->power;
printf("%s attacks %s for %d damage.\n",
attacker->name, target->name, damage
);
target->health -= damage;
if (target->health <= 0) {
// target has run out of health
printf("%s is knocked out.\n", target->name);
}
}
// returns 1 if both teams still have someone fighting, otherwise 0
int stillAlive(struct ninja *solo, struct ninja team[TEAM_SIZE]) {
int sAlive = 1;
int tAlive = 0;
if (solo->health <= 0) {
sAlive = 0;
}
int i = 0;
while (i < TEAM_SIZE) {
if (team[i].health > 0) {
tAlive = 1;
}
i++;
}
return sAlive * tAlive;
}
Resource created Wednesday 10 July 2019, 02:29:57 AM, last modified Tuesday 16 July 2019, 02:17:13 AM.
file: ninjaFight.c