-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathV3.py
2676 lines (2216 loc) · 113 KB
/
V3.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 math
import time
import random
import os
import ast
import winsound
from pathlib import Path
try:
import ctypes
USER32 = ctypes.windll.user32
except ImportError:
# If user is not on a windows system, win32api will fail to import,
# and the program will instead use default window size
USER32 = False
import pygame as pg
import pygame.math as pgmath
from pygame.locals import *
# An external library that I made - adds tkinter features in pygame
import pgkinter as pgk
pgkRoot = pgk.Pgk()
# Used to draw a line that follows a particle's path
class Graph(object):
def __init__(self, surface, width, height, topleft, bgColour, xLabelGap,
yLabelGap):
self.__screen = surface
self.__width = width
self.__height = height
self.__bgColour = bgColour
self.__rect = pg.Rect(0, 0, self.__width, self.__height)
self.__rect.topleft = (int(topleft[0]), int(topleft[1]))
self.__xLabels = []
x = width
while x > 0:
self.__xLabels.append(width - x)
x -= xLabelGap
self.__yLabels = []
y = height
while y > 0:
self.__yLabels.append(height - y)
y -= yLabelGap
self.__font = pg.font.SysFont("Helvetica", 18)
self.lines = []
def draw(self):
pg.draw.rect(self.__screen, self.__bgColour, self.__rect)
for i in self.__xLabels:
pg.draw.line(self.__screen, (170, 170, 170),
(i, self.__rect.top), (i, self.__rect.bottom), 1)
for i in self.__yLabels:
pg.draw.line(self.__screen, (170, 170, 170),
(self.__rect.left, i), (self.__rect.right, i), 1)
for i in self.lines:
i.draw()
def changeLabelGap(self, xLabelGap, yLabelGap):
self.__xLabels = []
x = self.__width
while x > 0:
self.__xLabels.append(self.__width - x)
x -= xLabelGap
self.__yLabels = []
y = 0
while y < self.__height:
self.__yLabels.append(self.__height - y)
y += yLabelGap
def clearLines(self):
for i in self.lines:
del i
self.lines = []
class Line(object):
def __init__(self, surface, graph, colour):
self.__screen = surface
graph.lines.append(self)
self.__colour = colour
self.__plotCoords = []
def draw(self):
plots = self.__plotCoords
if len(plots) > 1:
pg.draw.lines(self.__screen, self.__colour, False, plots, 2)
def addPlot(self, plot):
self.__plotCoords.append((int(plot[0]), int(plot[1])))
class Particle(pg.sprite.Sprite):
def __init__(self, coefficient, material, rad, density, v, colour, centre,
yA, xA=None):
super().__init__() # Runs pygame sprite __init__() method
self.hasRandomVelocity = False
self.line = False
self.restCoefficient = coefficient
self.material = material
self.radius = rad
self.density = density
self.mass = 0
self.vol = 0
self.updateDimension(rad=self.radius)
self.velocity = pgmath.Vector2(v)
self.colour = colour
self.rect = pg.draw.circle(screen, self.colour, centre,
int(self.radius * scale))
self.rect.x += int(self.radius * scale)
self.rect.y += int(self.radius * scale)
self.pos = pgmath.Vector2(self.rect.x, self.rect.y)
if not xA: # Assigns 0 as default x acceleration, if no value is passed
self.acceleration = pgmath.Vector2(0, yA)
else:
self.acceleration = pgmath.Vector2(xA, yA)
self.direction = 0
self.updateDirection()
# Dictionary storing data on each frame
self.posDict = {
0: (pgmath.Vector2(centre), pgmath.Vector2(v), tNow)
}
self.recentCollisions = []
def angleTo(self, p2):
xDistance = self.pos.x - p2.pos.x
yDistance = self.pos.y - p2.pos.y
# Uses inverse tan function on two lengths. Need to add pi/2 (90deg)
# in order to align with pygame angles (measured from vertical)
return math.atan2(xDistance, yDistance) + math.pi / 2
def collide(self, p2):
collisionDir = self.angleTo(p2)
# Particles have collided - calculate new velocities
m1, m2 = self.mass, p2.mass
v1, v2 = self.velocity, p2.velocity
pos1, pos2 = self.pos, p2.pos
selfNewVelocity = v1 - ((2 * m2) / (m1 + m2)) * (
((v1 - v2).dot(pos1 - pos2)) / (
(pos1 - pos2).length()) ** 2) * (pos1 - pos2)
p2NewVelocity = v2 - ((2 * m1) / (m2 + m1)) * (
((v2 - v1).dot(pos2 - pos1)) / (
(pos2 - pos1).length()) ** 2) * (pos2 - pos1)
self.velocity, p2.velocity = selfNewVelocity, p2NewVelocity
def delete(self):
particles.remove(self)
del self
def draw(self):
pg.draw.circle(screen, self.colour, (self.rect.x, self.rect.y),
int(self.radius * scale))
def drawDirectionArrow(self):
arrow = ARROW_IMAGE # Prevents having to load image every time
arrowscale = (self.radius * scale / arrow.get_width()) * 1.5
# Rotate and scale arrow image to fit particle
arrow = pg.transform.rotozoom(arrow, math.degrees(self.direction),
arrowscale)
arrowRect = arrow.get_rect(center=(self.rect.x, self.rect.y))
screen.blit(arrow, arrowRect)
def hasCollided(self, group):
collisionList = []
# Checks each sprite in the group and if the sum of their radii is less
# than the absolute distance between their centres, they have collided.
for sprite in group.sprites():
totalRad = self.radius * scale + sprite.radius * scale
if absoluteDistance(self.pos, sprite.pos) <= totalRad \
and sprite != self:
collisionList.append(sprite)
return collisionList
def scalePosition(self):
# If the scale has changed since last frame, then the particle will
# get resized and relocated, so that it will be in the same place
# relative to the window and other particles.
if previousScale != scale:
mouseX = pg.mouse.get_pos()[0]
fromMouseX = mouseX - self.pos.x
self.pos.x = mouseX - (fromMouseX * (scale / previousScale))
fromFloor = SH - self.pos.y
self.pos.y = SH - (fromFloor * (scale / previousScale))
self.rect.x, self.rect.y = int(self.pos.x), int(self.pos.y)
else:
pass
def updateDirection(self):
# Gets direction of travel (in radians)
# Multiply by -1 as pygame measures angles anti-clockwise.
self.direction = math.atan2(self.velocity.y, self.velocity.x) * -1
def updateDimension(self, rad=None, mass=None):
# Apply equation v=(4/3)*pi*r^2 and v=m/d to update particles radius if
# mass is changed, and vice-versa
if rad is not None:
self.radius = rad
self.vol = (4 / 3) * math.pi * (self.radius ** 3)
self.mass = roundToSigFig(self.vol * self.density, 3)
elif mass is not None:
self.mass = mass
self.vol = self.mass / self.density
rad = ((3 * self.vol) / (4 * math.pi)) ** (1 / 3)
self.radius = roundToSigFig(rad, 3)
def update(self):
global frameNumber
global tNow
self.scalePosition()
# If time is moving backwards
if TIME_SCALES[currentTimescale] < 0:
try:
# Sets attributes to what they were at the current frame number
p = self.posDict[frameNumber]
self.pos = pgmath.Vector2(p[0].x, p[0].y)
self.velocity = pgmath.Vector2(p[1].x, p[1].y)
tNow = p[2]
except KeyError:
pass
self.updateDirection()
self.rect.x, self.rect.y = int(self.pos.x), int(self.pos.y)
self.draw()
self.drawDirectionArrow()
# If time is moving forward
elif TIME_SCALES[currentTimescale] > 0:
# Only simulate particle's motion if current frame has not
# already been simulated, otherwise simply retrieve its
# positional data from the position dictionary
if frameNumber not in self.posDict:
# Checks if particle has collided with floor. Also checks
# that particle's velocity would take it towards the floor
# in order to make sure that the particle hasn't collided and
# was turned around in the previous frame.
if self.pos.y + self.radius * scale >= SH and \
self.velocity.y * timeMultiplier > 0:
self.velocity.y = roundToSigFig(
self.velocity.y * self.restCoefficient * -1, 4)
self.pos.y = SH - self.radius * scale
# Has collided with ceiling
elif self.pos.y - self.radius * scale <= 0 and \
self.velocity.y * timeMultiplier < 0:
self.velocity.y = roundToSigFig(
self.velocity.y * self.restCoefficient * -1, 4)
self.pos.y = 0 + self.radius * scale
# Has collided with right wall
if self.pos.x + self.radius * scale >= SW and \
self.velocity.x * timeMultiplier > 0:
self.velocity.x = roundToSigFig(
self.velocity.x * self.restCoefficient * -1, 4)
self.pos.x = SW - self.radius * scale
# Has collided with left wall
elif self.pos.x - self.radius * scale <= 0 and \
self.velocity.x * timeMultiplier < 0:
self.velocity.x = roundToSigFig(
self.velocity.x * self.restCoefficient * -1, 4)
self.pos.x = 0 + self.radius * scale
#
# Multiply by timeMultiplier in order to increase velocity by
# the correct amount per second.
self.velocity += self.acceleration * timeMultiplier
self.updateDirection()
# Multiply by scale as velocity is ms^-1, multiply by
# timeMultiplier for the same reasons as before
self.pos += self.velocity * scale * timeMultiplier
# Rect coordinates need to be integers
self.rect.x, self.rect.y = int(self.pos.x), int(self.pos.y)
self.draw()
self.drawDirectionArrow()
collisionList = self.hasCollided(particles)
for particle in collisionList:
# Self is included in collisionList, therefore != self
# check is required
# Also need to check if the particles are moving closer,
# otherwise two that collided last frame wil be treated as
# colliding again this frame.
if particle != self and particle not in \
self.recentCollisions:
# Need to both add the other particle to this
# particle's recentCollisions list, and the other way
# round. If I just added the other particle to this
# particle's collisions list, they would
# occasionally 'collide' twice, as the if not in
# self.recentCollisions check would pass in both
# particles' update methods
self.collide(particle)
self.recentCollisions.append(particle)
particle.recentCollisions.append(self)
for particle in self.recentCollisions:
if particle not in collisionList:
self.recentCollisions.remove(particle)
particle.recentCollisions.remove(self)
if self.line:
self.line.addPlot((self.pos.x, self.pos.y))
elif frameNumber in self.posDict:
# If current frame has already been simulated, grab values
# from posDict
p = self.posDict[frameNumber]
self.pos = pgmath.Vector2(p[0].x, p[0].y)
self.velocity = pgmath.Vector2(p[1].x, p[1].y)
tNow = p[2]
self.updateDirection()
self.rect.x, self.rect.y = int(self.pos.x), int(self.pos.y)
self.draw()
self.drawDirectionArrow()
p = pgmath.Vector2(self.pos.x, self.pos.y)
v = pgmath.Vector2(self.velocity.x, self.velocity.y)
# If time is set to x2 speed
if currentTimescale == 5:
# Need to add data to previous 1 and 1.5 frames
# Interpolates what the position and velocity will be based
# on current velocity and acceleration
if (frameNumber - 1.5) not in self.posDict:
olderPos = p - (v * scale * timeMultiplier * 1.5)
self.posDict[frameNumber - 1.5] = (olderPos, v, tNow)
if (frameNumber - 1) not in self.posDict:
oldPos = p - (v * scale * timeMultiplier)
self.posDict[frameNumber - 1] = (oldPos, v, tNow)
# x1 or x2
if currentTimescale in [4, 5]:
# Need to add data to previous 1/2 of a frame
# Interpolates what the position and velocity will be based
# on current velocity and acceleration
if (frameNumber - 0.5) not in self.posDict:
oldPos = p - (
v * scale * timeMultiplier * 0.5)
self.posDict[frameNumber - 0.5] = (oldPos, v, tNow)
if frameNumber not in self.posDict:
# Will always add data for the current frame if it is not
# already in the dictionary
self.posDict[frameNumber] = (p, v, tNow)
# All of these checks mean that every frame (and the half frames
# in between them) will be included in the dictionary, allowing
# the user to rewind through at any speed.
def absoluteDistance(pVector1, pVector2):
distance = pVector1 - pVector2
return distance.length()
def drawDottedLine(start, end):
# Used when resizing particles, to create the same look as in Blender
# (Dotted line from the centre of the object being resized to the mouse)
xLen = end[0] - start[0]
yLen = end[1] - start[1]
xStep = xLen / 10
yStep = yLen / 10
xCoord = start[0]
yCoord = start[1]
for i in range(0, 5):
pg.draw.line(screen, (33, 33, 33), (xCoord, yCoord),
(xCoord + xStep, yCoord + yStep), 2)
xCoord += 2 * xStep
yCoord += 2 * yStep
# Code snippet found online - rounds a number, x, to a given number of
# significant figures, n.
def roundToSigFig(x, n):
if x != 0:
return round(x, -int(math.floor(math.log10(abs(x)))) + (n - 1))
else:
return 0
def timeChange(speedUp):
global currentTimescale
# User can only speed up if the current timescale is at most one less
# than the maximum. Similarly, they can only decrease the timescale if it
# is a least one more than the minimum. This is to prevent the timescale
# from going out of bounds.
if 0 <= currentTimescale < len(TIME_SCALES) - 1 and speedUp == 1:
currentTimescale += 1
elif 0 < currentTimescale <= len(TIME_SCALES) - 1 and speedUp == -1:
currentTimescale -= 1
# Each procedure which contains a loop needs to have at least one argument,
# whether it is used or not, as the loop that prevents recursion needs to
# pass an argument (it passes *args, which cannot pass nothing). So I put a
# dummy argument in the procedures that don't need anything to be passed to
# them.
def mainMenu(dummyArg):
global mainmenu
global mainWidgets
global currentTimescale
global tNow
global frameNumber
global particleGraph
global scale
global previousScale
def endFunction(widgets, goTo, args):
# Can't use buttons to set variables, so I need to use this function
# to set global variables that will be
global nextFunc
global nextArgs
global mainmenu
if goTo == instructions:
instructions(*args)
return
widgets[-1].startAnimation("horizontalslide", 0.5, "out", 0 - SW, True)
mainmenu, nextFunc, nextArgs = False, goTo, args
def exitProgram():
pg.quit()
quit()
global timeMultiplier
dvdLogo = pg.image.load(
str(imagesFolder / "DVDlogo.png")).convert_alpha()
dvdLogo = pg.transform.scale(dvdLogo, (int(scaler(262, "x")), int(scaler(
150, "y"))))
x = random.randint(int(SW * 0.1), int(SW * 0.9))
y = random.randint(int(SH * 0.1), int(SH * 0.9))
dvdRect = dvdLogo.get_rect(center=(x, y))
dvdXSpeed = random.choice([1, -1])
dvdYSpeed = random.choice([1, -1])
# Uncomment to hit corner
# x = 500
# y = 500
#
# dvdRect = dvdLogo.get_rect(topleft=(x, y))
# dvdXSpeed = random.choice([-1])
# dvdYSpeed = random.choice([-1])
# Reset scale nd time-related globals to their default values - prevents
# bugs when going from a simulation to the menu, and then into another
# simulation
currentTimescale = 4
tNow = 0
frameNumber = 0
scale = scaler(100, "x")
previousScale = scale
particleGraph.clearLines()
del particleGraph
particleGraph = Graph(screen, SW, SH, (0, 0), BG_COLOUR, scale, scale)
mainContainer = pgk.Container(pgkRoot, screen, topleft=(0, 0),
width=SW, height=SH)
mainWidgets = [
pgk.Label(pgkRoot, screen, centre=(SW / 2, scaler(135, "y")),
font=LARGE_FONT,
text="Particle Simulator V3 or something idk",
container=mainContainer),
pgk.Label(pgkRoot, screen, centre=(SW / 2, scaler(200, "y")),
font=SMALL_FONT,
text="'A man dies, when he is forgotten' - Theo",
container=mainContainer)
]
buttonX = scaler(640, "x")
mainWidgets += [
pgk.Button(pgkRoot, screen, buttonX, scaler(425, "y"), font=MID_FONT,
bgColour=(33, 33, 33), text="Create a simulation",
height=scaler(115, "y"), width=scaler(640, "x"),
action=lambda: endFunction(mainWidgets, setup, (1,)),
container=mainContainer, swellOnHover=True),
pgk.Button(pgkRoot, screen, buttonX, scaler(560, "y"), font=MID_FONT,
bgColour=(33, 33, 33), text="Load a saved simulation",
height=scaler(115, "y"), width=scaler(640, "x"),
action=lambda: endFunction(mainWidgets, loadSetup,
(None,)),
container=mainContainer, swellOnHover=True),
pgk.Button(pgkRoot, screen, buttonX, scaler(695, "y"), font=MID_FONT,
bgColour=(33, 33, 33), text="Instructions",
height=scaler(115, "y"), width=scaler(640, "x"),
action=lambda: endFunction(mainWidgets, instructions,
(mainWidgets,)),
container=mainContainer, swellOnHover=True),
pgk.Button(pgkRoot, screen, buttonX, scaler(830, "y"), font=MID_FONT,
bgColour=(33, 33, 33), text="Exit program :(",
height=scaler(115, "y"), width=scaler(640, "x"),
action=exitProgram,
container=mainContainer, swellOnHover=True),
]
mainWidgets.append(mainContainer)
del mainContainer
mainWidgets[-1].startAnimation("horizontalslide", 0.5, "in", SW)
mainmenu = True
while mainmenu:
for event in pg.event.get():
pgkRoot.eventHandler(event)
if event.type == QUIT:
mainmenu = False
pg.quit()
quit()
try:
# If statement prevents 'jumping' of particles when user moves
# the window
if time.time() - previousFrame < 0.1:
timeMultiplier = (time.time() - previousFrame)
timeMultiplier *= TIME_SCALES[currentTimescale]
# Calculates time between frames
previousFrame = time.time()
except NameError:
# Will occur on the first frame, as there is no previous frame
pass
screen.fill(BG_COLOUR)
if dvdRect.left <= 0 or dvdRect.right >= SW:
dvdXSpeed = -dvdXSpeed
if dvdRect.top <= 0 or dvdRect.bottom >= SH:
dvdYSpeed = -dvdYSpeed
dvdRect.x += dvdXSpeed
dvdRect.y += dvdYSpeed
screen.blit(dvdLogo, dvdRect)
pgkRoot.update()
pg.display.update()
fps = str(int(clock.get_fps()))
pg.display.set_caption('HAHA CIRCLE GO BRR | FPS: ' + fps)
clock.tick()
# Returns the function that runs next (setup) and the args to pass to that
# function (*args requires a tuple to unpack)
return nextFunc, nextArgs
def instructions(mainMenuWidgets):
global instructing
def changePage(goToPage, pages, mainMenuWidgets):
global instructing
# First page slides to the right and gets deleted, main menu slides
# back in from the left, and delete the second page
if goToPage == -1:
pages[0][-1].startAnimation("horizontalslide", 0.5, "out", SW, True)
mainMenuWidgets[-1].startAnimation("horizontalslide", 0.5, "out", 0)
for i in pages[1]:
i.delete()
instructing = False
# First page slides to the left, second page slides in from the right
elif goToPage == 0:
pages[1][-1].startAnimation("horizontalslide", 0.5, "out", SW)
pages[0][-1].startAnimation("horizontalslide", 0.5, "out", 0)
# Second page slides to the right, second page slides in from the left
elif goToPage == 1:
pages[0][-1].startAnimation("horizontalslide", 0.5, "out", 0 - SW)
pages[1][-1].startAnimation("horizontalslide", 0.5, "in", SW,
destination=(0, 0))
# Second page slides to the left and gets deleted, main menu slides
# back in from the right, and delete the first page
elif goToPage == 2:
pages[1][-1].startAnimation("horizontalslide", 0.5, "out", 0 - SW,
True)
mainMenuWidgets[-1].startAnimation("horizontalslide", 0.5, "out",
0, destination=(SW, 0))
for i in pages[0]:
i.delete()
instructing = False
mainMenuWidgets[-1].startAnimation("horizontalslide", 0.5, "out", 0 - SW)
files = ["setupInstructions.txt", "mainInstructions.txt"]
pageTitles = ["Setup", "Simulation"]
pages = []
currentPage = 0
for i in files:
# Iterate through instruction files, creating labels and buttons
with open(i, "r") as f:
lines = f.readlines()
text = ''.join(lines)
pageContainer = pgk.Container(pgkRoot, screen, topleft=(0, SW),
width=SW, height=SH)
page = [
pgk.Label(pgkRoot, screen, centre=(SW / 2, scaler(135, "y")),
font=LARGE_FONT, text=pageTitles[currentPage],
container=pageContainer),
pgk.Label(pgkRoot, screen, centre=(SW / 2,
SH / 2 + scaler(135, "y")),
height=SH - scaler(135, "x"), width=SW * 0.8,
font=MID_FONT, text=text, container=pageContainer),
]
# Need to explicitly state the page values for the buttons - can't
# use currentPage + or - 1. This is because lambda passes the
# arguments as they are at the time of the button press. In this case
# that means that the previous page button will always pass 1,
# and the next page will always pass 3.
if currentPage == 0:
page += [
pgk.Button(pgkRoot, screen, 0, 0, height=SH, width=int(SW / 10),
action=lambda: changePage(-1, pages,
mainMenuWidgets),
image=L_MENU_IMG, hoverImage=L_MENU_IMG,
container=pageContainer),
pgk.Button(pgkRoot, screen, SW - int(SW / 10), 0, height=SH,
width=int(SW / 10),
action=lambda: changePage(1, pages,
mainMenuWidgets),
image=NEXT_IMG, hoverImage=NEXT_IMG,
container=pageContainer),
pageContainer
]
else:
page += [
pgk.Button(pgkRoot, screen, 0, 0, height=SH, width=int(SW / 10),
action=lambda: changePage(0, pages,
mainMenuWidgets),
image=PREV_IMG, hoverImage=PREV_IMG,
container=pageContainer),
pgk.Button(pgkRoot, screen, SW - int(SW / 10), 0, height=SH,
width=int(SW / 10),
action=lambda: changePage(2, pages,
mainMenuWidgets),
image=R_MENU_IMG, hoverImage=R_MENU_IMG,
container=pageContainer),
pageContainer
]
del pageContainer
pages.append(page)
currentPage += 1
pages[0][-1].startAnimation("horizontalslide", 0.5, "in", SW,
destination=(0, 0))
instructing = True
while instructing:
for event in pg.event.get():
pgkRoot.eventHandler(event)
if event.type == QUIT:
instructing = False
pg.quit()
quit()
screen.fill(BG_COLOUR)
pgkRoot.update()
pg.display.update()
fps = str(int(clock.get_fps()))
pg.display.set_caption('HAHA CIRCLE GO BRR | FPS: ' + fps)
clock.tick()
return
def setup(dummyArg):
global scale
global previousScale
global setupTime
global setting
global editingParticle
# Times the animation for setupContainer
setupTime = None
# Controls setup loop
setting = True
# List of widgets used when editing a placed particle
editList = None
# The particle being edited
editingParticle = None
# How many metres are shown in the scale display
metres = 1
def endFunction(widgetList):
# Starts the setupContainer's slide out animation
widgetList[-1].startAnimation("horizontalslide", 0.1, "out",
SW + contWidth, deleteAfter=True)
def endParticleEdit(editList):
global editingParticle
# Menu for editing a particle will disappear
editList[-1].startAnimation("centre", 0.25, "out", deleteAfter=True)
editingParticle = None
# Delete all widgets - to start with a 'clean slate'
# for i in pgkRoot.pgkGroup.sprites():
# i.delete()
def updateParticle(pRef, inputs, editing=None):
# Editing argument specifies whether or not the particle being
# updated has already been placed
try:
# Easier to add new inputs - only need to change index here
coefficientBox = inputs[0]
coefficient = float(inputs[0].get())
xVel = float(inputs[1].get())
yVel = float(inputs[2].get())
xAccel = float(inputs[3].get())
yAccel = float(inputs[4].get())
radBox = inputs[5]
rad = float(radBox.get())
massBox = inputs[6]
mass = float(massBox.get())
height = float(inputs[7].get())
lockHeight = inputs[8].get()
randomV = inputs[9].get()
drawGraph = inputs[10].get()
material = inputs[11].get()
if material in MATERIALS:
density, colour = MATERIALS[material][0], MATERIALS[material][1]
else:
density, colour = customMaterials[material][0], \
customMaterials[material][1]
pRef.colour = colour
except ValueError:
return
mouseX = pg.mouse.get_pos()[0]
mouseY = pg.mouse.get_pos()[1]
if coefficient > 1:
coefficientBox.write("1")
elif coefficient < 0:
coefficientBox.write("0")
else:
pRef.restCoefficient = coefficient
if not randomV:
pRef.velocity.x = xVel
pRef.velocity.y = yVel
pRef.hasRandomVelocity = False
elif randomV and not pRef.hasRandomVelocity:
upper = pRef.radius * 5
lower = upper * -1
# random.uniform instead of random.randint as uniform allows for
# two floating point numbers as the bounds
pRef.velocity.x = roundToSigFig(random.uniform(lower, upper), 3)
pRef.velocity.y = roundToSigFig(random.uniform(lower, upper), 3)
inputs[1].write(str(pRef.velocity.x))
inputs[2].write(str(pRef.velocity.y))
pRef.hasRandomVelocity = True
if not drawGraph and pRef.line:
pRef.line = False
elif drawGraph and not pRef.line:
pRef.line = Line(screen, particleGraph, colour)
pRef.acceleration.x = xAccel
pRef.acceleration.y = yAccel
# If user has selected that they want the particle to be locked to a
# certain height
if lockHeight:
if editing is None:
pRef.pos.x = mouseX
pRef.rect.x = mouseX
pRef.pos.y = SH - int(height * scale) - pRef.radius * scale
pRef.rect.y = SH - int(height * scale) - pRef.radius * scale
else:
if editing is None:
pRef.pos.x = mouseX
pRef.pos.y = mouseY
pRef.rect.x = mouseX
pRef.rect.y = mouseY
minRad = roundToSigFig(scaler(10, "x") / scale, 3)
maxRad = roundToSigFig((SW / 4) / scale, 3)
# Only update particle's radius/mass if they are not already equal to
# the values entered by the user
if density != pRef.density:
pRef.density = density
pRef.colour = colour
pRef.updateDimension(rad=rad)
radBox.write(str(pRef.radius))
massBox.write(str(pRef.mass))
elif rad != pRef.radius and minRad <= rad <= maxRad:
pRef.updateDimension(rad=rad)
massBox.write(str(pRef.mass))
elif mass != pRef.mass:
pRef.updateDimension(mass=mass)
radBox.write(str(pRef.radius))
if pRef.radius > maxRad:
pRef.updateDimension(rad=roundToSigFig((SW / 4) / scale, 3))
radBox.write(str(pRef.radius))
massBox.write(str(pRef.mass))
elif pRef.radius < minRad:
pRef.updateDimension(rad=roundToSigFig(scaler(10, "x") / scale, 3))
radBox.write(str(pRef.radius))
massBox.write(str(pRef.mass))
pRef.material = material
def deleteParticle(particle):
particle.delete()
def clearParticles():
for particle in particles.sprites():
particle.delete()
particles.add(Particle(1, "Custom Material 1 - 1.0kgm^-3",
roundToSigFig((SW / 4) / scale, 3), 1, (0, 0),
(144, 202, 249),
(int(pg.mouse.get_pos()[0]),
int(pg.mouse.get_pos()[1])), 0, xA=0))
setupContainer = pgk.Container(pgkRoot, screen,
topright=(SW, 0),
outlineThickness=0, width=scaler(400, "x"),
height=scaler(520, "y"))
contWidth = scaler(400, "x")
offset = scaler(150, "x")
boxWidth = scaler(125, "x")
inputList = [
pgk.InputBox(pgkRoot, screen, contWidth - offset, scaler(55, "y"),
font=SMALL_FONT, bgColour=(222, 222, 222),
inlineText="Coefficient of Restitution:",
width=boxWidth, allowLetters=False,
allowSpecial=False, allowSpace=False, charLimit=10,
defaultEntry="0.75", container=setupContainer),
pgk.InputBox(pgkRoot, screen, contWidth - offset, scaler(105, "y"),
font=SMALL_FONT, bgColour=(222, 222, 222),
inlineText="Velocity to the right (ms^-1):",
width=boxWidth, allowLetters=False,
allowSpecial=False, allowSpace=False, charLimit=10,
defaultEntry="0", container=setupContainer),
pgk.InputBox(pgkRoot, screen, contWidth - offset, scaler(155, "y"),
font=SMALL_FONT, bgColour=(222, 222, 222),
inlineText="Velocity downwards (ms^-1):",
width=boxWidth, allowLetters=False,
allowSpecial=False, allowSpace=False, charLimit=10,
defaultEntry="0", container=setupContainer),
pgk.InputBox(pgkRoot, screen, contWidth - offset, scaler(205, "y"),
font=SMALL_FONT, bgColour=(222, 222, 222),
inlineText="Acceleration to the right (ms^-2):",
width=boxWidth, allowLetters=False,
allowSpecial=False, allowSpace=False, charLimit=10,
defaultEntry="0", container=setupContainer),
pgk.InputBox(pgkRoot, screen, contWidth - offset, scaler(255, "y"),
font=SMALL_FONT, bgColour=(222, 222, 222),
inlineText="Acceleration downwards (ms^-2):",
width=boxWidth, allowLetters=False,
allowSpecial=False, allowSpace=False, charLimit=10,
defaultEntry="0", container=setupContainer),
pgk.InputBox(pgkRoot, screen, contWidth - offset, scaler(305, "y"),
font=SMALL_FONT, bgColour=(222, 222, 222),
inlineText="Radius (m):", width=boxWidth, charLimit=10,
allowLetters=False, allowSpecial=False, allowSpace=False,
defaultEntry="0.5", container=setupContainer),
pgk.InputBox(pgkRoot, screen, contWidth - offset, scaler(355, "y"),
font=SMALL_FONT, bgColour=(222, 222, 222),
inlineText="Mass (kg):", width=boxWidth, charLimit=10,
allowLetters=False, allowSpecial=False, allowSpace=False,
defaultEntry="0.5236", container=setupContainer),
pgk.InputBox(pgkRoot, screen, contWidth - offset, scaler(405, "y"),
font=SMALL_FONT, bgColour=(222, 222, 222),
inlineText="Height off of ground (m):",
width=boxWidth, allowLetters=False,
allowSpecial=False, allowSpace=False, charLimit=10,
defaultEntry="0", container=setupContainer),
pgk.Checkbox(pgkRoot, screen,
contWidth - scaler(50, "x"), scaler(455, "y"),
font=SMALL_FONT, bgColour=(222, 222, 222),
inlineText="Lock particle to height: ",
container=setupContainer),
pgk.Checkbox(pgkRoot, screen,
contWidth - scaler(50, "x"), scaler(505, "y"),
font=SMALL_FONT, bgColour=(222, 222, 222),
inlineText="Select for random velocity: ",
container=setupContainer),
pgk.Checkbox(pgkRoot, screen,
contWidth - scaler(50, "x"), scaler(555, "y"),
font=SMALL_FONT, bgColour=(222, 222, 222),
inlineText="Draw line following particle's motion: ",
container=setupContainer),
# Create dropdown menu last as it needs to be drawn on top of the other
# inputs
pgk.Dropdown(pgkRoot, screen, contWidth - offset -
boxWidth, scaler(5, "y"), sortedCustoms + MATERIALS_SORTED,
font=SMALL_FONT, bgColour=(222, 222, 222),
inlineText="Select material (scroll to see more):",
width=boxWidth * 2, container=setupContainer)
]
# Y distance between the buttons
buttonGap = scaler(50, "y") + inputList[0].getHeight()
inputList += [
pgk.Button(pgkRoot, screen,
contWidth - scaler(350, "x"), scaler(605, "y"),
font=MID_FONT,
bgColour=(33, 33, 33),
text="Create Custom Material",
height=inputList[0].getHeight() * 2,
width=scaler(325, "x"),
action=lambda: createMaterial(widgetList),
container=setupContainer, swellOnHover=True),
pgk.Button(pgkRoot, screen,
contWidth - scaler(350, "x"),
scaler(605, "y") + buttonGap, font=MID_FONT,
bgColour=(33, 33, 33),
text="Save Scenario",
height=inputList[0].getHeight() * 2,
width=scaler(325, "x"),
action=lambda: saveSetup(widgetList),