-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNuNetDesigner.py
3632 lines (2808 loc) · 179 KB
/
NuNetDesigner.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
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
import json
from math import pi, cos, sin
from tkinter import Tk, filedialog
from itertools import chain
from pygame import *
from pickle import dump, load, PickleError
from operator import itemgetter
# Position is used to store coordinates (as well as vectors) in terms of both pixels,
# and as a fraction of the window (worldcoordinates). By storing positions using an object,
# gui elements can simply request the pixel coordinates when drawing and be given the correct
# position regardless of any scaling or window resizing that has occured.
class Position:
def __init__(self, screen, xcoor, ycoor, *options):
# By holding the screen object (a pygame surface), the position can directly access the screen's dimensions at all times, this removes
# The need for a complex position screensize updating procedure, simplifying the code.
self.__screen = screen
# Setup of the positions x and y coordinates
self.__xcoor, self.__ycoor = xcoor, ycoor
# Default values for options setup:
# can be: axes (x and y stretch according to window size), mean (scale according to mean of x,y), square (scale according to diagonal).
self.__scaleType = "axes"
# RelCoor attribute flag shows whether the stored x and y coordinates are relative (in tems of fraction of the screen), or absolute (pixels)
self.__relCoor = True
# Anchor decides which corner of the screen the coordinates are set from, mainly useful for scaling the screen with absolute coordinates, for example
# the toolbar position stays set to the bottom right of the screen.
self.__anchor = ["top", "left"]
# The options parameter contaisn all arguments passed after 'ycoor', and enables the scaletype, relcoor and anchor to be set up and changed from defaults.
for option in options:
if option in ["axes", "mean", "square", "xaxis", "yaxis"]:
self.__scaleType = option
elif option == "rel":
self.__relCoor = True
elif option == "pixel":
self.__relCoor = False
elif option in ["top", "bottom"]:
self.__anchor[0] = option
elif option in ["left", "right"]:
self.__anchor[1] = option
# Scalervalue function returns a set of values for the x and y coordinates of the position, determining a value based on the scaletype
# and screen size that can be used for determining object sizes, and new positions.
def __scalervalue(self):
screensize = self.__screen.get_size()
if self.__scaleType == "axes":
return screensize
elif self.__scaleType == "mean":
mean = sum(screensize) / 2
return mean, mean
elif self.__scaleType == "square":
# Find the diagonal length of the screen using pythagoras' theorem.
diagonal = int(math.sqrt(screensize[0] ** 2 + screensize[1] ** 2))
return diagonal, diagonal
elif self.__scaleType == "xaxis":
return screensize[0], screensize[0]
elif self.__scaleType == "yaxis":
return screensize[1], screensize[1]
# pixelx returns the absolute (in pixels) position of the position class, this is useful when using relative coordinates, as even when the screen is
# resized, the pixelx function still returns the pixel position corresponding to the relative position passed.
def pixelx(self):
if self.__relCoor:
if self.__anchor[1] == "left":
return int(self.__xcoor * self.__scalervalue()[0])
else:
return int((1 - self.__xcoor) * self.__scalervalue()[0])
else:
if self.__anchor[1] == "left":
return self.__xcoor
else:
return self.__screen.get_size()[0] - self.__xcoor
# pixely returns the absolute (in pixels) position of the position class, this is useful when using relative coordinates, as even when the screen is
# is resized, the pixely function still returns the pixel position corresponding to the relative position passed.
def pixely(self):
if self.__relCoor:
if self.__anchor[0] == "top":
return int(self.__ycoor * self.__scalervalue()[1])
else:
return int((1 - self.__ycoor) * self.__scalervalue()[1])
else:
if self.__anchor[0] == "top":
return self.__ycoor
else:
return self.__screen.get_size()[1] - self.__ycoor
# pixel returns a two item list containing the x, y pixels
def pixel(self):
return self.pixelx(), self.pixely()
# relx returns the relative x-position of the object on the screen
def relx(self):
if self.__relCoor:
if self.__anchor[1] == "left":
return self.__xcoor
else:
return self.__screen.get_size()[0] - self.__xcoor
else:
if self.__anchor[1] == "left":
return self.__xcoor / self.__scalervalue()[0]
else:
return (self.__screen.get_size()[0] - self.__xcoor) / self.__scalervalue()[0]
# rely returns the relative x-position of the object on the screen
def rely(self):
if self.__relCoor:
if self.__anchor[0] == "top":
return self.__ycoor
else:
return self.__screen.get_size()[1] - self.__ycoor
else:
if self.__anchor[0] == "top":
return self.__ycoor / self.__scalervalue()[1]
else:
return (self.__screen.get_size()[1] - self.__ycoor) / self.__scalervalue()[1]
# rel returns a two item list containing the x, y relative positions
def rel(self):
return self.relx(), self.rely()
# The worldposition class is used for the grid of the editor interface. It converts the position of the camera (the area of the grid being displayed),
# the screensize and a position in the grid into a position in pixels for a given gui element. As fro getting pixel positions the methods are identical
# to the Position class, this can be used as an alternative to Position for a gui object, placing it at a position in the grid in doing so.
class WorldPosition:
def __init__(self, screen, camera, xcoor, ycoor, size=False):
# setup of required attributes:
# Storing the screen reference (so that screensize can be accessed easily)
self.__screen = screen
# Stopring the camera object (contains zoom as well as camera position to be accessed readily)
self.__camera = camera
# Setup of the xcoor, ycoor of the grid.
self.__xcoor, self.__ycoor = xcoor, ycoor
# Setup of the size flag, true means that the position is a size and hence only needs to be scaled with zoom, not with the camera's position.
self.__size = size
# Pixelx returns the x-coordinate of a worldposition in terms of pixels across the screen, and in the case of sizes, the width of the size.
def pixelx(self):
# Checking if the worldposition is a size (in which case cameraposition is not considered)
if self.__size:
return int(self.__xcoor * self.__camera.getzoom())
else:
# If not a size, the cameraposition needs to be considered as the object may be off screen.
return int((self.__xcoor - self.__camera.getposition()[0]) * self.__camera.getzoom())
# Pixely returns the y-coordinate of a worldposition in terms of pixels across the screen, and in the case of sizes, the height of the size.
def pixely(self):
if self.__size:
return int(self.__ycoor * self.__camera.getzoom())
else:
return int((self.__ycoor - self.__camera.getposition()[1]) * self.__camera.getzoom())
# Pixel returns the pixely and pixelx results as one list for convenient use.
def pixel(self):
return self.pixelx(), self.pixely()
# Worldx returns the worldposition's x-value.
def worldx(self):
return self.__xcoor
# Worldy returns the worldposition's y-value.
def worldy(self):
return self.__ycoor
# Pixel returns the worldy and worldx results as one list for convenient use.
def world(self):
return self.__xcoor, self.__ycoor
# The camera class is used for the implementation of the grid in which the user edits their network design. It contains the camera's position within
# that grid, and the zoom view, this enabled the conversion of worldcoordinates into a pixelposition on the screen, and the translation of the users
# view back and forth across the grid, as well as zooming to a point determined by the mouse.
class Camera:
def __init__(self, screen, worldposition, zoom):
# storing of the screen object for easy access to screen dimensions (useful when determining screensize).
self.__screen = screen
# worldcoordinates represent the positions of markers on the grid interface the user uses to design networks. Positions are defined in
# terms of x and y, with both potentially being negative as to allow for an infinitely large grid.
self.__worldPosition = worldposition
# Zoom represents the number of pixels per world coordinate, and is used for determining absolute pixel positions from worldpositions.
self.__zoom = zoom
# Getposition simply returns the current worldposition of the camera object.
def getposition(self):
return self.__worldPosition
# Getsize returns the size in terms of worldcoordinates of the screen, this is useful for checking if an object needs to be rendered (rather
# than attempting all), and hence reduce rescource utilisation.
def getsize(self):
size = self.__screen.get_size()
return size[0] / self.__zoom, size[1] / self.__zoom
# Getzoom returns the zoom, the number of pixels per worldposition.
def getzoom(self):
return self.__zoom
# Move moves the camera to a new position by a distance determined by a 2d vector of worldcoordinates.
def move(self, moveby):
self.__worldPosition[0] += moveby[0]
self.__worldPosition[1] += moveby[1]
# Setposition sets the position of the camera to a certain point.
def setposition(self, worldposition):
self.__worldPosition = worldposition
# setzoom sets the zoom level to an argument.
def setzoom(self, zoom):
self.__zoom = zoom
# world to pixel converts a worldposition into a opixelposition on the screen.
def worldtopixel(self, worldposition, size=False):
# If checking a size's magnitude in pixels, the camera's position does not need to be considered.
if size:
return int(worldposition[0] * self.__zoom), int(worldposition[1] * self.__zoom)
else:
return int((worldposition[0] - self.__worldPosition[0]) * self.__zoom), int((worldposition[1] - self.__worldPosition[1]) * self.__zoom)
# Pixeltoworld converts a pixelposition (such as that of the mouse) into a worldposition, this is useful for adding objects to the grid as the
# program can tell where in the grid the mouse is at a given time.
def pixeltoworld(self, pixelposition, size=False):
if size:
return pixelposition[0] / self.__zoom, pixelposition[1] / self.__zoom
else:
return pixelposition[0] / self.__zoom + self.__worldPosition[0], pixelposition[1] / self.__zoom + self.__worldPosition[1]
# Increasezoom both increases the zoom value (making grid objects larger), but also ensures the zoom is towards the current position of the mouse.
def increasezoom(self, eventposition):
# Limit on how far in the user can zoom in the form of an if statement.
if self.__zoom < 1000:
# Zoom increased by 10%.
self.__zoom *= 1.1
# Conversion of the mouseposition to a worldposition within the grid.
eventworldposition = self.pixeltoworld(eventposition)
# Moving the camera to make the zoom centered on the mouse.
self.__worldPosition[0] += (eventworldposition[0] - self.__worldPosition[0]) * 0.1
self.__worldPosition[1] += (eventworldposition[1] - self.__worldPosition[1]) * 0.1
# Increasezoom both decreases the zoom value (making grid objects smaller), but also ensures the zoom is centered on the current position of the mouse.
def decreasezoom(self, eventposition):
# Limit on how far the user can zoom out, as at high zooms so many grid crosshairs and network objects are positentially are viewable that
# the program will slow down due to high rescource utilisation.
if self.__zoom > 30:
# Zoom decreased by 10%.
self.__zoom *= 0.9
# Conversion of the mouseposition to a worldposition within the grid.
eventworldposition = self.pixeltoworld(eventposition)
# Moving the camera to make the zoom centered on the mouse.
self.__worldPosition[0] -= (eventworldposition[0] - self.__worldPosition[0]) * 0.1
self.__worldPosition[1] -= (eventworldposition[1] - self.__worldPosition[1]) * 0.1
# A basic GUI element, a coloured rectangle.
class Rectangle:
def __init__(self, screen, position, size, fillcolour, anchor="topleft"):
# Storing a reference to the display, so that the rectangle can be easily displayed.
self.__screen = screen
# Storing rectangle position.
self.__position = position
# Storing a Position/Worldposition object to be used for determining the size of the rectangle.
self.__size = size
# Storing fillcolour, using a tuple or RGB values.
self.__fillColour = fillcolour
# Storing the anchor, which determines what part of the object the position references.
self.__anchor = anchor
# paint is a standard function for GUI objects, it instructs pygame to display the object when the display next updates.
def paint(self):
# instructing pygame to draw the rectangle on next display update.
draw.rect(self.__screen, self.__fillColour, self.__generaterectangle())
# generaterectangle generates the rectangleobject for both checking if it has been clicked (used in textbutton for example) and for rendering.
def __generaterectangle(self):
# create new rectangle of size (size), at the position specified.
rectangle = Rect(self.__position.pixel(), self.__size.pixel())
# temporary holding of the rectangle's position for further manipulation
rectangleposition = self.__position.pixel()
# using the anchor provided to set the rectangle's position based upon it.
if self.__anchor == "topleft":
pass
elif self.__anchor == "topcenter":
rectangle.midtop = rectangleposition
elif self.__anchor == "topright":
rectangle.topright = rectangleposition
elif self.__anchor == "midleft":
rectangle.midleft = rectangleposition
elif self.__anchor == "midcenter":
rectangle.center = rectangleposition
elif self.__anchor == "midright":
rectangle.midright = rectangleposition
elif self.__anchor == "bottomleft":
rectangle.bottomleft = rectangleposition
elif self.__anchor == "bottomcenter":
rectangle.midbottom = rectangleposition
elif self.__anchor == "bottomright":
rectangle.bottomright = rectangleposition
return rectangle
# getposition returns the position of the rectangle.
def getposition(self):
return self.__position
# getsize returns the size of the rectangle
def getsize(self):
return self.__size
# getrectangle returns the pygame Rect of the rectangle, for use in collision detection.
def getrectangle(self):
return self.__generaterectangle()
# getfillcolour returns the current fillcolour of the rectangle.
def getfillcolour(self):
return self.__fillColour
# getalign returns the anchor used for the rectangle's position when drawing to the screen.
def getalign(self):
return self.__anchor
# gettype returns the type of object, in this case 'Rectangle'.
def gettype(self):
return "Rectangle"
# setposition sets the position of the rectangle to the provided argument.
def setposition(self, position):
self.__position = position
# setsize sets the size of the rectangle to the provided argument
def setsize(self, size):
self.__size = size
# setfillcolour sets the colour of the rectangle to a colour provided in the form of a tuple of RGB values.
def setfillcolour(self, fillcolour):
self.__fillColour = fillcolour
# setalign sets the alignment of the rectangle (which part the position is referencing).
def setalign(self, align):
self.__anchor = align
# The text class is used for displaying all text in the program, and is used by several other GUI objects for displaying their text.
class Text:
def __init__(self, screen, text, position, textsize, textcolour, anchor="midcenter"):
# Screen reference stored so that the textc an be easily drawn to the screen.
self.__screen = screen
# Storing the text to be displayed (converted to string as int, and float can be passed to the text attribute but not displayed without conversion).
self.__text = str(text)
# Storing the position.
self.__position = position
# Storing the text size.
self.__textSize = textsize
# storinhg text colour.
self.__textColour = textcolour
# Anchor is "midcenter" by default, and determines at what point in the object the position is referencing.
self.__anchor = anchor
# A standard method for GUI objects, instructing pygame to display the object when the display is next updated.
def paint(self):
# Setup of the textsurface copntaining the text itself.
textsurface = font.Font("freesansbold.ttf", self.__textSize).render(self.__text, True, self.__textColour)
# Creating the rectangle in which the text is to be displayed (used by pygame's draw functionality to render the text).
textrectangle = textsurface.get_rect()
# Default position of text setup
textposition = self.__position.pixel()
# Based on the anchor provided the position is applied to a different point in the textrectangle, this allows for many different
# arrangements, such as centering text of a given position.
if self.__anchor == "topleft":
pass
elif self.__anchor == "topcenter":
textrectangle.midtop = textposition
elif self.__anchor == "topright":
textrectangle.topright = textposition
elif self.__anchor == "midleft":
textrectangle.midleft = textposition
elif self.__anchor == "midcenter":
textrectangle.center = textposition
elif self.__anchor == "midright":
textrectangle.midright = textposition
elif self.__anchor == "bottomleft":
textrectangle.bottomleft = textposition
elif self.__anchor == "bottomcenter":
textrectangle.midbottom = textposition
elif self.__anchor == "bottomright":
textrectangle.bottomright = textposition
# Instructing pygame to display the text on next display update.
self.__screen.blit(textsurface, textrectangle)
# gettext returns the current text of the text object, this is made use of in the TextEntry class for accessing user input.
def gettext(self):
return self.__text
# getposition returns the current position of the text
def getposition(self):
return self.__position
# gettextsize returns the current font/text size used.
def gettextsize(self):
return self.__textSize
# gettextcolour returns the current colour of the text as a tuple of RGB values.
def gettextcolour(self):
return self.__textColour
# getalign returns the anchor from where the text's position is set.
def getalign(self):
return self.__anchor
# gettype returns the type of object, in this case "Text".
def gettype(self):
return "Text"
# settext sets the text to a given string.
def settext(self, text):
self.__text = str(text)
# setposition sets the position of the text to a new position object
def setposition(self, position):
self.__position = position
# settextsize sets the text size to a new size
def settextsize(self, textsize):
self.__textSize = textsize
# settextcolour sets the text colour to a new colour specified by a tuple of RGB values.
def settextcolour(self, textcolour):
self.__textColour = textcolour
# setalign sets the anchor of the text to a new anchor
def setalign(self, align):
self.__anchor = align
# The Image class is used to display images from a relative filename, and allows for transforming the image to different sizes.
class Image:
def __init__(self, screen, imagesource, position, size, anchor="topleft"):
# Storing a reference to the screen (for use in 'paint' for displaying the object).
self._screen = screen
# Storing the relative file-path of the image file.
self._imageSource = imagesource
# Storing the image itself, using the relative file-path and pygame's image functionality.
self._imageFile = image.load(imagesource)
# Holding the image surface (used for displaying the image), while initially set to 'None' it is filled by the 'refresh' method.
self._imageSurface = None
# Holding the pixel position the image (top left hand corner) for use when displaying. It is updated by the 'refresh' method.
self._imagePixelPosition = [0, 0]
# Holding the position of the image.
self._position = position
# Holding the size the image will be transformed/stretched to.
self._size = size
# Holding the anchor (from where the position references).
self._anchor = anchor
# Holding the rectangle of the image (for use in displaying the object, and in the ImageButton for use in click detection).
self._rectangle = None
# 'refresh' is run to set up the empty attributes above
self._refresh()
# paint is a standard method for displaying the image on the display.
def paint(self):
# refreshing the imagesurface, rectangle and pixelposition based on the position, size and anchor .
self._refresh()
# instruct pygame to display the object when the screen next updates.
self._screen.blit(self._imageSurface, (self._imagePixelPosition[0], self._imagePixelPosition[1]))
# refresh is used for updating the pixelposition, rectangle and image which do not update with scaling, using the position, size and anchor which
# do. This enables pygame to correctly draw the image.
def _refresh(self):
# creating an initial value for the pixelposition.
self._imagePixelPosition = [0, 0]
# setting the pixelposition based on the provided anchor, size and position object.
if self._anchor == "topleft":
self._imagePixelPosition = [self._position.pixelx(), self._position.pixely()]
elif self._anchor == "topcenter":
self._imagePixelPosition = [self._position.pixelx() - self._size.pixelx() // 2, self._position.pixely()]
elif self._anchor == "topright":
self._imagePixelPosition = [self._position.pixelx() - self._size.pixelx(), self._position.pixely()]
elif self._anchor == "midleft":
self._imagePixelPosition = [self._position.pixelx(), self._position.pixely() - self._size.pixely() // 2]
elif self._anchor == "midcenter":
self._imagePixelPosition = [self._position.pixelx() - self._size.pixely() // 2, self._position.pixely() - self._size.pixely() // 2]
elif self._anchor == "midright":
self._imagePixelPosition = [self._position.pixelx() - self._size.pixely(), self._position.pixely() - self._size.pixely() // 2]
elif self._anchor == "bottomleft":
self._imagePixelPosition = [self._position.pixelx(), self._position.pixely() - self._size.pixely()]
elif self._anchor == "bottomcenter":
self._imagePixelPosition = [self._position.pixelx() - self._size.pixely() // 2, self._position.pixely() - self._size.pixely()]
elif self._anchor == "bottomright":
self._imagePixelPosition = [self._position.pixelx() - self._size.pixely(), self._position.pixely() - self._size.pixely()]
# setup of the image surface (used by pygame to draw the object)
self._imageSurface = transform.scale(self._imageFile, self._size.pixel())
# Setup of the rectangle (used for collision detection)
self._rectangle = Rect((self._imagePixelPosition[0], self._imagePixelPosition[1]), self._size.pixel())
# getimagesource returns the realtive file-path of the image used.
def getimagesource(self):
return self._imageSource
# getimagefile returns the image being displayed.
def getimagefile(self):
return self._imageFile
# getposition retuirns the position of the object.
def getposition(self):
return self._position
# getrectangle returns the rectangle hitbox of the image for collision detection.
def getrectangle(self):
self._refresh()
return self._rectangle
# getsize returns the size of the image.
def getsize(self):
return self._size
# gettype returns the type of object, in this case an 'Image'
def gettype(self):
return "Image"
# setimage stes the current image to one defined by a provided relative file-path.
def setimage(self, imagesource):
# Changing the imagesource.
self._imageSource = imagesource
# Loading the new image file.
self._imageFile = image.load(imagesource)
# setposition sets the current position to a new one.
def setposition(self, position):
self._position = position
# setsize sets the current size to a new one.
def setsize(self, size):
self._size = size
# The Line class displays a straight line from a start to an end position
class Line:
def __init__(self, screen, startposition, endposition, width, fillcolour):
# Store the screen the line is being displayed on for use in the 'paint' methods.
self.__screen = screen
# Storing the start position.
self.__startPosition = startposition
# Storing the end position.
self.__endPosition = endposition
# Storing the value for the width of the line.
self.__width = width
# Storing the fill colour for the line.
self.__fillColour = fillcolour
# paint is a standard method for GUI Objects and instructs Pygame to display the object when the screen next updates.
def paint(self):
draw.line(self.__screen, self.__fillColour, self.__startPosition.pixel(), self.__endPosition.pixel(), self.__width)
# getcollide determines if a mouseposition is within the hitbox of the line. as collision detection had to be created from scratch (no line
# collision detection in Pygame) I use the line equation to calculate a hitbox and to check if the mouseposition is in it.
def getcollide(self, mouseposition):
# Retrieveing the start and end coordinates in pixels.
startpos = self.__startPosition.pixel()
endpos = self.__endPosition.pixel()
# Determining gradient by dividing change in y over x. This would break for a line with the same x-coordinates, however as this is only used
# for synapses which cannot be connected vertically such an eventuality cannot occur.
linegradient = (startpos[1] - endpos[1]) / (startpos[0] - endpos[0])
# Calculating the y intercept of the line.
lineintercept = startpos[1] - linegradient * startpos[0]
# Calculating the y-width of the hitbox using the line graident (if the line was flat, it would be 10 pixels, this is changed for lines at
# angles using pythagoras.
ywidth = 10 * abs(startpos[0] - endpos[0]) / ((startpos[0] - endpos[0]) ** 2 + (startpos[1] - endpos[1]) ** 2) ** 0.5
# Checking if the mouse is within the x bounds of the line (and hence could be touching the line's hitbox).
if (endpos[0] > mouseposition[0] > startpos[0] or endpos[0] < mouseposition[0] < startpos[0]):
# Calculating the y-position of the line at the mouse's x-position.
yposition = linegradient * mouseposition[0] + lineintercept
# Checking if the mouse y-position is within the hitbox's y-position range, and if so returning 'True' to show the mouse is on the line.
if (yposition - ywidth) < mouseposition[1] < (yposition + ywidth):
return True
else:
return False
else:
return False
# getstartposition returns the startPosition object for the line.
def getstartposition(self):
return self.__startPosition
# getendposition returns the endPosition object for the line.
def getendposition(self):
return self.__endPosition
# getwidth returns the width value given to the line.
def getwidth(self):
return self.__width
# getfillcolour returns the colour of the line as a tuple of RGB values.
def getfillcolour(self):
return self.__fillColour
# gettype returns the type of object, in this case a 'Line' object.
def gettype(self):
return "Line"
# setstartposition sets the startposition of the line to a new object.
def setstartposition(self, startposition):
self.__startPosition = startposition
# setendposition sets the endposition of the line to a new object.
def setendposition(self, endposition):
self.__endPosition = endposition
# setwidth sets the width of the line.
def setwidth(self, width):
self.__width = width
# setfillcolour sets the fillcolour of the line to a new colour specified by a tuple of RGB values.
def setfillcolour(self, fillcolour):
self.__fillColour = fillcolour
# Circle class creates circle objects at the centerposition, with a radius of the magnitude determined by the x-value of radiussize. Its main use is
# for displaying network objects, for example by default neurons are circles.
class Circle:
def __init__(self, screen, centerposition, radiussize, fillcolour):
# Storing the screen pygame surface as to ensure
self._screen = screen
# Storing the centerposition attribute
self._centerPosition = centerposition
# Storing radius size attribute
self._radiusSize = radiussize
self._fillColour = fillcolour
# paint is a standard method for GUI Objects, instructs pygame to display the object when the screen next updates.
def paint(self):
draw.circle(self._screen, self._fillColour, self._centerPosition.pixel(), self._radiusSize.pixelx())
# getcenterposition returns the current center position of the circle.
def getcenterposition(self):
return self._centerPosition
# getradiussize returns the current position defining the radius of the circle.
def getradiussize(self):
return self._radiusSize
# getfillcolour returns the tuple containing the RGB values for the circle's fill colour.
def getfillcolour(self):
return self._fillColour
# getrectangle returns the rectangular hitbox of the circle.
def getrectangle(self):
return Rect(self._centerPosition.pixelx() - self._radiusSize.pixelx(),
self._centerPosition.pixely() - self._radiusSize.pixely(),
2 * self._radiusSize.pixelx(),
2 * self._radiusSize.pixely()
)
# gettype returns the type of object.
def gettype(self):
return "Circle"
# setcenterposition sets the centerposition of the circle to a new position provided.
def setcenterposition(self, centerposition):
self._centerPosition = centerposition
# setradiussize sets the object determining circle radius to a new position object.
def setradiussize(self, radiussize):
self._radiusSize = radiussize
# setfillcolouir sets the fillcolour of the object to a new colour described by a tuple of RGB values.
def setfillcolour(self, fillcolour):
self._fillColour = fillcolour
# The polygon class is used to create regular shapes of varying number of faces, and is mainly used for displaying network objects in the design
# (e.g be default output neurons are pentagons).
class Polygon:
def __init__(self, screen, centerposition, radiussize, fillcolour, polygonnumber):
# Storing a reference to the screen the polygon is to be displayed on.
self._screen = screen
# Storing the center position of the polygon.
self._centerPosition = centerposition
# Storing the radius size of the polygon (whose x and y dimensions determine the position of the vertices of the shape).
self._radiusSize = radiussize
# Storing the colour of the polygon.
self._fillColour = fillcolour
# Storing the number of vertices in the polygon.
self._polygonNumber = polygonnumber
# 'paint' is a standard method for GUI objects and instructs pygame to display the object when the screen next updates.
def paint(self):
# Creating a list to hold the positions of the vertices of the shape
polypositions = list()
for index in range(self._polygonNumber):
# generating the pixel-positions of each vertex based on its number, by moving anticlockwise about the center, the points are placed at regular intervals.
polypositions.append(
(int(self._radiusSize.pixelx() * cos(pi * 2 * index / self._polygonNumber)) + self._centerPosition.pixelx(),
int(self._radiusSize.pixely() * sin(pi * 2 * index / self._polygonNumber)) + self._centerPosition.pixely()
)
)
# Instructing Pygame to draw the polygon.
draw.polygon(self._screen, self._fillColour, polypositions)
# getcenterposition returns the center position of the polygon.
def getcenterposition(self):
return self._centerPosition
# getradiussize returns the radiussize attribute, which effectively describes how far the object can go from its center-position in the x and y directions.
def getradiussize(self):
return self._radiusSize
# getfillcolour returns the colour of the polygon as a tuple of RGB values.
def getfillcolour(self):
return self._fillColour
# getpolygonnumber returns the number of vertices in the polygon.
def getpolygonnumber(self):
return self._polygonNumber
# getrectangle returns a Pygame Rect of the hitbox of the polygon (for use in Polygon button and network objects for determining if it has been clicked).
def getrectangle(self):
# As centerposition is from the center, radiussize must be subtracted to get the position of the top left hand corner. For the dimensions,
# twice the radiussize is required in the x and y directions to create the hitbox required.
return Rect(self._centerPosition.pixelx() - self._radiusSize.pixelx(),
self._centerPosition.pixely() - self._radiusSize.pixely(),
2 * self._radiusSize.pixelx(),
2 * self._radiusSize.pixely()
)
# gettype returns the object type, in this case a 'Polygon'
def gettype(self):
return "Polygon"
# setcenterposition sets the center-position of the polygon.
def setcenterposition(self, centerposition):
self._centerPosition = centerposition
# setradiussize sets the radiusSize attribute to a new Position/WorldPosition object.
def setradiussize(self, radiussize):
self._radiusSize = radiussize
# setfillcolour sets the colour of the polygon.
def setfillcolour(self, fillcolour):
self._fillColour = fillcolour
# setpolygonnumber sets the number of vertices of the polygon.
def setpolygonnumber(self, polygonnumber):
self._polygonNumber = polygonnumber
# creates a rectangle, containing centered text within a coloured rectangle.
class TextRectangle:
def __init__(self, screen, position, size, fillcolour, text, textsize, textcolour):
# Storing a reference to the screen on which the object is to be displayed.
self._screen = screen
# Storing position (for text rectangles this is always the top left hand corner).
self._position = position
# Storing the dimensions of the rectangle.
self._size = size
# Initialisation of the rectangle object.
self._rectangleObject = Rectangle(self._screen, position, size, fillcolour)
# Initialisation of the text object at the center opf the rectangle.
centerposition = Position(self._screen, position.relx() + size.relx() / 2, position.rely() + size.rely() / 2)
self._textObject = Text(self._screen, text, centerposition, textsize, textcolour, "midcenter")
# the paint method is standard for GUI objects and instructs pygame to display both the rectangle, and text (on top) when the display next updates.
def paint(self):
self._rectangleObject.paint()
self._textObject.setposition(Position(self._screen, self._rectangleObject.getposition().relx() + self._rectangleObject.getsize().relx() / 2, self._rectangleObject.getposition().rely() + self._rectangleObject.getsize().rely() / 2))
self._textObject.paint()
# gettext returns the text of the text object.
def gettext(self):
return self._textObject.gettext()
# getposition returns the center position of the object.
def getposition(self):
return self._textObject.getposition()
# gettextsize returns the font/text size.
def gettextsize(self):
return self._textObject.gettextsize()
# gettextcolour returns the colour of the text.
def gettextcolour(self):
return self._textObject.gettextcolour()
# getsize returns the size of the rectangle.
def getsize(self):
return self._rectangleObject.getsize()
# getrectangle returns the hitbox of the Text Rectangle (for use in buttons)
def getrectangle(self):
return self._rectangleObject.getrectangle()
# getfillcolour returns the colour of the rectangle.
def getfillcolour(self):
return self._rectangleObject.getfillcolour()
# gettype returns the type of object, in this case a 'TextRectangle'
def gettype(self):
return "TextRectangle"
# setposition sets the position of the object.
def setposition(self, position):
# setting the rectangle component's position.
self._position = position
self._rectangleObject.setposition(position)
# setting the centerposition of the text to the center of the rectangle.
centerposition = self._rectangleObject.getrectangle().center
self._textObject.setposition(Position(self._screen, centerposition[0], centerposition[1], "pixel"))
# setsize sets the size of the rectangle.
def setsize(self, size):
self._rectangleObject.setsize(size)
# setfillcolour sets the colour of the rectangle
def setfillcolour(self, fillcolour):
self._rectangleObject.setfillcolour(fillcolour)
# settext sets the text of the text component.
def settext(self, text):
self._textObject.settext(text)
# settextsize sets the font/text size of the text component.
def settextsize(self, size):
self._textObject.settextsize(size)
# settextcolour sets the colour of the text.
def settextcolour(self, textcolour):
self._textObject.settextcolour(textcolour)
# The TextButton is simply a TextRectangle with an attached function reference to allow it to act as a button.
class TextButton(TextRectangle):
def __init__(self, screen, function, position, size, fillcolour, text, textsize, textcolour):
# Inheriting from the TextRectangle class.
TextRectangle.__init__(self, screen, position, size, fillcolour, text, textsize, textcolour)
# Holding the function reference.
self.function = function
# Overriding the gettype method so that it return the correct object type.
def gettype(self):
return "TextButton"
# The TextEntry class is used for user inputting nhumerical values and text, mainly for determining activation constants, synpase initilisation
# values, and the names of input and output neurons.
class TextEntry(TextRectangle):
# class variables used to ensure that each object has a unique ID and only one is selected/being typed into at once.
enabledObject = False
objectID = 0
def __init__(self, screen, position, size, fillcolours, inputtype, textsize, textcolour, name, defaulttext=""):
# Inheriting from the TextRectangle class.
TextRectangle.__init__(self, screen, position, size, fillcolours[1], defaulttext, textsize, textcolour)
# Setting up the object ID.
self._thisObjectID = TextEntry.objectID
# Incrementing the objectID class variable so the next created TextEntry object has an ID one above this one.
TextEntry.objectID += 1
# Storing the fillcolours in a list so True, False can be used as indices for selecting colour.
self._validFillColours = fillcolours
# Storing the validity of the entry
self._invalid = False
# Storing the name, which is to be used to idenitify the object for user input retreival.
self._name = name
# Storing the type of input allowed, in the format shown below.
# {"type" : [numeric, nosymbols, nonumeric, all], "limit" : maxchars, "range" : [min, max]"}
self._inputType = inputtype
# A standard method for GUI objects, setting the fillcolour to reflect the validity of the user's input, then displaying the object through an override.
def paint(self):
# Re-checking the validity of the user input, and setting the fillcolour accordingly.
self._refreshvalidity()
self._rectangleObject.setfillcolour(self._validFillColours[self._invalid])
# Calling the base function for painting a Text Rectangle.
TextRectangle.paint(self)
# refreshvalidity re-checks the validity of the user input based on the input-type
def _refreshvalidity(self):
# storing the text as a local variable to avoid frequent calling of text component methods slowing the program.
currenttext = self._textObject.gettext()
# Checking if the input type is for numeric.
if self._inputType["type"] == "numeric":
if currenttext in ["", "+", "-"]:
self._invalid = True
elif float(currenttext) < self._inputType["range"][0] or float(currenttext) > self._inputType["range"][1]:
self._invalid = True
else:
self._invalid = False
# checking if it is a numericblank input (used for activation constants where it is not always required).
elif self._inputType["type"] == "numericblank":
if currenttext in ["+", "-"]:
self._invalid = True
else:
self._invalid = False
elif self._inputType["type"] == "allnoblank":
if currenttext == "" or all([character == " " for character in currenttext]):
self._invalid = True
else:
self._invalid = False
# Checking if the text is numeric but not zero.
elif self._inputType["type"] == "nonzeronumeric":
if not currenttext.isnumeric():
self._invalid = True
elif float(currenttext) == 0:
self._invalid = True
elif float(currenttext) < self._inputType["range"][0] or float(currenttext) > self._inputType["range"][1]:
self._invalid = True