summary refs log tree commit diff stats
path: root/src/components/ai.cpp
blob: 9f8c764f889c2f368c2b89977aa13529ce3e80f7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
#include "ai.h"
#include <cstdlib>
#include "entity.h"

void AIActionContainer::addAction(std::shared_ptr<AIAction> action)
{
  actions.push_back(action);
}

void AIActionContainer::start(Game& game, Entity& entity)
{
  currentAction = begin(actions);
  
  if (currentAction != end(actions))
  {
    (*currentAction)->start(game, entity);
  }
}

void AIActionContainer::perform(Game& game, Entity& entity, double dt)
{
  if (!isDone())
  {
    (*currentAction)->perform(game, entity, dt);
  
    if ((*currentAction)->isDone())
    {
      currentAction++;
      
      if (!isDone())
      {
        (*currentAction)->start(game, entity);
      }
    }
  }
}

bool AIActionContainer::isDone() const
{
  return currentAction == end(actions);
}

AI::AI(int chance)
{
  this->chance = chance;
}

int AI::getChance() const
{
  return chance;
}

AI& AIComponent::emplaceAI(int chance)
{
  maxChance += chance;
  ais.emplace_back(chance);
  
  return ais.back();
}

void AIComponent::tick(Game& game, Entity& entity, double dt)
{
  if (currentAI == nullptr)
  {
    int toChoose = rand() % maxChance;
    for (auto& ai : ais)
    {
      if (toChoose < ai.getChance())
      {
        currentAI = &ai;
        break;
      } else {
        toChoose -= ai.getChance();
      }
    }
    
    if (currentAI != nullptr)
    {
      currentAI->start(game, entity);
    }
  }
  
  if (currentAI != nullptr)
  {
    currentAI->perform(game, entity, dt);
  
    if (currentAI->isDone())
    {
      currentAI = nullptr;
    }
  }
}

MoveAIAction::MoveAIAction(Direction dir, int len, int speed)
{
  this->dir = dir;
  this->len = len;
  this->speed = speed;
}

void MoveAIAction::start(Game& game, Entity& entity)
{
  remaining = len;
}

void MoveAIAction::perform(Game&, Entity& entity, double dt)
{
  double dist = dt * speed;
  remaining -= dist;
  
  switch (dir)
  {
    case Direction::Left:
    {
      entity.position.first -= dist;
      break;
    }
    
    case Direction::Right:
    {
      entity.position.first += dist;
      break;
    }
    
    case Direction::Up:
    {
      entity.position.second -= dist;
      break;
    }
    
    case Direction::Down:
    {
      entity.position.second += dist;
      break;
    }
  }
}

bool MoveAIAction::isDone() const
{
  return remaining <= 0.0;
}