-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathai.cpp
More file actions
86 lines (79 loc) · 2.04 KB
/
ai.cpp
File metadata and controls
86 lines (79 loc) · 2.04 KB
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
#include "pch.h"
#include "main.hpp"
void PlayerAi::update(std::shared_ptr<Ent> owner) {
if (owner->mortal) {
if (!owner->mortal->isDead()) {
int ix = 0;
int iy = 0;
switch (engine.lastKey.vk) {
case TCODK_UP: iy = -1; break;
case TCODK_DOWN: iy = +1; break;
case TCODK_LEFT: ix = -1; break;
case TCODK_RIGHT: ix = +1; break;
default:break;
}
if (ix != 0 || iy != 0) {
engine.gameState = Engine::TURN;
if (moveOrAttack(owner, owner->x + ix, owner->y + iy)) {
engine.dungeon->computeFov();
}
}
}
}
}
bool PlayerAi::moveOrAttack(std::shared_ptr<Ent> owner, int tx, int ty) {
if (engine.dungeon->isWall(tx, ty)) {
return false;
}
for (auto &ent : engine.entL) {
if (ent->mortal) {
if (!ent->mortal->isDead() && ent->x == tx && ent->y == ty) {
owner->combat->attack(owner, ent);
return false;
}
}
else if (ent->mortal->isDead() && ent->x == tx && ent->y == ty) {
engine.gui->message(TCODColor::white, "A %s lays here.\n", ent->name);
}
}
owner->x = tx;
owner->y = ty;
return true;
}
static const int TRACK_TURNS = 3;
void MobAi::update(std::shared_ptr<Ent> owner) {
if (owner->mortal) {
if (owner->mortal->isDead()) {
return;
}
if (engine.dungeon->isInFov(owner->x, owner->y)) {
moveCount = TRACK_TURNS;
}
else {
moveCount--;
}
if (moveCount > 0) {
moveOrAttack(owner, engine.player->x, engine.player->y);
}
}
}
void MobAi::moveOrAttack(std::shared_ptr<Ent> owner, int tx, int ty) {
int dx(tx - owner->x), dy(ty - owner->y), sdx(dx > 0 ? 1:-1), sdy(dy > 0 ? 1:-1), distance((int)sqrt(dx*dx + dy*dy));
if (distance >= 2) {
dx = (int)(round(dx / distance));
dy = (int)(round(dy / distance));
if (engine.dungeon->canWalk(owner->x + dx, owner->y + dy)) {
owner->x += dx;
owner->y += dy;
}
else if (engine.dungeon->canWalk(owner->x + sdx, owner->y)) {
owner->x += sdx;
}
else if (engine.dungeon->canWalk(owner->x, owner->y + sdy)) {
owner->y += sdy;
}
}
else if (owner->combat) {
owner->combat->attack(owner, engine.player);
}
}