-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutilities.pyx
1415 lines (1145 loc) · 38.2 KB
/
utilities.pyx
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
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# cython: profile=True
# cython: language_level=3
# cython: infer_types=True
from . import global_values as g
import pygame as p
import random as r
import math as m
import re
import importlib
import sys
def nmx(double x, to_int=False):
"""
Takes the x component of the screen coordinate and converts it to a value between 0 and 1.
Used for relative positions.
Parameters
----------
x : number
x component of the screen coordinate.
to_int : boolean
If True, converts to integer - default is False.
Returns
-------
normalised_x
An integer which is between 0 and 1.
Any out-of-bounds screen value will result in a value which is not between 0 and 1.
"""
normalised_x = x/g.WIDTH
if to_int:
normalised_x = int(normalised_x)
return normalised_x
def nmy(double y, to_int=False):
"""
Takes the y component of the screen coordinate and converts it to a value between 0 and 1.
Used for relative positions.
Parameters
----------
y : number
y component of the screen coordinate.
to_int : boolean
If True, converts to integer - default is False.
Returns
-------
normalised_y
An integer which is between 0 and 1.
Any out-of-bounds screen value will result in a value which is not between 0 and 1.
"""
normalised_y = y/g.HEIGHT
if to_int:
normalised_y = int(normalised_y)
return normalised_y
def dnmx(double x, to_int=True):
"""
Takes a value between 0 and 1 and converts it to the x component of the screen coordinate.
Parameters
----------
x : number
Value between 0 and 1.
to_int : boolean
If True, converts to integer - default is True.
Returns
-------
normalised_x
An integer.
Any out-of-bounds screen value will result in a value which is greater than the screen size.
"""
normalised_x = x*g.WIDTH
if to_int:
normalised_x = int(normalised_x)
return normalised_x
def dnmy(double y, to_int=True):
"""
Takes a value between 0 and 1 and converts it to the y component of the screen coordinate.
Parameters
----------
y : number
Value between 0 and 1.
to_int : boolean
If True, converts to integer - default is True.
Returns
-------
normalised_y
An integer.
Any out-of-bounds screen value will result in a value which is greater than the screen size.
"""
normalised_y = y*g.HEIGHT
if to_int:
normalised_y = int(normalised_y)
return normalised_y
def get_magnitude(double x, double y):
"""
Gets the magnitude of a vector.
Parameters
----------
x : number
x component of vector.
y : number
y component of vector.
Returns
-------
The magnitude of a vector as a number.
"""
return ((x**2) + (y**2))**0.5
def get_distance(double x1, double y1, double x2, double y2):
"""
Gets the distance between two points.
Parameters
----------
x1 : number
x component of point 1.
x2 : number
x component of point 2.
y1 : number
y component of point 1.
y2 : number
y component of point 2.
Returns
-------
dist
The distance between two points as a number.
"""
x = x2-x1
y = y2-y1
dist = ((x**2) + (y**2))**0.5
return dist
def get_angle(double x1, double y1, double x2, double y2):
"""
Gets the angle between two points.
Parameters
----------
x1 : number
x component of point 1.
x2 : number
x component of point 2.
y1 : number
y component of point 1.
y2 : number
y component of point 2.
Returns
-------
angle
The angle between two points.
"""
x = x2-x1
y = y2-y1
angle = m.atan2(y, x)
return angle
def get_angle_bound(angle, b1, b2, degrees=False):
"""
Checks if an angle is between two other angles.
Parameters
----------
angle : number
Angle to check for.
b1 : number
First angle.
b2 : number
Second angle.
degrees : boolean
If True, assumes the given angles are in degrees instead of radians - default is False.
Returns
-------
True or False.
"""
if degrees:
angle = m.radians(angle)
b1 = m.radians(b1)
b2 = m.radians(b2)
angle %= (2*m.pi)
b1 %= (2*m.pi)
b2 %= (2*m.pi)
if b2 > b1:
return b1 <= angle <= b2
else:
if b1 <= angle <= 2*m.pi:
return True
if 0 <= angle <= 2*m.pi:
return True
return False
# TODO: check if left is actually left and if right is actually right
def get_angle_difference(a1, a2, direction="shortest", degrees=False):
"""
Get difference between two angles, measured from a1 to a2
Parameters
----------
a1 : number
First angle.
a2 : number
Second angle.
direction : string
Direction of a2 from a1 - "left", "right" or "shortest".
degrees : boolean
If True, assumes the given angles are in degrees instead of radians - default is False.
Raises
------
ValueError if direction argument is not "left", "right" or "shortest".
Returns
-------
angle
Difference between the two angles as a number.
"""
if degrees:
a1 = m.radians(a1)
a2 = m.radians(a2)
if direction == "shortest":
angle = a1-a2
if angle > 1*m.pi:
angle = (2*m.pi)-angle
elif direction == "left":
angle = (a1-a2) % (2*m.pi)
elif direction == "right":
angle = (a2-a1) % (2*m.pi)
else:
raise ValueError("Direction argument not recognized (please use left, right or shortest)")
if degrees:
angle = m.degrees(angle)
return angle
def move_to_target_angle(angle, target_angle, distance, stop_on_reaching_target=True, degrees=False):
"""
Move an angle a set amount towards a target angle.
Parameters
----------
angle : number
Angle to move.
target_angle : number
Target angle.
distance : string
Distance to move.
stop_on_reaching_target : boolean
If True, the angle will stop at the target instead of going past it - default is True.
degrees : boolean
If True, assumes the given angles are in degrees instead of radians - default is False.
Returns
-------
angle
Moved angle as a number.
"""
if degrees:
angle = m.radians(angle)
target_angle = m.radians(target_angle)
# left
if get_angle_difference(angle, target_angle, direction="left") >= get_angle_difference(angle, target_angle, direction="right"):
angle -= distance
# right
else:
angle += distance
angle %= (2*m.pi)
if degrees:
angle = m.degrees(angle)
return angle
# clamp an angle between two other angles
# returns the clamped angle
# if get_bound is True, then it also returns whether the angle was in bounds to begin with
# def clamp_angle(angle, b1, b2, get_bound=False, degrees=False):
# if degrees:
# b1 = m.radians(b1)
# b2 = m.radians(b2)
# if get_angle_bound(angle, b1, b2):
# if get_bound:
# return angle, True
# else:
# return angle
# else:
# if
def clamp(double value, double min_value, double max_value):
"""
Clamp a value between a minimum and maximum value.
Parameters
----------
value : number
Value to clamp between minimum and maximum.
min_value : number
Minimum value.
max_value : number
Maximum value.
Returns
-------
value
Clamped value.
"""
if min_value is not None and value < min_value:
value = min_value
elif min_value is not None and value > max_value:
value = max_value
return value
def interpolate_between_values(v1_list, v2_list, amount_list, smooth=False):
"""
Interpolate between two values or lists of values, either linearly or smoothly.
Parameters
----------
v1_list : number/sequence
First value or sequence of values.
v2_list : number/sequence
Second value or sequence of values.
amount_list : number/sequence
Amount or sequence of amounts to interpolate by - between 0 and 1.
smooth : boolean
If True, interpolate smoothly - default is False.
Returns
-------
interpolated_value
Interpolated value as a number or list of interpolated number values.
"""
#check to see if all objects are sequences or not sequences (not as proper as isinstances but a bit faster)
if hasattr(v1_list, "__getitem__") == hasattr(v2_list, "__getitem__"):
if hasattr(v1_list, "__getitem__"):
if (len(v1_list) == len(v2_list)) == False:
raise IndexError("v1_list and v2_list must have the same number of elements")
else:
if hasattr(amount_list, "__getitem__"):
if len(amount_list) != len(v1_list):
raise IndexError("amount_list must have the same number of elements as v1_list or v2_list, or be a single value")
#sequence
final_values = []
for i in range(len(v1_list)):
v1 = v1_list[i]
v2 = v2_list[i]
amount = amount_list[i]
if smooth:
interpolated_value = ((amount*amount*(3-(2*amount)))*(v2-v1))+v1
else:
difference = v2-v1
interpolated_value = v1+(difference*amount)
final_values.append(interpolated_value)
else:
#sequence with non-list amount_list
final_values = []
for i in range(len(v1_list)):
v1 = v1_list[i]
v2 = v2_list[i]
if smooth:
interpolated_value = ((amount_list*amount_list*(3-(2*amount_list)))*(v2-v1))+v1
else:
difference = v2-v1
interpolated_value = v1+(difference*amount_list)
final_values.append(interpolated_value)
return final_values
else:
#no sequence
if smooth:
interpolated_value = ((amount_list*amount_list*(3-(2*amount_list)))*(v2_list-v1_list))+v1_list
else:
difference = v2_list-v1_list
interpolated_value = v1_list+(difference*amount_list)
return interpolated_value
else:
raise AttributeError("v1_list, v2_list and amount_list must either all have the __getitem__ attribute, or must all not have the __getitem__ attribute")
def rotate_list_left(l, n):
"""
Rotates values in list to the left.
Parameters
----------
l : list
List to rotate.
n : integer
Number of spaces to rotate.
Returns
-------
l
List rotated to the left.
"""
return l[n:] + l[:n]
def rotate_list_right(l, n):
"""
Rotates values in list to the right.
Parameters
----------
l : list
List to rotate.
n : integer
Number of spaces to rotate.
Returns
-------
l
List rotated to the right.
"""
return l[-n:] + l[:-n]
def get_line_end(x, y, angle, distance, degrees=False):
"""
Given a start point and an angle, get the point a certain distance away from the start point, where the angle between the two points is the same as the angle given.
Parameters
----------
x : number
x component of a coordinate.
y : number
y component of a coordinate.
angle : number
Angle to check against.
distance : number
Distance away from the start point.
degrees : boolean
If True, assumes the given angles are in degrees instead of radians - default is False.
Returns
-------
end_x, end_y
x and y components of the line end.
"""
if degrees:
end_x = x+(m.sin(m.radians(angle)) * distance)
end_y = y+(m.cos(m.radians(angle)) * distance)
else:
end_x = x+(m.sin(angle)*distance)
end_y = y+(m.cos(angle)*distance)
return end_x, end_y
def rotate_point(origin, point, double angle, degrees=False):
"""
Rotate a point around another point.
Parameters
----------
origin : tuple
Point to rotate around.
point : tuple
Point that is rotating.
angle : number
Angle to rotate against.
degrees : boolean
If True, assumes the given angles are in degrees instead of radians - default is False.
Returns
-------
qx, qy
x and y components of the point.
"""
# completely stolen from Mark Dickinson from stackoverflow
if degrees:
angle = m.radians(angle)
ox, oy = origin
px, py = point
qx = ox + m.cos(angle) * (px - ox) - m.sin(angle) * (py - oy)
qy = oy + m.sin(angle) * (px - ox) + m.cos(angle) * (py - oy)
return qx, qy
def rotate_rect(origin, rect, angle, degrees=False):
"""
Rotate a rectangle around a point.
Parameters
----------
origin : tuple
Point to rotate around.
rect : tuple
Rectangle that is rotating.
angle : number
Angle to rotate against.
degrees : boolean
If True, assumes the given angles are in degrees instead of radians - default is False.
Returns
-------
List of four rotated points.
"""
if degrees:
angle = m.radians(angle)
tl = rotate_point(origin, rect.topleft, angle)
tr = rotate_point(origin, rect.topright, angle)
bl = rotate_point(origin, rect.bottomleft, angle)
br = rotate_point(origin, rect.bottomright, angle)
return [tl, tr, bl, br]
def split_string_into_sections(raw_string, split_text, lines=True):
"""
Turn a raw string format below into a dictionary where each value is a list.
section one:
line1
line2
section two:
line 1
Parameters
----------
raw_string : string
Raw string to format into dictionary.
split_text : string
Text which splits each section.
lines : boolean
If True, split text into lines instead of raw strings - default is True.
Returns
-------
sections
Dictionary containing each section as a list.
"""
split_finder_pattern = re.compile(split_text+" [a-zA-Z0-9_]+:")
sections_names = [n[len(split_text)+1:-1] for n in re.findall(split_finder_pattern, raw_string)]
sections_data = re.split(split_finder_pattern, raw_string)[1:]
if lines:
sections_lines = []
for section_data in sections_data:
section_lines = [l for l in section_data.split("\n") if l]
sections_lines.append(section_lines)
sections = dict(zip(sections_names, sections_lines))
else:
sections = dict(zip(sections_names, sections_data))
return sections
def turn_string_into_dict(string_data, convert_keys=False):
"""
Turn a raw string format below into a dictionary where each line is a key-value pair.
key1=value1
key2=value2
key3=value3
Parameters
----------
string_data : string
Raw string to format into dictionary.
convert_keys : boolean
If True, convert key strings into other data types - default is False.
Returns
-------
dictionary
Dictionary of generated key-value pairs.
"""
dictionary = {}
string_data_lines = string_data.split("\n")
for item_string in string_data_lines:
if item_string and not item_string.isspace():
key, value = item_string.split("=")
if convert_keys:
key = convert_string_to_alternate_type(key)
value = convert_string_to_alternate_type(value)
dictionary.update({key: value})
return dictionary
def convert_string_to_alternate_type(value_string):
"""
Convert a string value into another data type.
This function is recursive so arguments needed to create complex types will also be converted to alternate types.
Parameters
----------
value_string : string
Raw string to format into another data type.
Returns
-------
value_converted
Original string as a new data type.
"""
# setup scriptable types if they have not already been set up
# if not scriptable_types:
# parse through value_string
# whether a "container" (string literal or list) is currently being processed, and if so what character is used
container = False
nest = 0
list_nest = 0
name = ""
args = []
current_arg = ""
for char in value_string:
if container:
current_arg += char
if (container == '"' and char == '"') or (container == "'" and char == "'") or (container == "[" and char == "]"):
container = False
else:
if char == "(":
nest += 1
if nest == 1:
continue
elif char == ")":
nest -= 1
if nest == 0:
args.append(current_arg)
continue
if nest == 0:
if not char.isspace():
name += char
else:
if char == '"' or char == "'" or char == "[" or char == "{":
container = char
elif nest == 1:
if char == ",":
args.append(current_arg)
current_arg = ""
continue
if not char.isspace():
current_arg += char
args = [convert_string_to_alternate_type(arg) for arg in args]
if args == [""]:
args = []
if name.replace('.', '', 1).replace('-', '', 1).isdigit():
value_converted = float(name)
# make value_string boolean if possible
elif name == "True":
value_converted = True
elif name == "False":
value_converted = False
elif name == "None":
value_converted = None
elif name == "Add":
value_converted = args[0]+args[1]
elif name == "Sub":
value_converted = args[0]-args[1]
elif name == "Mul":
value_converted = args[0]*args[1]
elif name == "Div":
value_converted = args[0]/args[1]
elif name == "Mod":
value_converted = args[0] % args[1]
elif name == "Int_Div":
value_converted = args[0]//args[1]
elif name == "Round":
value_converted = round(args[0])
elif name == "Floor":
value_converted = m.floor(args[0])
elif name == "Ceiling":
value_converted = m.ceiling(args[0])
elif name == "Radians":
value_converted = m.radians(args[0])
elif name == "Degrees":
value_converted = m.degrees(args[0])
elif name == "Abs":
value_converted = abs(args[0])
elif name == "Min":
value_converted = min(args)
elif name == "Max":
value_converted = max(args)
elif name == "Any":
value_converted = any(args)
elif name == "All":
value_converted = all(args)
elif name == "Sum":
value_converted = sum(args)
# make value_string a list if possible
elif name.startswith("[") and name.endswith("]"):
value_converted = [convert_string_to_alternate_type(v) for v in name.split(",")]
# make value_string a list if possible (this version supports nested lists)
elif name == "List":
value_converted = args
# make value_string a set if possible
elif name == "Set":
value_converted = set(args)
elif name == "FrozenSet":
value_converted = frozenset(args)
# make value_string a tuple if possible
elif name == "Tuple":
value_converted = tuple(args)
# make value_string a dictionary if possible
elif name == "Dict":
value_converted = dict(args)
elif name == "Obj_Value":
value_converted = getattr(args[0], args[1:])
elif name == "Func_Value":
value_converted = getattr(args[0], args[1])(*args[2], **args[3])
elif name == "Container_Value":
value_converted = args[0][args[1]]
elif name == "Module":
importlib.import_module(args[0])
value_converted = sys.modules[args[0]]
elif name == "Global":
value_converted = getattr(g, args[0])
elif name == "Get_Game_Object_Type":
value_converted = g.game_objects[args[0]]
elif name == "Get_Spritesheet":
value_converted = g.spritesheets[args[0]]
elif name == "Get_Font":
value_converted = g.fonts[args[0]]
elif name == "Get_Log":
value_converted = g.logs[args[0]]
else:
if (value_string.startswith('"') and value_string.endswith('"')) or (value_string.startswith("'") and value_string.endswith("'")):
value_converted = value_string[1:-1]
else:
value_converted = value_string
return value_converted
def bound_text(font, rect, text, safe_bounding=False):
"""
Split a string of text into lines such that they won't exceed the bounds of a rectangle when rendered.
Parameters
----------
font : graphics.Font
Font of the text.
rect : pygame.Rect
Rectangle whose dimensions will be used for bounding.
text : string
Text to bound.
safe_bounding : boolean
If True, text is guaranteed not to go outside of bounds when rendered, but may not use all available space - default is False.
Returns
-------
lines
List of lines of text.
"""
def handle_word(w):
if word == "\n":
result_w = ""
elif word == "\t":
result_w = " "
else:
result_w = word+" "
return result_w
lines = []
text_height = font.size(text)[1]
text = text.replace("\n", " \n ").replace("\t", " \t ")
words = text.split(" ")
x = 0
y = 0
current_line_text = ""
for word in words:
if y+text_height <= rect.height:
if safe_bounding:
width = font.size(word+" ")[0]
else:
width = font.size(word)[0]
width_with_space = font.size(word+" ")[0]
new_line = False
if x+width > rect.w:
new_line = True
if word == "\n":
new_line = True
if new_line:
lines.append(current_line_text)
current_line_text = handle_word(word)
x = width_with_space
y += text_height
else:
current_line_text += handle_word(word)
x += width_with_space
lines.append(current_line_text)
return lines
def encrypt_value(value):
"""
Encrypt a given number. Use the decrypt_value function to decrypt the value.
Parameters
----------
value : number
Plaintext.
Returns
-------
encrypted_value
Ciphertext.
"""
encrypted_value = ((value+31.4421)*9.88)**2
return encrypted_value
def decrypt_value(value, int_check=False):
"""
Decrypt a given ciphertext from encrypt_value.
Parameters
----------
value : number
Ciphertext.
int_check : boolean
If True, gives warning if the decrypted value that should be an integer isn't - default is False.
Returns
-------
decrypted_value
Plaintext.
"""
decrypted_value = ((value**0.5)/9.88)-31.4421
if int_check:
int_dif = abs(decrypted_value-int(decrypted_value))
if int_dif > 0.00001:
return False
else:
return int(decrypted_value)
return decrypted_value
def check_collision(rect, collision_mask, collision_dict, exceptions, obj=None):
"""
Check whether collision is occuring within a specific rectangle.
Parameters
----------
rect : number
Entity bounding rectangle.
collision_dict : dictionary
Dictionary containing the things that you want to check for collision against.
exceptions : collection
Any objects that you ignore in collision.
Returns
-------
colliding
The first object that there was a collision against.
"""
def get_entities(entity_list):
chosen_entities = []
for ent_type, can_collide in collision_dict.items():
if ent_type.startswith("class_"):
for entity in entity_list:
if can_collide and entity not in exceptions and ent_type in entity.class_aliases:
chosen_entities.append(entity)
return chosen_entities
colliding = False
# ---LEVELS---
# check for collisions with levels
if collision_dict.get("levels", False):
for level in g.active_levels:
colliding = level.check_collision(rect, collision_mask, obj=obj)
if colliding:
return colliding
if collision_dict.get("border", False):
colliding = True
for level in g.active_levels:
if level.rect.contains(rect):
colliding = False
break
if colliding:
return colliding
# ---ENTITIES---
if g.segmenting_in_levels:
check_entities_amount = 0
for ent_type, can_collide in collision_dict.items():
if can_collide and ent_type.startswith("class_"):
check_entities_amount += len(g.game_objects.get(ent_type, []))
# get entities using segment method
check_entities = []
if g.segmenting_in_levels and check_entities_amount > g.ENABLE_SEGMENT_ENTITY_THRESHOLD:
for level in g.active_levels:
if level.enable_segmenting:
for segment in level.get_segments(rect):
check_entities += get_entities(segment.entities)
if not check_entities:
check_entities = get_entities(g.game_objects.get("class_Entity", []))
else:
check_entities = get_entities(g.game_objects.get("class_Entity", []))
for entity in check_entities:
if entity not in exceptions and entity.solid:
if entity.collide_rect.colliderect(rect):
if obj:
# stop early if self or creature has mask collision and there is no mask collision
if obj.mask_collision or entity.mask_collision:
collision_offset = (int(entity.x-rect.x), int(entity.y-rect.y))
if not obj.collision_mask.overlap(entity.collision_mask, collision_offset):
continue
colliding = entity
break
# ---CAMERA---
if collision_dict.get("camera", False):