-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdish.py
More file actions
806 lines (715 loc) · 33.1 KB
/
Copy pathdish.py
File metadata and controls
806 lines (715 loc) · 33.1 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
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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
import random
import math
import re
import statistics
from collections import deque
import pygame
import time
import networkx as nx
import matplotlib.pyplot as plt
import foodblock
import slimeblock
from foodblock import Foodblock
from slimeblock import Slimeblock
import pandas as pd
from IPython.display import display
class Dish:
def __init__(self, screen):
#declartion of variables
self.screen = screen
self.boundaryblocks = []
self.foodblocks = []
self.pheromones = []
self.slime_positions = []
self.fitness_vals = []
self.state = "start"
self.spawn_pt = (100, 400)
self.con_food_queue = []
self.con_rects = []
self.custom_boundary = []
self.next_gap = None
self.edges = []
#starting parameters that can be edited
self.diffusion_distance_threshold = 5
self.diffusion_threshold = 3.5
self.diffusion_decay_rate = 1.26
self.number_of_stalls = 0
self.increment_threshold = 1
#plot related variables
self.stats = None
self.plots = []
self.main_rect = pygame.Rect(225, 225, 510, 510)
self.main_rect.topleft = (10, 10)
#inserting food blocks
self.insert_food_block(200, 80)
self.target_food = self.foodblocks[0]
self.capital_slime = Slimeblock(idx=(100, 100), pheromone=0, decay=0.2)
self.insert_food_block(220, 120)
self.insert_food_block(400, 300)
self.insert_food_block(440, 210)
self.insert_food_block(120, 370)
self.insert_food_block(140, 370)
self.insert_food_block(230, 330)
self.insert_food_block(320, 430)
self.insert_food_block(450, 370)
#function to insert a food block
def insert_food_block(self, x, y, ph=7):
idx = (x, y)
foodblock = Foodblock(idx=idx, ph=ph)
self.foodblocks.append(foodblock)
#function to insert a slimeblock
def insert_slime_block(self, x, y, ph=0, decay=0.2):
idx = (x, y)
if ph == 0:
ph = 4 * (1 - decay)
slimeblock = Slimeblock(idx=idx, pheromone=ph, decay=0)
self.slime_positions.append(slimeblock)
return slimeblock
#handler function to handle states of simulation
def toggle_pause(self):
if self.state == "start":
self.state = "unpaused"
elif self.state == "paused":
print("changing state to unpaused")
self.state = "unpaused"
elif self.state == "unpaused":
print("changing state to paused")
self.state = "paused"
#updates at every game loop
def update(self):
if self.slime_positions:
if Foodblock.get_connected(self.target_food) == 0:
if self.target_food:
self.step(self.target_food)
else:
print("propagating")
self.propagate(1, (self.spawn_pt[0], self.spawn_pt[1]))
self.draw_everything()
#draw all items every frame
def draw_everything(self):
self.draw_border_line(10, self.main_rect[2] + 10, 'hor', 10)
self.draw_border_line(20, self.main_rect[2] + 10, 'ver', 10)
self.draw_border_line(20, self.main_rect[2] + 10, 'hor', self.main_rect[2])
self.draw_border_line(20, self.main_rect[2] + 10, 'ver', self.main_rect[2])
for b in self.boundaryblocks:
pygame.draw.rect(self.screen, (50, 50, 50), b)
for b in self.custom_boundary:
pygame.draw.rect(self.screen, (255, 0, 0), b)
for f in self.foodblocks:
pygame.draw.rect(self.screen, (0, 0, 255), Foodblock.get_rect(f))
for s in self.slime_positions:
pygame.draw.rect(self.screen, (0, 200, 0), Slimeblock.get_rect(s))
for c in self.con_rects:
pygame.draw.rect(self.screen, (49, 82, 155), c)
if self.state == "start":
pygame.draw.rect(self.screen, (0, 200, 0), pygame.Rect(self.spawn_pt[0], self.spawn_pt[1], 10, 10))
#begin the slime at these coords
def propagate(self, pop, spawn_coords):
x, y = spawn_coords
for i in range(pop):
self.insert_slime_block(x, y)
capital_slime = random.choice(self.get_slime_four_corners())
Slimeblock.set_pheromone(capital_slime, 5.5)
self.target_food = self.find_nearest_unconnected_food(capital_slime)
#function that draws the 'veins' efficent lines between nodes
def draw_efficent_path(self, sink_food):
#if it is not the first food
if len(self.con_food_queue) > 1:
source_food = self.find_nearest_connected_food(sink_food)
sx, sy = Foodblock.get_idx(source_food)
tx, ty = Foodblock.get_idx(sink_food)
self.add_edge(source_food, sink_food)
self.con_rects.append(pygame.Rect(sx, sy, 10, 10))
while (self.con_rects[-1].x, self.con_rects[-1].y) != (tx, ty):
print("connecting foods")
nx, ny = self.step_direction(self.con_rects[-1], sink_food)
next_block = pygame.Rect(nx, ny, 10, 10)
if next_block.collidelist(self.custom_boundary) != -1:
wall_gap = self.find_wall_gap(self.con_rects[-1])
print("wall gap is")
print(wall_gap)
print(self.con_rects[-1])
if wall_gap is not None and (self.con_rects[-1].x, self.con_rects[-1].y) != (
wall_gap.x, wall_gap.y):
nx, ny = self.step_direction(self.con_rects[-1], wall_gap)
print("boundary direction is")
print(nx, ny)
if pygame.Rect(nx, ny, 10, 10).collidelist(self.custom_boundary) != -1:
print("crosses boundary")
self.con_rects.append(self.climb_wall(self.con_rects[-1], wall_gap))
else:
self.con_rects.append(pygame.Rect(nx, ny, 10, 10))
else:
self.con_rects.append(pygame.Rect(nx, ny, 10, 10))
if (self.con_rects[-1].x, self.con_rects[-1].y) == (tx, ty):
print("setting connected")
Foodblock.set_connected(sink_food, 2)
capital_slime = random.choice(self.get_slime_four_corners())
tf = self.find_nearest_unconnected_food(capital_slime)
print("TARGET FOOD IS")
print(tf)
if tf is not None:
self.capital_slime = capital_slime
self.target_food = tf
else:
print("all foods found")
#keep track of edges connected for graphing
def add_edge(self, source_food, sink_food):
path = []
dist = 0
sx, sy = Foodblock.get_idx(source_food)
tx, ty = Foodblock.get_idx(sink_food)
source_rect = pygame.Rect(sx, sy, 10, 10)
path.append(source_rect)
while (path[-1].x, path[-1].y) != (tx, ty):
nx, ny = self.step_direction(path[-1], sink_food)
next_block = pygame.Rect(nx, ny, 10, 10)
path.append(next_block)
dist += 1
edge = ((sx, sy), (tx, ty), dist)
self.edges.append(edge)
#create graphs. These will show up as plots. But can be downloaded with metrics button.
def graph(self):
self.plots = []
print(self.edges)
G = nx.Graph()
nodes = set()
for edge in self.edges:
nodes.add(edge[0])
nodes.add(edge[1])
G.add_edge(edge[0], edge[1])
positions = {n: [n[0], n[1]] for n in list(G.nodes)}
print("edges are")
print(G.edges)
print("nodes are")
print(positions)
plt.figure()
nx.draw_networkx(G, positions, with_labels=True)
self.plots.append(plt.gcf())
plt.show()
#calulate the shortest distance and total distance
total_dist_G = 0
prev_dist = 1000000000000
shortest_dist_G = prev_dist
for edge in G.edges(data=True):
x1, y1 = edge[0]
x2, y2 = edge[1]
distance = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
total_dist_G += distance
if distance < prev_dist:
shortest_dist_G = distance
cost_of_G = shortest_dist_G/total_dist_G
dict_G1 = {"Edges":G.edges(data=True), "Cost": cost_of_G, "Shortest Distance": shortest_dist_G, "Total Distance": total_dist_G}
dict_G1 = self.generate_stats(G, dict_G1)
G2 = nx.Graph()
for node in nodes:
G2.add_node(str(node), pos=node)
print("G2 nodes are")
print(G2.nodes.data())
pos = nx.get_node_attributes(G2, 'pos')
#create random graph with equal number of edges to generated SMA graph
Gn = G2.copy()
network_gen = False
while not network_gen:
while nx.is_connected(Gn) is False:
# Choose two nodes randomly.
node1, node2 = random.sample(Gn.nodes, 2)
# Add an edge between the two nodes.
Gn.add_edge(node1, node2)
#check that it has the same number of edges as the SMA graph
if G.number_of_edges() == Gn.number_of_edges():
network_gen = True
G2 = Gn
else:
Gn = G2.copy()
shortest_dist_G2, total_dist_G2 = self.find_shortest_total_dist(G2)
cost_of_G2 = shortest_dist_G2/total_dist_G2
dict_G2 = {"Edges": G2.edges(data=True), "Cost": cost_of_G2, "Shortest Distance": shortest_dist_G2, "Total Distance": total_dist_G2}
dict_G2 = self.generate_stats(G2, dict_G2)
plt.figure()
nx.draw_networkx(G2, pos, with_labels=True)
self.plots.append(plt.gcf())
plt.show()
stats = [dict_G1, dict_G2]
pd.set_option('display.max_rows', None)
df = pd.DataFrame(stats, index = ['SMA', 'Random Graph'])
df = df.T
print(df)
self.stats = df
#generate remaining statistics
def generate_stats(self, G, stat_dict):
num_of_edges = nx.number_of_edges(G)
num_of_nodes = nx.number_of_nodes(G)
average_degree = sum(nx.average_degree_connectivity(G)) / len(nx.average_degree_connectivity(G))
assortativity = nx.degree_assortativity_coefficient(G)
density = nx.density(G)
mean_shortest_path_length = nx.average_shortest_path_length(G)
transport_efficiency = nx.global_efficiency(G)
diameter = nx.diameter(G)
stat_dict["Number of Edges"] = num_of_edges
stat_dict["Number of nodes"] = num_of_nodes
stat_dict["Average Degree Connectivity"] = average_degree
stat_dict["Degree Assortativity"] = assortativity
stat_dict["Density"] = density
stat_dict["Mean Shortest Path Length"] = mean_shortest_path_length
stat_dict["Transport Efficiency"] = transport_efficiency
stat_dict["Diameter"] = diameter
return stat_dict
#find the shortest distance and total distance for second random graph
def find_shortest_total_dist(self, G):
totaldist = 0
prev_dist = 1000000000000
shortest_dist = prev_dist
for edge in G.edges().data():
# Find all matches of the regular expression in the string.
x1, y1 = int(re.compile(r'\d+').findall(edge[0])[0]), int(re.compile(r'\d+').findall(edge[0])[1])
x2, y2 = int(re.compile(r'\d+').findall(edge[1])[0]), int(re.compile(r'\d+').findall(edge[1])[1])
distance = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
totaldist += distance
if distance < prev_dist:
shortest_dist = distance
return shortest_dist, totaldist
#diffuse every slime cell
def step(self, target_food):
self.r = 1
self.p = 0
self.num_slimes = len(self.slime_positions)
for s in range(len(self.slime_positions)):
if self.r >= self.p:
if Slimeblock.get_pheromone(self.slime_positions[s]) > self.diffusion_threshold:
self.diffuse(self.slime_positions[s], target_food)
else:
print("randomly diffusing")
if self.get_unconnected_food_blocks():
target_food = random.choice(self.get_unconnected_food_blocks())
if Slimeblock.get_pheromone(self.slime_positions[s]) > self.diffusion_threshold:
self.diffuse(self.slime_positions[s], target_food)
print("number of slimes" + str(len(self.slime_positions)))
self.r = random.uniform(0, 1)
if self.slime_positions:
weight = 1 + self.r * math.log(
(self.get_highest_ph() - Slimeblock.get_pheromone(self.slime_positions[s]) /
self.get_highest_ph() - self.get_lowest_ph()))
self.fitness_vals.append(weight)
fitness = (sum(self.fitness_vals) / len(self.fitness_vals))
print("fitness = " + str(fitness -2))
best_fit = max(self.fitness_vals)
self.p = math.atan(best_fit - fitness)
self.r = random.uniform(0, 1)
if self.num_slimes == len(self.slime_positions):
self.number_of_stalls += 1
#diffusion function based on MoeBuTa SlimeMould
def diffuse(self, current_slime, target_food):
moving_threshold = 1
og_diffusion_distance_threshold = 5
increment_max_ph = 0.2
new_idx = self.step_direction(current_slime, target_food)
new_cur_slime = (new_idx, pygame.Rect(new_idx[0], new_idx[1], 10, 10))
neighbours_dict = self.get_neighbours(current_slime)
neighbours = []
# make sure the first neighbour is the first step
for k, i in neighbours_dict.items():
if i == new_cur_slime:
neighbours.append((k, i))
for k, i in neighbours_dict.items():
if i != new_cur_slime:
neighbours.append((k, i))
neighbours = deque(neighbours)
while neighbours:
neigh = neighbours.popleft()
cur_idx = neigh[0]
cur_cell = neigh[1]
# check boundaries
if cur_cell.collidelist(self.boundaryblocks) == -1 and cur_cell.collidelist(self.custom_boundary) == -1:
# if the neighbour cell is an empty cell
if cur_cell.collidelist(self.foodblocks) == -1 and cur_cell.collidelist(self.slime_positions) == -1:
# next the next spot is an empty cell
if cur_idx == new_idx and slimeblock.Slimeblock.get_pheromone(current_slime) > moving_threshold:
new_slime = self.insert_slime_block(cur_idx[0], cur_idx[1])
new_slime_ph = new_slime.get_pheromone()
new_slime.set_pheromone(new_slime_ph * (1 - self.diffusion_decay_rate * new_slime.get_decay()))
continue
# neighbour cell is a random diffusion cell and find nearest connected food distance
if slimeblock.Slimeblock.get_pheromone(current_slime) > self.diffusion_threshold and \
self.find_nearest_connected_food_dist(current_slime) < self.diffusion_distance_threshold:
new_slime = self.insert_slime_block(cur_idx[0], cur_idx[1], ph=(
Slimeblock.get_pheromone(current_slime) / self.diffusion_decay_rate),
decay=Slimeblock.get_decay(current_slime))
new_slime_ph = slimeblock.Slimeblock.get_pheromone(new_slime)
new_slime.set_pheromone(
new_slime_ph * (1 - (2 * self.diffusion_decay_rate * new_slime.get_decay())))
# if the neighbor is a slime cell
if cur_cell.collidelist(self.slime_positions) != -1 and cur_cell.collidelist(self.foodblocks) == -1:
cur_slime = self.slime_positions[cur_cell.collidelist(self.slime_positions)]
if cur_idx == new_idx and slimeblock.Slimeblock.get_pheromone(current_slime) > moving_threshold:
neigh_increase_ph = slimeblock.Slimeblock.get_pheromone(cur_slime) + (
slimeblock.Slimeblock.get_pheromone(current_slime) / self.diffusion_decay_rate)
if neigh_increase_ph > slimeblock.Slimeblock.get_max_ph(cur_slime):
slimeblock.Slimeblock.set_pheromone(cur_slime, slimeblock.Slimeblock.get_max_ph(cur_slime))
else:
slimeblock.Slimeblock.set_pheromone(cur_slime, neigh_increase_ph)
slimeblock.Slimeblock.set_pheromone(current_slime, (
slimeblock.Slimeblock.get_pheromone(current_slime) / self.diffusion_decay_rate))
slimeblock.Slimeblock.set_idx(cur_slime, new_idx)
# increase self-pheromone if neighbour nearby is bigger than self
if slimeblock.Slimeblock.get_pheromone(cur_slime) > slimeblock.Slimeblock.get_pheromone(
current_slime) and \
slimeblock.Slimeblock.get_max_ph(current_slime) < slimeblock.Slimeblock.get_max_ph(
cur_slime):
slimeblock.Slimeblock.set_max_ph(current_slime, slimeblock.Slimeblock.get_max_ph(
current_slime) + increment_max_ph)
slimeblock.Slimeblock.set_pheromone(cur_slime, (
slimeblock.Slimeblock.get_pheromone(cur_slime) + (
slimeblock.Slimeblock.get_pheromone(cur_slime) / 10)))
# add pheromone if current cell find food nearby
if cur_cell.collidelist(self.foodblocks) != -1:
# eat food
slimeblock.Slimeblock.set_pheromone(current_slime, 7)
slimeblock.Slimeblock.set_max_ph(current_slime, 7)
food = self.foodblocks[cur_cell.collidelist(self.foodblocks)]
if Foodblock.get_connected(food) == 0:
Foodblock.set_connected(food, 1)
self.con_food_queue.append(food)
self.draw_efficent_path(food)
#else if it hits boundary
else:
#if it stalls
if self.number_of_stalls >= len(self.slime_positions):
#climb wall
self.increment_threshold += 1
self.increment_wall_climbers()
self.diffusion_distance_threshold += 1
else:
self.increment_threshold = 1
self.diffusion_distance_threshold = og_diffusion_distance_threshold
#find the gap in the wall
def find_wall_gap(self, wall_block):
next_gap = None
explored = [wall_block]
for block in explored:
for b in self.get_neighbours(block):
cur_block = self.get_neighbours(block)[b]
if cur_block.collidelist(self.custom_boundary) != -1 and cur_block.collidelist(explored) == -1:
explored.append(cur_block)
print("explored is")
print(explored)
neighbour_count = 0
potential_tips = []
for element in explored:
list = [element.x, element.y, neighbour_count]
potential_tips.append(list)
for list in potential_tips:
block = pygame.Rect(list[0], list[1], 10, 10)
minx, miny, maxx, maxy = self.main_rect
for b in self.get_neighbours(block):
cur_block = self.get_neighbours(block)[b]
if cur_block.collidelist(self.custom_boundary) != -1:
if minx < list[0] < maxx and miny < list[1] < maxy:
list[2] += 1
else:
if list in potential_tips:
potential_tips.remove(list)
print(potential_tips)
boundary_tips = []
for list in potential_tips:
if list[2] == 1:
print("boundary tip found!")
boundary_tips.append(pygame.Rect(list[0], list[1], 10, 10))
if boundary_tips:
print("boundary tips not empty")
print(boundary_tips)
potential_gaps = []
i = 0
for boundary_tip in boundary_tips:
for b in self.get_neighbours(boundary_tip):
cur_block = self.get_neighbours(boundary_tip)[b]
if cur_block.collidelist(self.slime_positions) != -1:
list_item = [cur_block.x, cur_block.y, 0]
potential_gaps.append(list_item)
for s in self.get_neighbours(cur_block):
cur_slime = self.get_neighbours(cur_block)[s]
if cur_slime.collidelist(self.custom_boundary) != -1:
potential_gaps[i][2] += 1
print(potential_gaps)
i += 1
gaps = []
for g in potential_gaps:
print("gaps found")
print(g)
if g[2] == 1:
gaps.append(g)
if len(gaps) > 0:
next_gap = pygame.Rect(gaps[0][0], gaps[0][1], 10, 10)
return next_gap
#climb the wall
def climb_wall(self, source, gap):
prev_dist = 100000000
target_block = gap
for b in self.get_neighbours(source):
cur_block = self.get_neighbours(source)[b]
if cur_block.collidelist(self.slime_positions) != -1:
dist = self.calcuate_distance(cur_block, gap)
if dist <= prev_dist:
prev_dist = dist
target_block = cur_block
return target_block
#add pheromone value to slimes near wall
def increment_wall_climbers(self):
for s in self.slime_positions:
neighbours = self.get_neighbours(s)
for n in neighbours:
if neighbours[n].collidelist(self.custom_boundary):
if s.incremented < self.increment_threshold and s.pheromone < s.max_ph:
if s.pheromone < self.diffusion_threshold:
slimeblock.Slimeblock.set_pheromone(s, self.diffusion_threshold + 0.1)
#calulate euclidian distance between two pygame rects
def calcuate_distance(self, source, sink):
x1, y1 = source.x, source.y
x2, y2 = sink.x, sink.y
dist = math.sqrt(((x1 - x2) ** 2) + ((y1 - y2) ** 2))
return dist
#find the nearsest food that is not connected
def find_nearest_unconnected_food(self, capital_slime):
slime_pos = Slimeblock.get_idx(capital_slime)
nearest_fb = None
prev_dist = 10000000000
for fb in self.foodblocks:
if Foodblock.get_connected(fb) == 0:
food_pos = Foodblock.get_idx(fb)
food_ph = Foodblock.get_pheromone(fb)
dist = math.sqrt(((slime_pos[0] - food_pos[0]) ** 2) + ((slime_pos[1] - food_pos[1]) ** 2))/food_ph
if dist <= prev_dist:
print("distance is", dist)
prev_dist = dist
nearest_fb = fb
target_food = nearest_fb
return target_food
#find the nearest food that is connected
def find_nearest_connected_food(self, target_food):
target_food_pos = Foodblock.get_idx(target_food)
nearest_fb = None
prev_dist = 10000000
for fb in self.foodblocks:
if Foodblock.get_connected(fb) > 0 and fb != target_food:
food_pos = Foodblock.get_idx(fb)
dist = math.sqrt(((target_food_pos[0] - food_pos[0]) ** 2) + ((target_food_pos[1] - food_pos[1]) ** 2))
if dist <= prev_dist:
prev_dist = dist
nearest_fb = fb
target_food = nearest_fb
return target_food
#find the distance of the nearest food that is connected
def find_nearest_connected_food_dist(self, capital_slime):
slime_pos = Slimeblock.get_idx(capital_slime)
nearest_fb = None
prev_dist = 10000000
for fb in self.foodblocks:
if Foodblock.get_connected(fb) == 1:
food_pos = Foodblock.get_idx(fb)
dist = math.sqrt(((slime_pos[0] - food_pos[0]) ** 2) + ((slime_pos[1] - food_pos[1]) ** 2))
if dist <= prev_dist:
prev_dist = dist
nearest_fb = fb
target_food = nearest_fb
return prev_dist
#find the farthest food distance
def find_furthest_food_dist(self, capital_slime):
slime_pos = Slimeblock.get_idx(capital_slime)
furthest_fb = None
prev_dist = 0.00001
for fb in self.foodblocks:
food_pos = Foodblock.get_idx(fb)
dist = math.sqrt(((slime_pos[0] - food_pos[0]) ** 2) + ((slime_pos[1] - food_pos[1]) ** 2))
if dist >= prev_dist:
prev_dist = dist
furthest_fb = fb
return prev_dist
#find the nearest food that is unconnected from current food point
def find_nearest_unconnected_food_from_food(self, foodblock):
origin_food_pos = Foodblock.get_idx(foodblock)
nearest_fb = None
prev_dist = 10000000
for fb in self.foodblocks:
if Foodblock.get_connected(fb) == 0:
food_pos = Foodblock.get_idx(fb)
dist = math.sqrt(((origin_food_pos[0] - food_pos[0]) ** 2) + ((origin_food_pos[1] - food_pos[1]) ** 2))
print("distance is " + str(dist))
if dist <= prev_dist:
prev_dist = dist
nearest_fb = fb
target_food = nearest_fb
return target_food
#step towards sink from source
def step_direction(self, source, sink):
if isinstance(source, slimeblock.Slimeblock):
sx, sy = Slimeblock.get_idx(source)
elif isinstance(source, pygame.Rect):
sx, sy = source.x, source.y
new_idx = sx, sy
if not isinstance(sink, foodblock.Foodblock):
fx, fy = sink.x, sink.y
else:
fx, fy = Foodblock.get_idx(sink)
# foodblock is N
if sx == fx and sy > fy:
# set the new id to 10 pixels up (pygame increase in y moves squares down)
new_idx = (sx, sy - 10)
# foodblock is NE
elif fx > sx and sy > fy:
new_idx = (sx + 10, sy - 10)
# foodblock is E
elif fx > sx and sy == fy:
new_idx = (sx + 10, sy)
# foodblock is SE
elif fx > sx and sy < fy:
new_idx = (sx + 10, sy + 10)
# foodblock is S
elif fx == sx and sy < fy:
new_idx = (sx, sy + 10)
# foodblock is SW
elif fx < sx and sy < fy:
new_idx = (sx - 10, sy + 10)
# foodblock is W
elif fx < sx and sy == fy:
new_idx = (sx - 10, sy)
# foodblock is NW
elif fx < sx and sy > fy:
new_idx = (sx - 10, sy - 10)
Slimeblock.set_isleader(slimeblock, 0)
return new_idx
#remove slimeblock formula
def slimeblock_remove(self, slime):
i = 0
for s in self.slime_positions:
if s == slime:
self.slime_positions[i].remove()
i += 1
#get the pygame rects for all the slimes
def get_slime_rects(self):
slime_rects = []
for slime in self.slime_positions:
slime_rects.append(Slimeblock.get_rect(slime))
return slime_rects
# get the pygame rects for all the food blocks
def get_food_rects(self):
food_rects = []
for food in self.foodblocks:
food_rects.append(Foodblock.get_rect(food))
return food_rects
# get the pygame rects for all the unconnected food blocks
def get_unconnected_food_rects(self):
connected_foods = []
for food in self.foodblocks:
if Foodblock.get_connected(food) == 0:
connected_foods.append(Foodblock.get_rect(food))
return connected_foods
#get all the unconnected food blocks
def get_unconnected_food_blocks(self):
connected_foodblocks = []
for food in self.foodblocks:
if Foodblock.get_connected(food) == 0:
connected_foodblocks.append(food)
return connected_foodblocks
#calculate the sum of all pheromone values. Used to calculate fitness
def get_total_ph(self):
total_ph = 0
ph_list = []
for s in self.slime_positions:
if Slimeblock.get_pheromone(s) > 1:
total_ph += Slimeblock.get_pheromone(s)
ph_list.append(Slimeblock.get_pheromone(s))
# print(ph_list)
return total_ph
#get the lowest pheromone value. Used to calculate fitness
def get_lowest_ph(self):
ph_prev = 10000000
lowest_ph = ph_prev
for s in self.slime_positions:
ph = Slimeblock.get_pheromone(s)
if ph < ph_prev:
lowest_ph = ph
ph_prev = ph
return lowest_ph
# get the highest pheromone value. Used to calculate fitness
def get_highest_ph(self):
ph_prev = 0
highest_ph = ph_prev
for s in self.slime_positions:
ph = Slimeblock.get_pheromone(s)
if ph > ph_prev:
highest_ph = ph
ph_prev = ph
return highest_ph
#get the pheromone rectangles
def get_ph_rect_list(self):
ph_rects = []
if self.pheromones:
for k, v in self.pheromones:
ph_rects.append(k)
return ph_rects
#return the four corners of the slime. Used to help choose the capital slime
def get_slime_four_corners(self):
slime_idxs = []
if self.slime_positions:
for s in self.slime_positions:
idx = Slimeblock.get_idx(s)
slime_idxs.append(idx)
max_x = max([x for x, y in slime_idxs])
max_y = max([y for x, y in slime_idxs])
min_x = min([x for x, y in slime_idxs])
min_y = min([y for x, y in slime_idxs])
for s in self.slime_positions:
x, y = Slimeblock.get_idx(s)
if x == max_x:
max_x_slime = s
if y == max_y:
max_y_slime = s
if x == min_x:
min_x_slime = s
if y == min_y:
min_y_slime = s
return [max_x_slime, max_y_slime, min_x_slime, min_y_slime]
#draw the border from point to point and what axis
def draw_border_line(self, start, end, orientation, axis):
temp_boundary = []
for tilespace in range(start, end, 10):
rect = pygame.Rect(10, 10, 10, 10)
if orientation == 'hor':
rect.topleft = (tilespace, axis)
elif orientation == 'ver':
rect.topleft = (axis, tilespace)
# if the tile doesnt already exist
if rect.collidelist(self.boundaryblocks) == -1:
temp_boundary.append(rect)
pygame.draw.rect(self.screen, (255, 0, 0), rect)
else:
break
for b in temp_boundary:
self.boundaryblocks.append(b)
#insert a border block
def insert_border_block(self, idx):
x, y = idx
rect = pygame.Rect(x, y, 10, 10)
# if the tile doesnt already exist
if rect.collidelist(self.boundaryblocks) == -1 and rect.collidelist(
self.get_food_rects()) == -1 and rect.collidelist(self.custom_boundary):
print("inserting border block")
self.custom_boundary.append(rect)
pygame.draw.rect(self.screen, (255, 0, 0), rect)
#get the neighbours
def get_neighbours(self, block):
if isinstance(block, slimeblock.Slimeblock):
x, y = Slimeblock.get_idx(block)
else:
x, y = block.x, block.y
neighbours = dict(
[((x, y - 10), pygame.Rect(x, y - 10, 10, 10)), ((x + 10, y - 10), pygame.Rect(x + 10, y - 10, 10, 10)),
((x + 10, y), pygame.Rect(x + 10, y, 10, 10)), ((x + 10, y + 10), pygame.Rect(x + 10, y + 10, 10, 10)),
((x, y + 10), pygame.Rect(x, y + 10, 10, 10)), ((x - 10, y + 10), pygame.Rect(x - 10, y + 10, 10, 10)),
((x - 10, y), pygame.Rect(x - 10, y, 10, 10)), ((x - 10, y - 10), pygame.Rect(x - 10, y - 10, 10, 10))])
#illustrates what direction each neighbour is in so left in
# neighbours = dict([('blockN', pygame.Rect(x, y - 10, 10, 10)),('blockNE', pygame.Rect(x + 10, y - 10, 10, 10)),
# ('blockE', pygame.Rect(x + 10, y, 10, 10)),('blockSE', pygame.Rect(x + 10, y + 10, 10, 10)),
# ('blockS', pygame.Rect(x, y + 10, 10, 10)),('blockSW', pygame.Rect(x - 10, y + 10, 10, 10)),
# ('blockW', pygame.Rect(x - 10, y, 10, 10)),('blockNW', pygame.Rect(x - 10, y - 10, 10, 10))])
return neighbours