-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathEnemy.cpp
380 lines (309 loc) · 12.3 KB
/
Enemy.cpp
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
//
// Created by Иван Ильин on 23.07.2020.
//
#include "Enemy.h"
#include <utility>
#include "Time.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include "Point2D.h"
using namespace std;
Enemy::Enemy(World& world, Point2D position, double vPos, double height, double health, std::string texture, double fieldOfView, double eyesHeight, double depth, double walkSpeed, double jumpSpeed, double viewSpeed) :
Player(position, vPos, height, health, std::move(texture)), W_world(world), d_fieldOfView(fieldOfView), d_eyesHeight(eyesHeight), d_jumpSpeed(jumpSpeed), d_walkSpeed(walkSpeed), d_depth(depth)
{
Weapon weapon1(30);
weapon1.choiceWeapon("shotgun");
v_weapons.push_back(weapon1);
}
void Enemy::connect(std::string clientIp, sf::Uint16 clientPort) {
client = new ClientUDP(W_world);
client->connect(clientIp, clientPort);
}
[[nodiscard]] bool Enemy::connected() const {
return client->connected();
}
void Enemy::disconnect() {
if(client->isWorking())
client->disconnect();
}
void Enemy::updateDistances() {
v_distances.clear();
allCollisions.clear();
Point2D forward = { cos(d_direction), sin(d_direction) };
Point2D left = { -forward.y, forward.x };
double halfWidth = tan(d_fieldOfView / 2) * ((double)SCREEN_WIDTH / SCREEN_HEIGHT);
// Visible for player segments
for (int i = 0; i < DIS_SEG_FOR_BOTS; i++) // Need top-down map? Set limit to segs. No need? DISTANCE_SEGMENTS.
{
pair<Point2D, Point2D> segment1;
//double offset = ((i * 2.0 / (DIS_SEG_FOR_BOTS - 1.0)) - 1.0) * halfWidth;
segment1 = { {x(), y()}, {x() + d_depth * cos(i*2*PI/DIS_SEG_FOR_BOTS), y() + d_depth * sin(i*2*PI/DIS_SEG_FOR_BOTS)} };
std::vector<RayCastStructure> v_rayCastStructure;
objectsRayCrossed(segment1, v_rayCastStructure);
// first 16 neirons are distances to objects around
if (!v_rayCastStructure.empty()) {
v_distances.push_back(v_rayCastStructure);
double dist = v_rayCastStructure.back().distance / 10;
dist = (dist > 1) ? 1 : dist;
N_network.addInput(dist);
}
else {
v_distances.push_back({{d_depth, 0, nullptr, 1}});
N_network.addInput(1);
}
}
}
// Fire at the player
void Enemy::fire()
{
if (v_weapons[i_selectedWeapon].fire()) {
d_wastedAmmun++;
client->localPlayer()->weapon().fire();
client->localPlayer()->weapon().set(v_weapons[i_selectedWeapon].balance());
client->localPlayer()->chDir(d_direction);
client->localPlayer()->fire();
}
}
void Enemy::objectsRayCrossed(const pair<Point2D, Point2D>& ray, std::vector<RayCastStructure>& v_rayCastStruct)
{
pair<Point2D, Point2D> edge;
Point2D nearCross;
double len = 0;
double closest = d_depth;
string nearObject;
for (auto& object : W_world.objects())
{
if (object.first == getName() || object.second == nullptr || object.second.get()->nodes().size() < 2)
continue;
// Check crossing
Point2D crossPoint = ray.second;
std::vector<RayCastStructure> v_reflectedRayCastStructure;
pair<Point2D, Point2D> wall;
// If ray crossed with object
if (object.second.get()->cross(ray, wall, crossPoint, len))
{
v_rayCastStruct.push_back({ (ray.first - crossPoint).abs(), len, object.second.get(), object.second.get()->height(), v_reflectedRayCastStructure });
// for collision
double dist = (crossPoint - position()).abs();
if (dist < closest)
{
edge = std::move(wall);
closest = dist;
nearCross = crossPoint;
nearObject = object.first;
}
}
}
// Sort hits by descending of distance
std::sort(v_rayCastStruct.begin(), v_rayCastStruct.end(), [](const RayCastStructure& lh, const RayCastStructure& rh) { return lh.distance > rh.distance; });
// collision
if (!nearObject.empty() && COLLISION_AREA >= closest)
{
CollisionInformation newCollision;
newCollision.distance = (nearCross - position()).abs();
newCollision.edge = std::move(edge);
newCollision.collisionPoint = nearCross;
newCollision.height = W_world[nearObject]->height();
allCollisions.push_back(newCollision);
}
// Bonus collision
if (!nearObject.empty() && (W_world[nearObject]->position() - position()).abs() <= COLLISION_AREA && W_world[nearObject]->type() == ObjectType::Bonus)
{
if(reinterpret_cast<Bonus*>(W_world[nearObject].get())->bonusType() == BonusType::TreatmentBonus)
client->shoot(getName(), -100, 1);
if(reinterpret_cast<Bonus*>(W_world[nearObject].get())->bonusType() == BonusType::AmmunitionBonus)
v_weapons[i_selectedWeapon].add(30);
if(reinterpret_cast<Bonus*>(W_world[nearObject].get())->bonusType() == BonusType::SpeedBonus) {
if (d_walkSpeed < 7)
d_walkSpeed += 0.5;
if(d_jumpSpeed < 10)
d_jumpSpeed++;
}
W_world.freeBonusPoint(W_world[nearObject]->position()); // free this place for another bonus
W_world[nearObject]->setPosition(W_world.getBonusPoint()); // change the position of this bonus and mark this
}
}
void Enemy::hiddenObjectsRayCrossed(const pair<Point2D, Point2D>& ray, const std::string& name)
{
Object2D* obj = nullptr;
std::pair<Point2D, Point2D> edge;
double len = 0;
Point2D nearCross = ray.second;
for (auto object : W_world.objects())
{
if (object.second == nullptr || object.first == name || object.second.get()->nodes().size() < 2)
continue;
// Check collision
Point2D crossPoint = ray.second;
// If object hitted and near closer than already finded - rember it
pair<Point2D, Point2D> wall;
if (object.second.get()->cross(ray, wall, crossPoint, len) && (nearCross - ray.first).abs() > (crossPoint - ray.first).abs())
{
nearCross = std::move(crossPoint);
obj = object.second.get();
edge = std::move(wall);
}
}
// If something was hitted close enough - write it
if (obj)
{
CollisionInformation newCollision;
newCollision.distance = (nearCross - position()).abs();
newCollision.edge = std::move(edge);
newCollision.collisionPoint = nearCross;
newCollision.height = obj->height();
allCollisions.push_back(newCollision);
}
}
void Enemy::makeDecision(double elapsedTime) {
vector<double> outLayer = N_network.getOutput();
if(outLayer.empty())
return;
// -------- MAKE DECISION --------
// enemy displacement
double dx = 0;
double dy = 0;
double d_sin = sin(d_direction);
double d_cos = cos(d_direction);
// change direction
d_direction += (outLayer[2] - 0.5) * d_fieldOfView;
client->localPlayer()->chDir(d_direction);
// fire in d_direction
if(outLayer[3] >= 0.5)
fire();
dx += d_sin * (outLayer[0] - 0.5) * 2 + d_cos * (outLayer[1] - 0.5) * 2;
dy += -d_cos * (outLayer[0] - 0.5) * 2 + d_sin * (outLayer[1] - 0.5) * 2;
shiftPrecise({ dx * d_walkSpeed * elapsedTime * (health() / 100), dy * d_walkSpeed * elapsedTime * (client->localPlayer()->health() / 100) });
}
double Enemy::distanceToBonus(BonusType type) {
double l = d_depth;
for (auto& b : W_world.bonuses())
{
if (b.expired())
continue;
shared_ptr<Bonus> pb = b.lock();
if (pb->bonusType() == type)
if ((position() - pb->position()).abs() < l)
l = (position() - pb->position()).abs();
}
return l;
}
double Enemy::angleToBonus(BonusType type) {
double angle = -d_fieldOfView / 2;
double l = d_depth;
for (auto& b : W_world.bonuses())
{
if (b.expired())
continue;
shared_ptr<Bonus> pb = b.lock();
if (pb->bonusType() == type)
if ((position() - pb->position()).abs() < l) {
l = (position() - pb->position()).abs();
angle = (angleBetween(pb) + d_fieldOfView / 2) / d_fieldOfView;
}
}
return angle;
}
double Enemy::angleBetween(std::shared_ptr<Object2D> obj) const {
if (obj == nullptr)
return -d_fieldOfView;
Point2D viewDir = { cos(d_direction), sin(d_direction) };
Point2D objDir = (obj->position() - position()).normalize();
if (viewDir * objDir < 0)
return -d_fieldOfView / 2;
double angle = viewDir.getAngle(objDir);
if (angle < -d_fieldOfView / 2)
angle = -d_fieldOfView / 2;
if (angle > d_fieldOfView / 2)
angle = d_fieldOfView / 2;
return angle;
}
void Enemy::update(double dt, double elapsedTime) {
if(!client->isWorking())
return;
v_weapons[i_selectedWeapon].setTimeMult(dt/elapsedTime );
N_network.clearInput();
// 16 distances
updateDistances();
double near = d_depth;
double enemyAngle = -d_fieldOfView/2;
for(auto& p : client->localPlayer()->players()) {
//double dist = distanceTo(p.first);
if(client->localPlayer()->getName() == p.second->getName())
continue;
if((p.second->position() - position()).abs() > d_depth)
continue;
bool canSee = false;
Point2D enemyDirection = (p.second->position() - position()).normalize();
pair<Point2D, Point2D> segment1 = { {x(), y()}, {x() + d_depth*enemyDirection.x, y() + d_depth*enemyDirection.y} };
std::vector<RayCastStructure> v_rayCastStructure;
objectsRayCrossed(segment1, v_rayCastStructure);
if(!v_rayCastStructure.empty() && v_rayCastStructure.back().object->getName() == p.first)
canSee = true;
double dist = (p.second->position() - position()).abs();
if(dist < near && canSee) {
near = dist;
//enemyAngle = (angleBetween(p.second) + d_fieldOfView/2)/d_fieldOfView;
enemyAngle = angleBetween(p.second);
}
if(enemyAngle == -d_fieldOfView/2 || enemyAngle == d_fieldOfView/2)
near = d_depth;
}
if(enemyAngle != enemyAngle)
enemyAngle = 0;
/*
// distance to the ammunition
N_network.addInput(distanceToBonus(BonusType::AmmunitionBonus) / d_depth);
// distance to the speedBonus
N_network.addInput(distanceToBonus(BonusType::SpeedBonus) / d_depth);
// distance to the health
N_network.addInput(distanceToBonus(BonusType::TreatmentBonus) / d_depth);
// angle to the ammunition
N_network.addInput(angleToBonus(BonusType::AmmunitionBonus));
// angle to the speedBonus
N_network.addInput(angleToBonus(BonusType::SpeedBonus));
// angle to the health
N_network.addInput(angleToBonus(BonusType::TreatmentBonus));
// health
N_network.addInput((double)client->localPlayer()->health() / 100.0);
*/
// distance to the near enemy
N_network.addInput(near / d_depth);
// angle to the near enemy
N_network.addInput((enemyAngle + d_fieldOfView/2)/d_fieldOfView);
// ammunition balance
N_network.addInput((NeuralNetwork::sigmoid((double)v_weapons[i_selectedWeapon].balance()/10.0) - 0.5)*2);
//d_direction += enemyAngle;
// Based on resulting v_inLayer enemy needs to makeDecision
makeDecision(dt);
if(client != nullptr && client->isWorking()) {
client->update();
}
if(client->localPlayer() != nullptr) {
//client->localPlayer()->setPosition(position());
setPosition(client->localPlayer()->position());
}
}
void Enemy::shiftPrecise(Point2D vector) {
for (auto& c : allCollisions)
{
Point2D edgeVector = c.edge.second - c.edge.first;
Point2D normal = { edgeVector.y, -edgeVector.x };
normal = normal.normalize();
Point2D toWallVector = c.edge.first + c.edge.second - p_position * 2;
if(normal * toWallVector > 0)
normal = normal * (-1);
double scalar = vector * normal;
if (scalar < 0 && abs(c.distance - abs(scalar)) < COLLISION_DISTANCE && vPos() + d_eyesHeight < c.height)
{
vector.x -= normal.x * scalar;
vector.y -= normal.y * scalar;
}
}
p_path += vector;
d_path += vector.abs();
shift(vector);
client->localPlayer()->shift(vector);
//client->localPlayer()->setPosition(position());
}