Oolite
Loading...
Searching...
No Matches
OORoleSet.m
Go to the documentation of this file.
1/*
2
3OORoleSet.m
4
5
6Copyright (C) 2007-2013 Jens Ayton
7
8Permission is hereby granted, free of charge, to any person obtaining a copy
9of this software and associated documentation files (the "Software"), to deal
10in the Software without restriction, including without limitation the rights
11to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12copies of the Software, and to permit persons to whom the Software is
13furnished to do so, subject to the following conditions:
14
15The above copyright notice and this permission notice shall be included in all
16copies or substantial portions of the Software.
17
18THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24SOFTWARE.
25
26*/
27
28#import "OORoleSet.h"
29
31#import "OOLogging.h"
32#import "OOStringParsing.h"
33
34@interface OORoleSet (OOPrivate)
35
36- (id)initWithRolesAndProbabilities:(NSDictionary*)dict;
37
38@end
39
40@implementation OORoleSet
41
42+ (instancetype)roleSetWithString:(NSString*)roleString
43{
44 return [[[self alloc] initWithRoleString:roleString] autorelease];
45}
46
47+ (instancetype)roleSetWithRole:(NSString*)role probability:(float)probability
48{
49 return [[[self alloc] initWithRole:role probability:probability] autorelease];
50}
51
52- (id)initWithRoleString:(NSString*)roleString
53{
54 NSDictionary* dict = nil;
55
57 return [self initWithRolesAndProbabilities:dict];
58}
59
60- (id)initWithRole:(NSString*)role probability:(float)probability
61{
62 NSDictionary* dict = nil;
63
64 if (role != nil && 0 <= probability) {
65 dict = [NSDictionary dictionaryWithObject:[NSNumber numberWithFloat:probability] forKey:role];
66 }
67 return [self initWithRolesAndProbabilities:dict];
68}
69
70- (void)dealloc
71{
72 [_roleString autorelease];
73 [_rolesAndProbabilities autorelease];
74 [_roles autorelease];
75
76 [super dealloc];
77}
78
79- (NSString*)description
80{
81 return [NSString stringWithFormat:@"<%@ %p>{%@}", [self class], self, [self roleString]];
82}
83
84- (BOOL)isEqual:(id)other
85{
86 if ([other isKindOfClass:[OORoleSet class]]) {
87 return [_rolesAndProbabilities isEqual:[other rolesAndProbabilities]];
88 } else
89 return NO;
90}
91
92- (NSUInteger)hash
93{
94 return [_rolesAndProbabilities hash];
95}
96
97- (id)copyWithZone:(NSZone*)zone
98{
99 // Note: since object is immutable, a copy is no different from the original.
100 return [self retain];
101}
102
103- (NSString*)roleString
104{
105 NSArray* roles = nil;
106 NSString* role = nil;
107 float probability;
108 NSMutableString* result = nil;
109 BOOL first = YES;
110
111 if (_roleString == nil) {
112 // Construct role string. We always do this so that it's in a normalized form.
113 result = [NSMutableString string];
114 roles = [self sortedRoles];
115 foreach (role, roles) {
116 if (!first)
117 [result appendString:@" "];
118 else
119 first = NO;
120
121 [result appendString:role];
122
123 probability = [self probabilityForRole:role];
124 if (probability != 1.0f) {
125 [result appendFormat:@"(%g)", probability];
126 }
127 }
128
129 _roleString = [result copy];
130 }
131
132 return _roleString;
133}
134
135- (BOOL)hasRole:(NSString*)role
136{
137 return role != nil && [_rolesAndProbabilities objectForKey:role] != nil;
138}
139
140- (float)probabilityForRole:(NSString*)role
141{
142 return [_rolesAndProbabilities oo_floatForKey:role defaultValue:0.0f];
143}
144
145- (BOOL)intersectsSet:(id)set
146{
147 if ([set isKindOfClass:[OORoleSet class]])
148 set = [set roles];
149 else if (![set isKindOfClass:[NSSet class]])
150 return NO;
151
152 return [[self roles] intersectsSet:set];
153}
154
155- (NSSet*)roles
156{
157 if (_roles == nil) {
158 _roles = [[NSSet alloc] initWithArray:[_rolesAndProbabilities allKeys]];
159 }
160 return _roles;
161}
162
163- (NSArray*)sortedRoles
164{
165 return [[_rolesAndProbabilities allKeys] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
166}
167
168- (NSDictionary*)rolesAndProbabilities
169{
171}
172
173- (NSString*)anyRole
174{
175 NSString* role = nil;
176 float prob, selected;
177
178 selected = randf() * _totalProb;
179 prob = 0.0f;
180
181 if ([_rolesAndProbabilities count] == 0)
182 return nil;
183
185 {
186 prob += [_rolesAndProbabilities oo_floatForKey:role];
187 if (selected <= prob)
188 break;
189 }
190 if (role == nil) {
191 role = [[self roles] anyObject];
192 OOLog(@"roleSet.anyRole.failed", @"Could not get a weighted-random role from role set %@, returning unweighted selection %@. TotalProb: %g, selected: %g, prob at end: %f", self, role, _totalProb, selected, prob);
193 }
194 return role;
195}
196
197- (id)roleSetWithAddedRoleIfNotSet:(NSString*)role probability:(float)probability
198{
199 NSMutableDictionary* dict = nil;
200
201 if (role == nil || probability < 0 || ([self hasRole:role] && [self probabilityForRole:role] == probability)) {
202 return [[self copy] autorelease];
203 }
204
205 dict = [[_rolesAndProbabilities mutableCopy] autorelease];
206 [dict setObject:[NSNumber numberWithFloat:probability] forKey:role];
207 return [[[[self class] alloc] initWithRolesAndProbabilities:dict] autorelease];
208}
209
210- (id)roleSetWithAddedRole:(NSString*)role probability:(float)probability
211{
212 NSMutableDictionary* dict = nil;
213
214 if (role == nil || probability < 0 || [self hasRole:role]) {
215 return [[self copy] autorelease];
216 }
217
218 dict = [[_rolesAndProbabilities mutableCopy] autorelease];
219 [dict setObject:[NSNumber numberWithFloat:probability] forKey:role];
220 return [[[[self class] alloc] initWithRolesAndProbabilities:dict] autorelease];
221}
222
223- (id)roleSetWithRemovedRole:(NSString*)role
224{
225 NSMutableDictionary* dict = nil;
226
227 if (![self hasRole:role])
228 return [[self copy] autorelease];
229
230 dict = [[_rolesAndProbabilities mutableCopy] autorelease];
231 [dict removeObjectForKey:role];
232 return [[[[self class] alloc] initWithRolesAndProbabilities:dict] autorelease];
233}
234
235@end
236
237@implementation OORoleSet (OOPrivate)
238
239- (id)initWithRolesAndProbabilities:(NSDictionary*)dict
240{
241 NSString* role = nil;
242 float prob;
243
244 if (dict == nil) {
245 [self release];
246 return nil;
247 }
248
249 self = [super init];
250 if (self == nil)
251 return nil;
252
253 // Note: _roles and _roleString are derived on the fly as needed.
254 // MKW 20090815 - if we are re-initialising this OORoleSet object, we need
255 // to ensure that _roles and _roleString are cleared.
256 // Why would we be re-initing? That's never valid. -- Ahruman 2010-02-06
257 assert(_roles == nil && _roleString == nil);
258
259 NSMutableDictionary* tDict = [[dict mutableCopy] autorelease];
260 float thargProb = [dict oo_floatForKey:@"thargon" defaultValue:0.0f];
261
262 if (thargProb > 0.0f && [dict objectForKey:@"EQ_THARGON"] == nil) {
263 [tDict setObject:[NSNumber numberWithFloat:thargProb] forKey:@"EQ_THARGON"];
264 [tDict removeObjectForKey:@"thargon"];
265 }
266
267 _rolesAndProbabilities = [tDict copy];
268
269 foreachkey(role, dict)
270 {
271 prob = [dict oo_floatForKey:role defaultValue:-1];
272 if (prob < 0) {
273 OOLog(@"roleSet.badValue", @"Attempt to create a role set with negative or non-numerical probability for role %@.", role);
274 [self release];
275 return nil;
276 }
277
278 _totalProb += prob;
279 }
280
281 return self;
282}
283
284@end
285
286NSDictionary* OOParseRolesFromString(NSString* string)
287{
288 NSMutableDictionary* result = nil;
289 NSArray* tokens = nil;
290 NSUInteger i, count;
291 NSString* role = nil;
292 float probability;
293 NSScanner* scanner = nil;
294
295 // Split string at spaces, sanity checks, set-up.
296 if (string == nil)
297 return nil;
298
299 tokens = ScanTokensFromString(string);
300 count = [tokens count];
301 if (count == 0)
302 return nil;
303
304 result = [NSMutableDictionary dictionaryWithCapacity:count];
305
306 // Scan tokens, looking for probabilities.
307 for (i = 0; i != count; ++i) {
308 role = [tokens objectAtIndex:i];
309
310 probability = 1.0f;
311 if ([role rangeOfString:@"("].location != NSNotFound) {
312 scanner = [[NSScanner alloc] initWithString:role];
313 [scanner scanUpToString:@"(" intoString:&role];
314 [scanner scanString:@"(" intoString:NULL];
315 if (![scanner scanFloat:&probability])
316 probability = 1.0f;
317 // Ignore rest of string
318
319 [scanner release];
320 }
321
322 // shipKey roles start with [ so other roles can't
323 if (0 <= probability && ![role hasPrefix:@"["]) {
324 [result setObject:[NSNumber numberWithFloat:probability] forKey:role];
325 }
326 }
327
328 if ([result count] == 0)
329 result = nil;
330 return result;
331}
#define foreachkey(VAR, DICT)
#define OOLog(class, format,...)
Definition OOLogging.h:84
unsigned count
return nil
NSDictionary * OOParseRolesFromString(NSString *string)
Definition OORoleSet.m:286
NSDictionary * OOParseRolesFromString(NSString *string)
Definition OORoleSet.m:286
NSMutableArray * ScanTokensFromString(NSString *values)
void dealloc()
Definition OORoleSet.m:70
NSString * description()
Definition OORoleSet.m:79
NSSet * roles()
Definition OORoleSet.m:155
NSArray * sortedRoles()
Definition OORoleSet.m:163
float _totalProb
Definition OORoleSet.h:39
NSString * anyRole()
Definition OORoleSet.m:173
NSDictionary * rolesAndProbabilities()
Definition OORoleSet.m:168
NSString * roleString()
Definition OORoleSet.m:103
NSDictionary * _rolesAndProbabilities
Definition OORoleSet.h:37
NSUInteger hash()
Definition OORoleSet.m:92
NSString * _roleString
Definition OORoleSet.h:36
NSSet * _roles
Definition OORoleSet.h:38
float probabilityForRole:(NSString *role)
Definition OORoleSet.m:140
id initWithRolesAndProbabilities:(NSDictionary *dict)
Definition OORoleSet.m:239
float randf(void)