-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.pyw
More file actions
1444 lines (1058 loc) · 45.4 KB
/
main.pyw
File metadata and controls
1444 lines (1058 loc) · 45.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
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
# ================================== Imports =================================
import sys
# sys.stdout = open("mylog.txt", "w")
# sys.stderr = open("errors.txt", "w")
import time
import json
try:
import Tkinter
import cPickle as pickle
import tkFileDialog as filedialog
import tkMessageBox as messagebox
import tkColorChooser as colorchooser
import tkSimpleDialog as simpledialog
except ModuleNotFoundError:
import tkinter as Tkinter
import pickle
from tkinter import filedialog
from tkinter import messagebox
from tkinter import colorchooser
from tkinter import simpledialog
from circle import *
# ================================= variables ================================
'''
********************************************************************************
Class: Enum
Definition: this is a class i made to represent the Enum datatype available
in most languages.
Author: ty Silva
Date: 4-5-2019
History:
********************************************************************************
'''
class Enum:
dic = {}
'''
********************************************************************************
Function: __init__
Definition: this takes all of the arguments, assumes they are strings, and
adds them to a dictionary, with the string as the key, and an
integer as the value
Author: ty Silva
Date: 4-5-2019
History:
********************************************************************************
'''
def __init__(self, *args):
for j in range(0, len(args)):
self.dic[args[j]] = j
'''
********************************************************************************
Function: __getitem__
Definition: this is a magic function called when enum is indexed into, ie:
hello["world"] would call hello.__getitem__("world")
Author: ty Silva
Date: 4-5-2019
History:
********************************************************************************
'''
def __getitem__(self, item):
return self.dic[item]
'''
********************************************************************************
Function: __getattr__
Definition: this function is called when you attempt to get an attribute
from the object, ie: hello.world would call
hello.__getattr__("world")
Author: ty Silva
Date: 4-5-2019
History:
********************************************************************************
'''
def __getattr__(self, item):
return self.dic[item]
'''
********************************************************************************
Function: keyName
Definition: this function is called to get the keyname of a key as a string
from the enum value
Author: ty Silva
Date: 5-1-2019
History:
********************************************************************************
'''
def key_name(self, item):
return self.dic.keys()[item]
# This is the default JSON file for the shotcuts, in case the original one gets
# Corrupted
defaultJson = '''{
"delete":"<d>",
"create":"<c>",
"push":"<p>",
"pause":"<space>"
}'''
framerate = 1.0 / 60.0 # Determines the number of seconds per frame.
shapes = [] # Where all of the circles that physics applies to are stored
width = 1200 # Width of the screen
height = 800 # Height of the screen
noPhysicsShapes = [] # Where all of the other circles will be placed
lines = [] # Where individual lines are stored, no physics is applied
circleId = 0 # The highest circle ID currently used.
# This is an enum of all the states that the cursor can be in
States = Enum("debug", "create", "delete", "push", "move", "none")
state = States.none # This is the current state that cursor is in.
# This is used for communication between onclick and onrelease mouse events.
validShape = False
click = False # This is used for a similar purpose.
shapeToMove = [] # Again, used for communication.
# This is used to communicate where mouse was from onclick to onrelease events
x = 0
y = 0
# This is used to store the mouse position relative to the window
mouseX = 0
mouseY = 0
# This is used to store the mouse position relative to the screen (top left of
# Leftmost screen)
globalX = 0
globalY = 0
playing = True # Whether or not the simulation is playing
running = True # Whether or not the program should be running
color = "white" # Default color for circles.
showVel = False # Whether to show velocities or not
trail_length = 10 # Default length of the trail, if trails are turned on.
# ================================ functions ================================
# ============================ state controllers ============================
'''
********************************************************************************
Function: ToggleVelocities
Definition: Toggles whether or not velocities are shown.
Author: ty Silva
Date: 5-1-2019
History:
********************************************************************************
'''
def toggle_velocities():
global showVel
showVel = not showVel
'''
********************************************************************************
Function: set_create
Definition: Sets the cursor state to create
Author: ty Silva
Date: 4-5-2019
History:
********************************************************************************
'''
def set_create(*args):
if args: # To get rid of useless parameter warning
pass
global state
state = States.create
'''
********************************************************************************
Function: set_push
Definition: Sets the cursor state to push
Author: ty Silva
Date: 4-5-2019
History:
********************************************************************************
'''
def set_push(*args):
if args: # To get rid of useless parameter argument
pass
global state
state = States.push
'''
********************************************************************************
Function: set_delete
Definition: Sets the cursor state to delete
Author: ty Silva
Date: 4-5-2019
History:
********************************************************************************
'''
def set_delete(*args):
if args: # To get rid of useless parameter argument
pass
global state
state = States.delete
'''
********************************************************************************
Function: debug
Definition: Sets the cursor state to debug
Author: ty Silva
Date: 4-5-2019
History:
********************************************************************************
'''
def debug(*args):
if args: # To get rid of useless parameter argument
pass
global state
state = States.debug
'''
********************************************************************************
Function: set_move
Definition: Sets the cursor state to move
Author: ty Silva
Date: 4-5-2019
History:
********************************************************************************
'''
def set_move(*args):
if args: # To get rid of useless parameter argument
pass
global state
state = States.move
'''
********************************************************************************
Function: start_trail
Definition: sets the shape that was clicked on to leave a trail.
Author: ty Silva
Date: 5-1-2019
History:
********************************************************************************
'''
def start_trail(circles):
global shapes
for j in circles:
shapes[j].use_trail = not shapes[j].use_trail
# ============================= Misc Functions ==============================
'''
********************************************************************************
Function: test
Definition: Generic function i can use for testing things, changes often and
rarely kept here. Disabled for public tests.
Author: ty Silva
Date: 4-5-2019
History:
********************************************************************************
'''
def test(event=None):
if event: # To get rid of useless parameter argument
pass
'''root.overrideredirect(True)
#root.geometry("+250+250")
root.lift()
root.wm_attributes("-topmost", True)
#root.wm_attributes("-disabled", True)
root.wm_attributes("-transparentcolor", "white")
root.config(menu = Tkinter.Menu(root))
root.unbind(shortcuts["delete"])
root.unbind(shortcuts["create"])
root.unbind(shortcuts["push"])
root.unbind(shortcuts["pause"])
root.attributes("-fullscreen", True)
# root.wm_attributes("-transparentcolor", "black")'''
retval = Vector2D(0.0, 0.0)
for j in shapes:
retval += j.velocity
print (retval.x + retval.y)
'''
********************************************************************************
Function: destroy
Definition: Closes the window safely, so there isn't an error. It takes
*args so that it can be called from keypress or click of a
button, as a keypress passes the "event" argument
Author: ty Silva
Date: 4-5-2019
History:
********************************************************************************
'''
def destroy(*args):
if args: # To get rid of useless parameter argument
pass
global running
running = False
'''
********************************************************************************
Function: motion
Definition: This event is called on the motion of the mouse. It saves the
local and global mouse position to the correct global variables.
Author: ty Silva
Date: 4-5-2019
History:
********************************************************************************
'''
def motion(event):
global mouseX, mouseY, globalX, globalY
mouseX, mouseY = event.x, event.y
globalX = root.winfo_pointerx() - root.winfo_vrootx()
globalY = root.winfo_pointery() - root.winfo_vrooty()
'''
********************************************************************************
Function: toggle_play
Definition: Toggles whether the simulation is playing or not.
Author: ty Silva
Date: 4-5-2019
History:
********************************************************************************
'''
def toggle_play(event=None):
if event: # To get rid of useless parameter argument
pass
global playing
playing = not playing
'''
********************************************************************************
Function: resize
Definition: This event is called on the window being resized, among other
things, but i'm using it only to handle resizing of the window.
When the window is resized, the canvas is also changed to take
up the entire screen.
Author: ty Silva
Date: 4-5-2019
History:
********************************************************************************
'''
def resize(event):
global width
global height
width = event.width
height = event.height
w.configure(width=width, height=height)
# ============================ Circle Functions ==============================
'''
********************************************************************************
Function: precise_circle
Definition: creates a precise circle at a given point, using
Author: ty Silva
Date: 5-1-2019
History:
********************************************************************************
'''
def precise_circle():
# Gets the x coordinate to place the circle at
local_x = simpledialog.askinteger("Coords", "X coordinate", minvalue=0,
maxvalue=width, parent=root)
# Gets the y coordinate to place the circle at
local_y = simpledialog.askinteger("Coords", "Y coordinate", minvalue=0,
maxvalue=height, parent=root,
initialvalue=300)
# Gets the radius to make the circle.
radius = simpledialog.askinteger("Radius", "Radius", parent=root,
minvalue=3, initialvalue=50)
# Gets the x velocity to make the circle move at
vx = simpledialog.askfloat("Velocity", "X Velocity", minvalue=0,
parent=root, initialvalue=0)
# Gets the y velocity to make the circle move at
vy = simpledialog.askfloat("Velocity", "Y Velocity", minvalue=0,
parent=root, initialvalue=0)
# If all popups got an answer
if not (local_x is None or local_y is None or radius is None or
vx is None or vy is None):
global circleId
# Create a circle object, with the x, y, and radius defined earlier.
retval = Circle(Vector2D(local_x, local_y), radius, True, circleId,
color=color)
# retval.velocity = Vector2D(((random()*2)-1)*.1, ((random()*2)-1)*.1)
vel = Vector2D(vx, vy) # Set velocity to what was defined earlier.
retval.velocity = vel
collision = circle_invalid(retval, 2)
if len(collision) > 0: # If the circle can be placed there
messagebox.showinfo("Error", "Cannot place a circle, position "
"requested is obstructed.",
icon="error", parent=temp) # Tell the user no
else:
circleId += 1
shapes.append(retval) # Add circle to array of circles.
'''
********************************************************************************
Function: circle_at_pos
Definition: Checks if there is a circle at the given x and y value. Returns
the circle object
Author: ty Silva
Date: 4-5-2019
History:
********************************************************************************
'''
def circle_at_pos(local_x, local_y):
retval = []
for j in shapes:
# If the distance from where the circle is to the point it's checking is
# Is less than the radius of the circle
if abs(line_length(Vector2D(local_x, local_y), j.coords)) < j.radius:
retval.append(j)
return retval
'''
********************************************************************************
Function: circle_at_pos2
Definition: Checks if there is a circle at the given x and y value. Returns
the index where the circle object is object
Author: ty Silva
Date: 4-5-2019
History:
********************************************************************************
'''
def circle_at_pos2(local_x, local_y):
retval = []
for j in range(0, len(shapes)):
# If the distance from where the circle is to the point it's checking is
# Is less than the radius of the circle
if abs(line_length(Vector2D(local_x, local_y), shapes[j].coords)) < \
shapes[j].radius:
retval.append(j)
return retval
'''
********************************************************************************
Function: circle_invalid
Definition: Checks to see if a circle is able to be placed where it
currently is, without colliding with any other circles.
Author: ty Silva
Date: 4-5-2019
History:
********************************************************************************
'''
def circle_invalid(circle, error=10):
retval = []
for j in shapes:
# If the distance from one circle's center to another circle's center is
# Greater than the sum of their radii
if line_length(circle.coords, j.coords
) <= (circle.radius + j.radius) + error:
retval.append(j)
return retval
'''
********************************************************************************
Function: max_radius
Definition: This takes a point, a desired radius, and the circle that causes
the desired radius to be a problem. It then uses that
information to get the largest possible radius the circle can
have while still not touching anything.
Author: ty Silva
Date: 4-5-2019
History:
********************************************************************************
'''
def max_radius(coords, radius, collision):
closest = collision[0] # Assumes that the closest one is the first one.
smallestdist = line_length(coords, collision[0].coords) - collision[
0].radius
for j in collision:
# If another is closer
if line_length(coords, j.coords) - j.radius < smallestdist:
# Set that to be the smallest
smallestdist = line_length(coords, j.coords) - j.radius
closest = j
# Get the distance to closeset circle
distance = line_length(coords, closest.coords)
# The distance to the nearest circle minus that circle's radius is the
# Closest it can get. Subtract 10 just in case.
retval = distance - closest.radius - 10
return min(retval, radius)
'''
********************************************************************************
Function: delete_shapes
Definition: Deletes a circle from the array, and then re-id's them, so that
none of the Ids are missing.
Author: ty Silva
Date: 4-5-2019
History:
********************************************************************************
'''
def delete_shapes(index):
global circleId
for j in range(0, len(index)):
del shapes[index[j] - j]
for j in range(0, len(shapes)):
shapes[j].id = j
circleId = len(shapes)
'''
********************************************************************************
Function: to_delete
Definition: Checks if the shape is completely off the screen.
Author: ty Silva
Date: 4-5-2019
History:
********************************************************************************
'''
def to_delete(shape):
return (shape.coords.x + shape.radius < 0 or
shape.coords.x - shape.radius > width or
shape.coords.y + shape.radius < 0 or
shape.coords.y - shape.radius > height)
'''
********************************************************************************
Function: new_circle
Definition: Creates a new circle, if someone tries to create a circle with a
radius too small to be used.
Author: ty Silva
Date: 4-5-2019
History:
********************************************************************************
'''
def new_circle(x_val, y_val):
radius = simpledialog.askinteger("Radius", "What should the radius be?",
parent=root, minvalue=3)
if radius is not None: # If something was enetered in the popup
global circleId
# Creates a circle where the mouse was, with the radius from the popup.
retval = Circle(Vector2D(x_val, y_val), radius, True, circleId,
color=color)
# retval.velocity = Vector2D(((random()*2)-1)*.1, ((random()*2)-1)*.1)
retval.velocity = Vector2D(0, 0)
collision = circle_invalid(retval) # Check if a circle fits there.
if len(collision) > 0:
# Make the radius smaller if it can't fit where it was attempted to
# be placed
retval.radius = max_radius(retval.coords, retval.radius, collision)
if retval.radius > 3:
circleId += 1
shapes.append(retval) # Create the circle
'''
********************************************************************************
Function: change_color
Definition: Changes the color of a cirlce.
Author: ty Silva
Date: 4-5-2019
History:
********************************************************************************
'''
def change_color(change):
global shapes
# Gets the color to change to
new_color = (colorchooser.askcolor(title="Pick a new color", parent=root))
for j in change:
shapes[j].color = new_color[1] # Changes the color, using the hex value
'''
********************************************************************************
Function: stop
Definition: Stops a circle at a position
Author: ty Silva
Date: 4-5-2019
History:
********************************************************************************
'''
def stop(circles):
global shapes
for j in circles:
shapes[j].velocity = Vector2D(0.0, 0.0) # Sets the velocity to 0
# ======================= File Manipulation Functions ========================
'''
********************************************************************************
Function: save_shapes
Definition: Saves the shapes file to a location of the user's choice.
Author: ty Silva
Date: 4-5-2019
History:
********************************************************************************
'''
def save_shapes():
# Asks the user where to save the file to
file_name = filedialog.asksaveasfilename(parent=root, title="Save As",
filetypes=[("Saved Shapes File",
"*.p")],
defaultextension="p")
if not file_name == "": # If user entered something
fi = open(file_name, "wb") # Open the file
pickle.dump(shapes, fi) # Save the shapes to the file
fi.close()
'''
********************************************************************************
Function: load_shapes
Definition: Loads the shapes from a file of the user's choice
Author: ty Silva
Date: 4-5-2019
History:
********************************************************************************
'''
def load_shapes():
# Gets the file directory of the file to load from the user
file_name = filedialog.askopenfilename(parent=root, title="Load",
filetypes=[("Saved Shapes File",
"*.p")],
defaultextension="p")
if not file_name == "": # If the user provided a file name
global shapes
fi = open(file_name, "rb")
shapes = pickle.load(fi) # Put the contents of the file into the
fi.close()
# ========================== Menu Making Functions ===========================
'''
********************************************************************************
Function: right_click
Definition: This is the handler for when the right mouse button is pressed.
it opens a new menu for all these options
Author: ty Silva
Date: 4-5-2019
History:
********************************************************************************
'''
def right_click(event):
global playing
playing = False # Stops the simulation from running
# Finds the circles that were clicked, if any.
clicked = circle_at_pos2(event.x, event.y)
if len(clicked) == 0: # If none were clicked
# Create menu with 1 option, create a new circle.
empty_spot_menu = Tkinter.Menu(tearoff=0)
empty_spot_menu.add_command(label="New Circle",
command=lambda: new_circle(event.x, event.y)
)
empty_spot_menu.post(globalX, globalY)
else:
# Creates a new menu with many options, related to the circle clicked.
right_click_menu = Tkinter.Menu()
right_click_menu.add_command(label="Delete Circle",
command=lambda: delete_shapes(clicked))
right_click_menu.add_command(label="Change Color",
command=lambda: change_color(clicked))
right_click_menu.add_command(label="Stop Shape",
command=lambda: stop(clicked))
right_click_menu.add_command(label="Add Trail",
command=lambda: start_trail(clicked))
right_click_menu.post(globalX, globalY)
'''
********************************************************************************
Function: shortcut_menu
Definition: this creates a menu that is used to change the keyboard
shortcuts
Author: ty Silva
Date: 4-5-2019
History:
********************************************************************************
'''
def shortcut_menu():
buttons = [] # Array storing the
# The diffrent functions of the buttons
shortcut_states = Enum("create", "delete", "push", "pause", "none")
currentState = shortcut_states.none # The function currently being changed
currentIndex = 10 # Used to get the name instead of an integer.
'''
********************************************************************************
Function: resetShortcuts
Definition: resets the shortcuts file back to the default file.
Author: ty Silva
Date: 4-5-2019
History:
********************************************************************************
'''
def reset_shortcuts():
fi = open("shortcuts.json", "w")
fi.write(defaultJson)
fi.close()
local_shortcuts = json.loads(defaultJson)
print (local_shortcuts)
buttons[0].config(text=local_shortcuts["create"])
buttons[1].config(text=local_shortcuts["delete"])
buttons[2].config(text=local_shortcuts["push"])
buttons[3].config(text=local_shortcuts["pause"])
'''
********************************************************************************
Function: activateButton
Definition: sets the state variables to match the most recent button
pressed. This function is the callback of the buttons pressed to
change the keyboard shortcuts.
Author: ty Silva
Date: 4-5-2019
History:
********************************************************************************
'''
def activate_button(local_state, index):
global currentState
global currentIndex
currentState = local_state
currentIndex = index
new_root.bind("<Key>", change_val)
'''
********************************************************************************
Function: changeVal
Definition: This is the callback from any key being pressed, and tests to
see if the new key can be used as a keyboard shortcut, and if it
then it makes the new keyboard shortcut.
Author: ty Silva
Date: 4-5-2019
History:
********************************************************************************
'''