sw-battle-test-c

Interesting test task in C instead of C++
git clone git://bsandro.tech/sw-battle-test-c
Log | Files | Refs | README

attack_ranged.c (1382B)


      1 #include <stdlib.h>
      2 #include <stdbool.h>
      3 #include <stdio.h>
      4 #include "sys/param.h"
      5 #include "stb_ds.h"
      6 #include "actions/attack_ranged.h"
      7 #include "components/ranged.h"
      8 #include "core/ecs/entity.h"
      9 #include "core/world.h"
     10 
     11 bool Action_Attack_Ranged(Entity *e, World *w) {
     12     //printf("unit %d try ranged attack\n", e->id);
     13     Ranged r = Entity_Find_Component(e, COMPONENT_RANGED)->ranged; //@todo NULL check
     14     int hp = Entity_Find_Component(e, COMPONENT_HEALTH)->health.hp; //@todo NULL check
     15     Position p = Entity_Find_Component(e, COMPONENT_POSITION)->position; //@todo NULL check
     16     for (int i=0;i<arrlen(w->entities);++i) {
     17         if (w->entities[i].id==e->id) continue;
     18         Position pe = Entity_Find_Component(&w->entities[i], COMPONENT_POSITION)->position;
     19         // used to be taxicab distance to keep it simple for now
     20         int dist = MAX(abs(pe.x-p.x), abs(pe.y-p.y));
     21         if (dist>=2&&dist<=r.range) {
     22             //printf("found enemy for ranged attack %d\n", w->entities[i].id);
     23             Entity_Find_Component(&w->entities[i], COMPONENT_HEALTH)->health.hp -= r.agility;
     24             printf("[%d] UNIT_ATTACKED attackerUnitId=%d targetUnitId=%d damage=%d targetHp=%d\n", w->turn, e->id, w->entities[i].id, r.agility, Entity_Find_Component(&w->entities[i], COMPONENT_HEALTH)->health.hp);
     25             return true;
     26         }
     27     }
     28     return false;
     29 }
     30