forked from Whales/Cataclysm2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvar_string.cpp
More file actions
69 lines (59 loc) · 1.41 KB
/
var_string.cpp
File metadata and controls
69 lines (59 loc) · 1.41 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
#include "var_string.h"
#include "stringfunc.h"
#include "rng.h"
Variable_string::Variable_string()
{
total_chance = 0;
}
Variable_string& Variable_string::operator=(const Variable_string& rhs)
{
strings = rhs.strings;
total_chance = rhs.total_chance;
return *this;
}
bool Variable_string::empty()
{
return strings.empty();
}
std::string Variable_string::pick()
{
if (strings.empty()) {
return "";
}
int roll = rng(1, total_chance);
for (int i = 0; i < strings.size(); i++) {
roll -= strings[i].chance;
if (roll <= 0) {
return strings[i].string;
}
}
return strings.back().string;
}
void Variable_string::add_string(int chance, std::string string)
{
add_string( String_chance(chance, string) );
}
void Variable_string::add_string(String_chance string)
{
total_chance += string.chance;
strings.push_back(string);
}
bool Variable_string::load_data(std::istream& data, std::string owner)
{
std::string ident;
String_chance tmp_chance;
while (data >> ident) {
if (no_caps( ident.substr(0, 2) ) == "w:") { // it's a weight, i.e. a chance
tmp_chance.chance = atoi( ident.substr(2).c_str() );
} else if (ident == "/") { // End of an option
add_string(tmp_chance);
tmp_chance.string = "";
tmp_chance.chance = 0;
} else {
tmp_chance.string += ident;
}
}
// Add the last one in the line to our list
add_string(tmp_chance);
return true;
}