forked from gamerlily/Cogstruction
-
Notifications
You must be signed in to change notification settings - Fork 1
/
cog_array_stuff.py
488 lines (439 loc) · 18.6 KB
/
cog_array_stuff.py
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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
"""
Cogstruction: Optimizing cog arrays in Legends of Idleon
Copyright (C) 2021 Michael P. Lane
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
"""
import copy
import random
import numpy as np
from cog_types import Boost_Cog, Col_Cog, Row_Cog
from constants import NUM_COGS_HORI, NUM_COGS_VERT, TOTAL_COORDS
from coords import Coords
"""
- `Empties_Set.empties' should be a `set'.
- `Empties_Set.coords_list' is a list of all the non-empty coords in the array.
- There should be one `Empties_Set' per cog array template.
"""
class Empties_Set:
def __init__(self,empties):
self.empties = empties
self.coords_list = []
for y in range(NUM_COGS_VERT):
for x in range(NUM_COGS_HORI):
coords = Coords(x, y)
if coords not in self.empties:
self.coords_list.append(coords)
def __eq__(self, other):
return self.empties == other.empties
def __ne__(self, other):
return not(self == other)
def __contains__(self, coords):
return coords in self.empties
def __len__(self):
return len(self.empties)
"""
- `excludes_dict[type(cog)]' is a `set' of all coordinates where `cog' should not be placed.
- For example, if `cog' is of type `Up_Cog', then `excludes_dict[type(cog)]' should contain all coords on the top row of
the array.
- This dict is not necessary for the genetic algorithm to find an optimal array. It merely improves the convergence rate.
"""
def get_excludes_dict(empties_set, cogs):
cog_array = Cog_Array(empties_set)
excludes_dict = {}
for cog in cogs:
if type(cog) not in excludes_dict and isinstance(cog, Boost_Cog) and not isinstance(cog, Row_Cog) and not isinstance(cog, Col_Cog):
excludes_dict[type(cog)] = set()
for coords in Coords_Iter(cog_array):
num_oob_neighbors = sum((adj_coords.is_out_of_bounds()) for adj_coords in cog.get_influence(coords))
if num_oob_neighbors > cog.get_max_oob_neighbors():
excludes_dict[type(cog)].add(coords)
return excludes_dict
"""
A cog array consists of:
- array: A `numpy.ndarray' of `Cogs' placed on the cog array.
- empties_set: An `Empties_Set' of `Coords' that the user has not yet unlocked using flaggies. There is only one per
cog array template.
- flaggies: A collection of `Coords' where the user currently has flaggies placed.
- spares: A spare collection of `Cogs'.
- excludes_dict: A `dict` of `sets'. Each key of `excludes_dict' is a `Cog` subtype. Each `set' consists of `Coords' where
`Cogs' should not be placed. There is only one per cog array template.
"""
class Cog_Array:
def __init__(self, empties_set = None, flaggies = None, excludes_dict = None):
self.array = np.empty((NUM_COGS_HORI, NUM_COGS_VERT), dtype=np.dtype(object))
self.empties_set = empties_set if empties_set is not None else Empties_Set(set())
self.flaggies = set(flaggies) if flaggies is not None else set()
self.spares = set()
self.build_rate = self.flaggy_rate = self.total_exp_mult = None
self.excludes_dict = excludes_dict if excludes_dict is not None else {}
self._num_occupied = 0
"""
- Randomly places cogs on the cog array. Any leftover cogs are added to `self.spares'.
- If `cog in cogs', then this method will try to place `cog' where `self.excludes(coords, cog)' is `False'. However,
depending on the shape of the cog array and the given `cogs', this will not always be possible, but the method will
always return.
"""
def instantiate_randomly(self,cogs):
if self.get_num_spares() != 0 or self.get_num_occupied() != 0:
raise RuntimeError("Cog_Array must be empty before instatiating.")
self.extend_spares(cogs)
for coords in Coords_Iter(self,True):
if self.get_num_spares() > 0:
self.move_random_cog_from_spares(coords)
else:
return self
return self
"""
Mostly used for copying.
"""
def instantiate_from_array(self,array):
if self.get_num_spares() != 0 or self.get_num_occupied() != 0:
raise RuntimeError("Cog_Array must be empty before instatiating.")
self.array = array
self._num_occupied = sum((self.array[i,j] is not None) for i,j in np.ndindex((NUM_COGS_HORI,NUM_COGS_VERT)))
return self
"""
- Randomly place cogs from `self.spares' on non-empty coords where `self.is_occupied(coords)' is `False'.
- This method will not remove or replace cogs that have already been placed on the cog array.
"""
def randomize(self):
self._reset_rates()
for coords in Coords_Iter(self,True):
if not self.is_occupied(coords):
self.move_random_cog_from_spares(coords)
return self
"""
Place a cog by coords.
"""
def __setitem__(self, coords, cog):
if coords.is_out_of_bounds() or coords in self.empties_set:
raise RuntimeError("invalid coords")
if not self.is_occupied(coords):
self._num_occupied += 1
self.array[coords.x, coords.y] = cog
self._reset_rates()
"""
Get a cog by coords.
"""
def __getitem__(self, coords):
if coords.is_out_of_bounds() or coords in self.empties_set:
return None
return self.array[coords.x, coords.y]
def __str__(self):
ret = ""
line = ""
i = 1
for coords in Coords_Iter():
if coords.x == 0 and coords.y > 0:
ret = line + "\n\n" + ret
line = ""
if coords in self.empties_set:
line += "E "
elif not self.is_occupied(coords):
line += "e "
else:
line += str(i) + " "*(3-int(np.log10(i)))
i+=1
ret = line + "\n\n" + ret
ret = self.str_with_abbr() + "\n\n\n" + ret
for i,(coords,cog) in enumerate(self):
ret += (
("Cog %d\n" %(i+1)) +
("Coords: %s\n" %coords) +
(str(cog)) +
"\n\n\n"
)
for cog in self.spares:
ret += ("Spare Cog\n" + str(cog) + "\n\n\n")
return ret.strip()
def __iter__(self):
return ((coords,self[coords]) for coords in Coords_Iter(self))
def __copy__(self):
cog_array = Cog_Array(self.empties_set, None, self.excludes_dict)
cog_array.instantiate_from_array(copy.copy(self.array))
cog_array.extend_spares(copy.copy(self.spares))
return cog_array
def __eq__(self, other):
if self.empties_set != other.empties_set or self.spares != other.spares or self.flaggies != other.flaggies:
return False
for coords,cog in self:
if cog != other[coords]:
return False
return True
def __ne__(self, other):
return not(self==other)
def csv_record(self):
ret = ""
line = ""
i = 1
ret += "ID,Xpos,Ypos,Type,Name,Build_Rate,Flaggy_Rate,Exp_Mul,Build_r_Boost,Flaggy_r_boost,Flaggy_s_boost,Exp_boost\n"
for i, (coords, cog) in enumerate(self):
ret += (
("%d," % (i + 1)) +
("%d," % coords.x) +
("%d," % coords.y) +
(cog.csv_record()) +
"\n"
)
for cog in self.spares:
ret += ("Spare,Spare,Spare," + cog.csv_record() + "\n")
return ret.strip()
"Call it and see =)"
def str_with_abbr(self):
ret = ""
line = ""
for coords in Coords_Iter():
if coords.x == 0 and coords.y > 0:
ret = line + "\n\n" + ret
line = ""
if coords in self.empties_set:
line+= "E "
else:
if not self.is_occupied(coords):
line += "E "
else:
cog = self[coords]
line += cog.get_abbr() + " "
return line + "\n\n" + ret
"""
If `self.excludes(coords,cog)' is true, then `cog' should not be placed at `coords'. It sometimes must be though,
depending on the shape of the array and the cogs used to initialize it.
"""
def excludes(self,coords,cog):
if not isinstance(cog, Boost_Cog) or type(cog) not in self.excludes_dict:
return False
return coords in self.excludes_dict[type(cog)]
"""
Only returns non-empty coords.
"""
def get_random_coords(self,k=1):
ret = []
for coords in Coords_Iter(self,True,k):
ret.append(coords)
if k == 1:
return ret[0]
else:
return ret
"""
- This method blends two input `Cog_Arrays'. The blended `Cog_Array' is called `child'.
- For each non-empty `coord' of `self', the cog `child[coord]' will usually be either `self[coord]' or 'other[coord]'.
- The decision of whether `child[coord]' is equal to either `self[coord]' or 'other[coord]' is made randomly. However,
the odds are not 1:1. The exact probability is based off four floats
> `self[coords].get_strength(coords)'
> `other[coords].get_strength(coords)'
> `self[coords].get_average_std_obj()[0]' and
> `other[coords].get_average_std_obj()[0]'.
- Under certain circumstances, `child[coord]' will be neither `self[coord]' nor `other[coord]'. This will happen if
both of these cogs have already been placed somewhere else in `child'.
"""
def cross_breed(self,other):
child = copy.copy(self)
child.move_all_to_spares()
for coords in Coords_Iter(self, True):
self_strength = self[coords].get_strength(coords)*self[coords].get_average_std_obj()[0]
other_strength = other[coords].get_strength(coords)*other[coords].get_average_std_obj()[0]
self_weight = self_strength/(self_strength + other_strength)
if random.uniform(0,1) <= self_weight:
if self[coords] in child.spares:
child.move_cog_from_spares(coords, self[coords])
elif other[coords] in child.spares:
child.move_cog_from_spares(coords, other[coords])
else:
child.move_random_cog_from_spares(coords)
else:
if other[coords] in child.spares:
child.move_cog_from_spares(coords, other[coords])
elif self[coords] in child.spares:
child.move_cog_from_spares(coords, self[coords])
else:
child.move_random_cog_from_spares(coords)
return child
"""
- This method produces a new `Cog_Array' called `child'.
- First, randomly choose a cog placed in `self'. Then, choose a random cog from `self.spares'. Switch these two.
"""
def one_point_mutation(self):
if self.get_num_spares() == 0:
raise Cog_Not_Found_Error
child = copy.copy(self)
coords = self.get_random_coords()
old_cog = child[coords]
child[coords] = None
child.move_random_cog_from_spares(coords)
child.add_spare(old_cog)
return child,coords,old_cog
"""
- Switch two cogs that are currently placed in the array.
- This method ignores the cog shelf, `self.spares`.
"""
def two_point_mutation(self):
child = copy.copy(self)
coords1,coords2 = child.get_random_coords(2)
cog1 = child[coords1]
child[coords1] = child[coords2]
child[coords2] = cog1
return child, coords1, coords2
"""
- Move `cog' from `self.spares' to `coords'.
- If `coords' is already occupied by a different cog, then move that cog to `self.spares' before replacing with `cog'.
- This method ignores the return value of `self.excludes(coords, cog)'.
"""
def move_cog_from_spares(self, coords, cog):
if cog not in self.spares:
raise Cog_Not_Found_Error
self.spares.remove(cog)
self.move_cog_to_spares(coords)
self[coords] = cog
self._reset_rates()
return self
"""
- Move a random cog from `self.spares' to `coords' of `self'.
- If `coords' is already occupied by a different cog, then move that cog to `self.spares' before replacing with the
new random cog.
- This method will attempt to choose a `cog' such that `self.excludes(coords,cog)' is `False', whenever this is
possible.
"""
def move_random_cog_from_spares(self,coords):
if self.get_num_spares() == 0:
raise Cog_Not_Found_Error
attempts = 0
while attempts < len(self.spares):
cog = random.sample(self.spares, 1)[0]
if not self.excludes(coords,cog):
break
attempts += 1
else:
cog = random.sample(self.spares, 1)[0]
self.move_cog_from_spares(coords,cog)
return cog
def move_cog_to_spares(self,coords):
if self.is_occupied(coords):
self.add_spare(self[coords])
self.array[coords.x,coords.y] = None
self._reset_rates()
self._num_occupied -= 1
return self
def move_all_to_spares(self):
for coords in Coords_Iter(self):
self.move_cog_to_spares(coords)
return self
def add_spare(self,cog):
self.spares.add(cog)
return self
def extend_spares(self,cogs):
for cog in cogs:
self.add_spare(cog)
return self
def is_occupied(self,coords):
return self[coords] is not None
def is_flaggy(self,coords):
return coords in self.flaggies
def _reset_rates(self):
self.build_rate = self.flaggy_rate = self.total_exp_mult = None
"""
Calculate the total build rate of the array.
"""
def get_build_rate(self):
if self.build_rate is None:
total = 0
for coords, cog in self:
if self.is_occupied(coords):
if isinstance(cog, Boost_Cog):
rate = cog.build_rate_boost
if rate > 0:
for adj_cog_coords in cog.get_influence(coords):
if self.is_occupied(adj_cog_coords):
adj_cog = self[adj_cog_coords]
total += adj_cog.build_rate * rate
total += cog.build_rate
self.build_rate = total
return self.build_rate
"""
- Calculate the total flaggy rate.
- Due to a bug in Lava's implementation, the ''player exp'' adjacency bonuses give a multiplicative bonus to adjacent
flaggy speeds.
- The method below accounts for that bug. (TODO)
- The ''flaggy speed'' adjacency bonus does nothing, which is likewise a bug.
"""
def get_flaggy_rate(self):
if self.flaggy_rate is None:
total_rate = total_speed = 0
for coords, cog in self:
if self.is_occupied(coords):
if isinstance(cog, Boost_Cog):
rate = cog.flaggy_rate_boost
if rate > 0:
for adj_cog_coords in cog.get_influence(coords):
if self.is_occupied(adj_cog_coords):
adj_cog = self[adj_cog_coords]
total_rate += adj_cog.flaggy_rate * rate
speed = cog.flaggy_speed_boost
if speed > 0:
for adj_cog_coords in cog.get_influence(coords):
if self.is_flaggy(adj_cog_coords):
total_speed += speed/len(self.flaggies)
total_rate += cog.flaggy_rate
self.flaggy_rate = total_rate*(1+total_speed)
return self.flaggy_rate
"""
- Calculate the total exp multiplier.
- Due to a bug in Lava's implementation, the ''player exp'' adjacency bonuses give a multiplicative bonus to adjacent
flaggy speeds.
"""
def get_total_exp_mult(self):
if self.total_exp_mult is None:
self.total_exp_mult = sum((cog.exp_mult if self.is_occupied(coords) else 0.0) for coords, cog in self)
# if self.exp_rate is None:
# total_rate = sum((cog.exp_rate if self.is_occupied(coords) else 0.0) for coords,cog in self)
# total_bonus = 0.0
# for coords, cog in self:
# bonus = cog.exp_boost
# if bonus > 0:
# for adj_coords in cog.get_influence(coords):
# if self.is_occupied(adj_coords):
# cog = self[adj_coords]
# if isinstance(cog, Character):
# total_bonus += cog.exp_gain * bonus
# self.exp_rate = total_rate + total_bonus
return self.total_exp_mult
def get_num_spares(self):
return len(self.spares)
def get_num_non_empty(self):
return TOTAL_COORDS - len(self.empties_set)
"""
Returns the total number of cogs in `self.spares` if every non-empty coords of `self` is occupied.
"""
def get_num_extras(self):
return self.get_num_spares() - self.get_num_non_empty() + self.get_num_occupied()
def get_num_occupied(self):
return self._num_occupied
"""
Iterates through all the non-empty coordinates of an input `Cog_Array'.
"""
class Coords_Iter:
def __init__(self, cog_array = None, randomize_order = False, length =TOTAL_COORDS):
self.cog_array = cog_array if cog_array is not None else Cog_Array()
self.randomize_order = randomize_order
self.curr_index = None
self.coords_list = self.cog_array.empties_set.coords_list
self.length = min(length,len(self.coords_list))
def __iter__(self):
self.curr_index = 0
if self.randomize_order:
self.coords_list = random.sample(self.coords_list, self.length)
return self
def __next__(self):
if self.curr_index >= len(self.coords_list):
raise StopIteration
next_coords = self.coords_list[self.curr_index]
self.curr_index += 1
return next_coords
class Cog_Not_Found_Error(RuntimeError):
pass