-
Notifications
You must be signed in to change notification settings - Fork 0
/
Warrior.cpp
98 lines (86 loc) · 2.62 KB
/
Warrior.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
#include "Warrior.h"
#include "Model.h"
#include "Structure.h"
#include "Utility.h"
#include <iostream>
using std::cout; using std::endl;
using std::shared_ptr; using std::weak_ptr;
using std::string;
Warrior::Warrior(const string& name_, Point location_, int strength_, double range_) :
Agent(name_, location_), strength(strength_), range(range_),
attacking(false)
{}
void Warrior::update()
{
Agent::update();
if(!is_alive() || !attacking) {
return;
}
auto target_ptr = target.lock();
if(!target_ptr || !target_ptr -> is_alive()) {
// If the target disappears or the target is still there but not alive,
// stop attacking and forget about the target.
cout << get_name() << ": Target is dead" << endl;
attacking = false;
target.reset();
return;
}
double distance = cartesian_distance(get_location(), target_ptr -> get_location());
if(distance > range) {
cout << get_name() << ": Target is now out of range" << endl;
attacking = false;
return;
}
// print proper attacking word and impose hit on the target
dispatch_hit();
if(!target_ptr -> is_alive()) {
cout << get_name() << ": I triumph!" << endl;
attacking = false;
target.reset();
}
}
void Warrior::start_attacking(shared_ptr<Agent> target_ptr)
{
if(target_ptr == shared_from_this()) {
throw Error(get_name() + ": I cannot attack myself!");
} else if(!target_ptr -> is_alive()) {
throw Error(get_name()+ ": Target is not alive!");
}
double distance = cartesian_distance(get_location(), target_ptr -> get_location());
if(distance > range) {
throw Error(get_name() + ": Target is out of range!");
}
initiate_attacking("I'm attacking!", target_ptr);
}
void Warrior::stop()
{
cout << get_name() << ": Don't bother me" << endl;
}
void Warrior::describe() const
{
Agent::describe();
if(!attacking) {
cout << " Not attacking" << endl;
return;
}
auto target_ptr = target.lock();
if(target_ptr) {
cout << " Attacking " << target_ptr -> get_name() << endl;
} else {
cout << " Attacking dead target" << endl;
}
}
void Warrior::initiate_attacking(const string& message, shared_ptr<Agent> target_ptr)
{
cout << get_name() << ": " << message << endl;
target = target_ptr;
attacking = true;
}
bool Warrior::can_counter_attack(shared_ptr<Agent> attacker) const
{
return !attacking && is_alive() && attacker -> is_alive();
}
bool Warrior::can_run_away(shared_ptr<Agent> attacker) const
{
return is_alive() && attacker -> is_alive();
}