-
Notifications
You must be signed in to change notification settings - Fork 0
/
honey_bee.py
1627 lines (1483 loc) · 65.1 KB
/
honey_bee.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
# example of drag
# https://stackoverflow.com/questions/37280004/tkinter-how-to-drag-and-drop-widgets
import tkinter as tk
from PIL import Image, ImageTk, ImageFilter, ImageDraw
from PIL import ImageEnhance as IE
from math import sqrt, pi, sin, cos
import cmath
from functools import partial
from collections import namedtuple
import fly_path as fly
#import winsound as wsnd
import threading
import os, pickle
from run_fifo import RunFifo, fifo_run_queue
import hex_math
from http_client import send_to_server, check_server_for_function, reset_server_fifo
from http_client import test_server
from pprint import pprint
LABEL_FONT = ('Cosmic Sans MS', 14, 'normal')
NORMAL_TILE_OPTIONS = {'fill': '#ee8', 'outline': '#cc6', 'width': 2} # more like hive color?
SELECTED_TILE_OPTIONS = {'fill': '#e5e575', 'outline': '#c5c555', 'width': 3} # original
fifo = RunFifo() # queue routines that might use tkinter to animate
# @fifo_run_queue - decorator to put function call into a fifo queue; blocks queue
# fifo.complete() - unblocks fifo queue so that the next function may run
#fifo.verbose = False # for debugging
def play_sound(name, option):
pass
#play = lambda: wsnd.PlaySound(name, option)
#t = threading.Thread(target=play)
#t.start()
#play_error = lambda: play_sound("error.wav", wsnd.SND_FILENAME)
#play_alert = lambda: play_sound("SystemExclamation", wsnd.SND_ALIAS)
def play_error(): pass
def play_alert(): pass
# if hexagonal tiles, gives pattern of tiles as 'rectangular' or 'hexagonal'
b_shape = 'rectangular'
#b_shape = 'hexagonal'
imgs = [] # required so that images persist
item_offset = {} # map canvas item number to (x, y) offset relative to tile center
item_image = {} # map canvas item number to image dict:
# 'stack': (original, after resize, after rotate)
# 'angle'
game = None
# Three underscores '___' in the help_msg separate tkinter Labels so as to allow hyperlinks
def get_key_text(key):
if key == 'nine_key':
help_keys = (
"Nine alphabetic keys select and move a bee according to this map:\n"+
"('qwe': 1), ('asd': 2), ('zxc': 3), ('uio': 4), ('jkl': 5), ('m,.': 6).\n"+
"For example, 'qwe' controls bee 1. Or use the numeric keys.")
elif key == 'three_key':
help_keys = (
"Three alphabetic keys move a bee previously selected by numeric keys.\n"+
"Use keys ('awd') for team A, or ('jil') for team B, or use the arrow keys." )
else:
help_keys = (
"Six alphabetic keys control direction (NW, N, NE, SW, S, SE).\n"+
"Use keys ('qweasd') for team A, or ('uiojkl') for team B, or use the arrows.\n" +
"Obs., to move NW requires that arrows Left and Up are pressed at the same time.")
return help_keys
def get_help_msg():
help_keys = (get_key_text('nine_key') if game.option('nine_key')[0] == 'on' else
get_key_text('three_key') if game.option('three_key')[0] == 'on' else
get_key_text('six_key'))
help_msg = (
'''Each bee is selected by number keys 1-3 (team A) or 4-6 (team B).
There are two teams, A and B. The object of the game is to kill your
opponent's bees. You move the selected bee one tile at a time by hitting a
key. '''+help_keys+'''
\tctrl-O\toptions
\tctrl-R\trevives killed bees
\tctrl-S\trestarts the game
\tctrl-T\ttests the server
\tctrl-Q\tquit
___
The red dwarf honey bee (Apis florea)
https://en.wikipedia.org/wiki/Apis_florea
___
The yellow European honey bee (Apis mellifera)
https://entnemdept.ufl.edu/creatures/MISC/BEES/euro_honey_bee.htm
'''
)
return help_msg
import webbrowser
def callback(url):
webbrowser.open_new(url)
def frame_window(title, **kw):
# https://stackoverflow.com/questions/28089942/
# difference-between-fill-and-expand-options-for-tkinter-pack-method
w_width, w_height = 620, 400
w_width = kw['width'] if 'width' in kw else w_width
w_height = kw['height'] if 'height' in kw else w_height
window = tk.Toplevel()
window.title(title)
window.geometry(f"{w_width}x{w_height}")
frame1 = tk.Frame(window, background='#cc5')
frame1.pack(fill='both', expand=True)
frame2 = tk.Frame(frame1, background='#888')
frame2.pack(padx=8, pady=8, fill='both', expand=True)
frame3 = tk.Frame(frame2, background='#eeb')
frame3.pack(padx=3, pady=3, fill='both', expand=True)
frame4 = tk.Frame(frame3, background='#eeb')
frame4.pack(padx=10, pady=10, fill='both', expand=True)
return window, frame4
def error(msg):
global imgs
window, frame = frame_window("error", width=550, height=160)
img = tk.PhotoImage(file="error.png")
imgs.append(img)
panel = tk.Label(frame, image = img)
panel.grid(row=0, column=0)
lab = tk.Label(frame, background='#eeb', text=msg,
anchor=tk.NW, justify=tk.LEFT, font=("Comic Sans MS", 12))
lab.grid(row=0, column=1, padx=30, pady=30)
def help():
window, frame3 = frame_window("Honey Bee rules")
msgs = get_help_msg().split('___')
row = 0
for msg in msgs:
if 'http' in msg:
a = [x for x in msg.split('\n') if x]
msg, link = '\n'.join(a[:-1]), a[-1]
height = 12
lab = tk.Label(frame3, background='#eeb', text=msg, fg='blue',
anchor=tk.NW, justify=tk.LEFT, font=("Comic Sans MS", 12))
lab.grid(row=row, column=0, sticky=tk.W)#, padx=4, pady=4, fill='both', expand=True)
lab.bind("<Button-1>", lambda e: callback(link))
else:
lab = tk.Label(frame3, background='#eeb', text=msg,
anchor=tk.NW, justify=tk.LEFT, font=("Comic Sans MS", 12))
lab.grid(row=row, column=0)#, padx=4, pady=4, fill='both', expand=True)
row += 1
def validate(options):
for key in options:
opt = options[key]
if (type(opt) in (tuple, list) and len(opt)
and options[key][-1] == 'text'):
try:
v, text, on, off, ctype = options['tile_dimension']
if key == 'tile_dimension':
tup = v.split(',')
x, y = tup if len(tup) == 2 else (tup[0], tup[0])
x, y = int(x), int(y)
if (x < 5 or x > 20) or (y < 5 or y > 20):
raise Exception('(x, y) values must be in range(5, 20).')
except Exception as e:
tk.messagebox.showerror('Validation', e)
return False
return True
def options_window(options, control_keys, radio_group):
# expect that options is a dictionary {key:(value, text)}
window, frame = frame_window("Honey Bee options")
def save_change():
for i, key in enumerate(keys):
value = var[i].get()
other = tuple(options[key][1:])
options.update({key: (value,) + other})
if validate(game.game_options):
window.destroy()
save_options_and_restart_game(options, client_version)
keys = []
var = []
ctl = []
on = []
off = []
row = 0
for i, key in enumerate(options):
if key not in control_keys:
continue
value, text, onvalue, offvalue, type_control = options[key]
keys.append(key)
var.append(tk.StringVar(value=value))
on.append(offvalue)
off.append(offvalue)
if type_control == 'text':
frame2 = tk.Frame(frame)
frame2.grid(row=row, column=0, sticky=tk.W)
lbl = tk.Label(frame2, text=text, font=("Comic Sans MS", 12),
background='#eeb')
lbl.grid(row=0, column=0, sticky=tk.W)
ctl.append(tk.Entry(frame2, textvariable=var[-1],
width=20, font=('calibre', 12, 'normal')))
ctl[-1].grid(row=0, column=1, sticky=tk.W)
else:
ctl.append(tk.Checkbutton(frame, text=text, variable=var[-1],
onvalue=onvalue, offvalue=offvalue, background='#eeb',
anchor=tk.W, justify=tk.LEFT, font=("Comic Sans MS", 12)))
ctl[-1].grid(row=row, column=0, sticky=tk.W)
row += 1
#radio = lambda i, group: [var[j].set(off[j]) for j in group if i != j]
def radio(i, group):
[var[j].set(off[j]) for j in group if i != j]
text = (get_key_text('nine_key') if keys[i] == 'nine_key' and var[i].get() == 'on' else
get_key_text('three_key') if keys[i] == 'three_key' and var[i].get() == 'on' else
get_key_text('six_key'))
lbl.config(text = '\n' + text)
group_ids = [i for i,k in enumerate(options) if k in radio_group]
for i in group_ids:
ctl[i].config(command=partial(radio, i, group_ids))
btn = tk.Button(frame, text="Save", background='#eeb', command=save_change)
btn.grid(row=row, column=0, sticky=tk.W)
lbl = tk.Label(frame, background='#eeb', text='...',
anchor=tk.W, justify=tk.LEFT, font=("Comic Sans MS", 12))
lbl.grid(row=row+1, column=0, sticky=tk.W)
# options_file_versionshould be incremented if options structure is
options_file_version = 2
options_filename = 'honey_bee.pckl'
client_version = 1
def save_options(options):
options.update({'version': options_file_version})
with open(options_filename, 'wb') as fout:
pickle.dump(options, fout)
return options
def load_options(options):
options.update({'version': options_file_version})
if os.path.exists(options_filename):
try:
with open(options_filename, 'rb') as fin:
opts = pickle.load(fin)
if 'version' not in opts:
return opts # no version control yet
if options['version'] == opts['version']:
return opts
except Exception as e:
print('load_options: ', e)
return options
def check_client_and_options_versions(other_options, other_client_version):
_check_client_and_options_versions(other_options, other_client_version)
def _check_client_and_options_versions(other_options, other_client_version):
global options_file_version, client_version
other_option_version = other_options['version']
if other_client_version > client_version:
error('Client version in another computer is newer '
+ f'({other_client_version})\n'
+ 'Your software should be updated.')
elif other_client_version < client_version:
error('Client version in another computer is older '
+ f'({other_client_version})\n'
+ 'Their software should be updated to yours '
+ f'({client_version}).')
if other_option_version > options_file_version:
error(
'Options version in another computer is newer '
+ f'({other_option_version})\n'
+ 'Your software should be updated.')
elif other_option_version < options_file_version:
error('Options version in another computer is older '
+ f'({other_options})\n'
+ 'Their software should be updated to yours '
+ f'({options_file_version}).')
else:
return True
return False
#For now, players must verbally synchronize options.
def save_options_and_restart_game(other_options, other_client_version):
# check options version with other clients
global game
if _check_client_and_options_versions(other_options, other_client_version):
game.game_options = save_options(other_options)
game.restart_game(rebuild_board=True)
def scale(r, factor):
# scale a geometric object around its center
x0, y0, x1, y1 = r
cx, cy = (x0 + x1) // 2, (y0 + y1) // 2
x0 = cx + round((x0 - cx) * factor)
x1 = cx + round((x1 - cx) * factor)
y0 = cy + round((y0 - cy) * factor)
y1 = cy + round((y1 - cy) * factor)
return x0, y0, x1, y1
def center_item(canvas, item, bounds):
x0, y0, x1, y1 = canvas.bbox(item)
cx0, cy0, cx1, cy1 = bounds
offset_x = (cx0 + cx1) // 2 - (x0 + x1) // 2
offset_y = (cy0 + cy1) // 2 - (y0 + y1) // 2
canvas.move(item, offset_x, offset_y)
def add_image(canvas, options):
global imgs
filename = options.pop('filename')
vx0, vy0, vx1, vy1 = options.pop('viewport')
key_id = options.pop('key_id')
view_max = max(vx1 - vx0, vy1 - vy0)
img0 = Image.open(filename)
img_max = max(img0.size)
img_size = tuple(x * view_max // img_max for x in img0.size)
x, y = vx0, vy0
img1 = img0.resize(img_size, Image.LANCZOS)
img2 = ImageTk.PhotoImage(img1)
options.update({'anchor':tk.NW, 'image':img2})
item = canvas.create_image(x, y, options)
dimg = {}
dimg.update({'filename': filename, 'scale': 1, 'view_max': view_max})
dimg.update({'contrast': 1.0, 'brightness': 1.0, 'saturation': 1.0})
dimg.update({'edge': False, 'angle': 0, 'blur': False})
dimg.update({'angle': 0, 'key_id': key_id, 'select': 0, 'stack': (img0, img1, img2)})
item_image.update({item: dimg})
modify_image(canvas, item, force=True)
return item
def test_modify_image(canvas, item):
# define kw here
kw = {}
test = ['scale', 'contrast', 'brightness', 'saturation', 'blur']
i = item - 50
kw.update({'filename': 'bee_yellow.png'})
if i == 0:
kw.update({'edge': True})
if i in range(len(test)):
kw.update({test[i]: 0.2})
modify_image(canvas, item, **kw)
def modify_image(canvas, item, **kw):
if item not in item_image:
return
dimg = item_image[item]
img0, img1, img2 = dimg['stack']
group0 = ['filename']
group1 = ['scale', 'contrast', 'brightness', 'saturation', 'edge', 'blur', 'key_id', 'select', ]
group2 = ['angle']
dirty0 = dirty1 = dirty2 = False
for key in kw:
dirty0 = dirty0 or key in group0 and dimg[key] != kw[key]
dirty1 = dirty1 or key in group1 and dimg[key] != kw[key]
dirty2 = dirty2 or key in group2 and dimg[key] != kw[key]
dimg.update({key: kw[key]})
sw = 'force' in kw and kw['force']
def process_scale(img, scale):
nonlocal dimg, img0
view_max = dimg['view_max']
img_max = max(img0.size)
img_size = tuple(round(x * scale * view_max // img_max) for x in img0.size)
img1 = img0.resize(img_size, Image.LANCZOS)
return img1
def process_key_id(img, key_id):
draw = ImageDraw.Draw(img)
# compute dimensions
w, h = img.size
t = 24, 13, 6, 5, 7 # good for w == 100, by trial and error
x, y, d, dx0, dy0 = (x * w // 100 for x in t)
team = (key_id - 1) // 3
for i in range((key_id - 1) % 3 + 1):
color = '#cc4' if team==0 else '#f00' if team==1 else '#555'
dx, dy = (0, 0) if i==0 else (-dx0, dy0) if i==1 else (-dx0*2, dy0*2)
xy = (x+dx, y+dy, x+dx+d, y+dy+d)
draw.ellipse(xy, fill=color, outline='#777') #, outline=None, width=1)
return img
def process_select_item(img, key_id):
draw = ImageDraw.Draw(img)
w, h = img.size
x, y = (w*11//16, 10)
xy = (x, y, x+10, y+10) # good dimensions for w = 100
xy = (x, y, x+6, y+6) # good dimensions for w = 60
draw.ellipse(xy, fill='#5f5', outline='#2a2')
return img
def process(img, key, default, func):
nonlocal sw, kw, dimg
if (sw or key in kw) and dimg[key] != default:
img = func(img, dimg[key])
sw = True
return img
sw = sw or dirty0
img0 = process(img0, 'filename', '', lambda img, p: Image.open(p))
sw = sw or dirty1
img1 = process(img1, 'scale', None, process_scale) # None means to do this if sw is dirty
img1 = process(img1, 'contrast', 1.0, lambda img, p: IE.Contrast(img).enhance(p))
img1 = process(img1, 'brightness', 1.0, lambda img, p: IE.Brightness(img).enhance(p))
img1 = process(img1, 'saturation', 1.0, lambda img, p: IE.Color(img).enhance(p))
img1 = process(img1, 'edge', False, lambda img, p: img.filter(ImageFilter.EDGE_ENHANCE))
img1 = process(img1, 'blur', False, lambda img, p: img.filter(ImageFilter.BLUR))
img1 = process(img1, 'key_id', 0, process_key_id)
img1 = process(img1, 'select', 0, process_select_item)
sw = sw or dirty2
key = 'angle'
if sw or 'angle' in kw:
dimg.update({'stack': (img0, img1, img2)})
item_image.update({item: dimg})
rotate_item(canvas, item, dimg['angle'])
cx, cy = get_item_center(canvas, item)
board_item = canvas.find_overlapping(cx, cy, cx+1, cy+1)[0]
canvas.center_item(item, canvas.bbox(board_item))
def rotate_item(canvas, item, angle):
# https://stackoverflow.com/questions/15736530/python-tkinter-rotate-image-animation
# https://pillow.readthedocs.io/en/stable/reference/Image.html#the-image-class
# img is of pillow class Image
if item not in item_image:
return
dimg = item_image[item]
img0, img1, img2 = dimg['stack']
tmp = img1.rotate(angle)
img2 = ImageTk.PhotoImage(tmp)
dimg.update({'stack': (img0, img1, img2), 'angle': angle})
item_image.update({item: dimg})
item = canvas.itemconfig(item, image=img2)
canvas.angle = angle % 360
def rotate_item_smoothly(canvas, item, angle):
canvas._drag_item = item
cx1, cy1 = get_tile_center(canvas, item)
offx, offy = item_offset[item]
fifo.set_completion_routine(rotate_item_completion, item, cx1, cy1, angle=angle)
animate_snap(canvas, cx1+offx, cy1+offy, angle)
def rotate_item_completion(item, cx1, cy1, angle=0):
bee = game.get_bee_from_item(item)
bee.last_direction = (angle + 90) % 360
assert (bee.last_direction - 30) % 60 == 0, 'last_direction 2'
board = bee.board
game.label0.config(text = game.direction_msg[bee.last_direction])
deselect_tiles(board)
game.toggle_team()
if board.active_item:
select_tiles(board, board.active_item)
def mirror_image(canvas, item):
#image = ImageOps.mirror(image)
pass
def delete_item_piece(canvas, item):
if item in canvas.item_piece:
canvas.item_piece.pop(item)
def add_item_piece(canvas, item, piece):
item = item if type(item) in (tuple, list) else [item]
for it in item:
canvas.item_piece.update({it: piece})
def delete_family(canvas, item):
if item in canvas.fam_parents: # item is a child
parent = canvas.fam_parents[item]
canvas.fam_parents.pop(item)
if item in canvas.fam_children[parent]:
canvas.fam_children[parent].remove(item)
if not canvas.fam_children[parent]:
canvas.fam_children.pop(parent)
if item in canvas.fam_children:
children = canvas.fam_children[item]
for child in children:
delete_family(canvas, child)
def add_family(canvas, parent, children):
children = children if type(children) in (tuple, list) else [children]
for ch in children:
canvas.fam_parents.update({ch: parent})
s = canvas.fam_children[parent] if parent in canvas.fam_children else set()
s.add(ch)
canvas.fam_children.update({parent: s})
def is_draggable(canvas, item):
item = item[0] if type(item) == tuple else item
return item in canvas.draggable_items
def get_item_center(canvas, item):
px0, py0, px1, py1 = canvas.bbox(item)
cx0, cy0 = (px0 + px1) // 2, (py0 + py1) // 2
return cx0, cy0
def get_tile_center(canvas, item):
# return tile center
if item in canvas.tile_centers:
tile = item
else:
cx, cy = get_item_center(canvas, item)
tile = find_closest_tile(canvas, cx, cy)
return canvas.tile_centers[tile]
def make_board_clickable(canvas, item):
canvas.tag_bind(item, "<Button-1>", on_board_click)
def make_draggable(canvas, item, child=None):
item = item[0] if type(item) == tuple else item
parent, item = (item, child) if child else (None, item)
canvas.draggable_items.append(item)
canvas.tag_bind(item, "<Button-1>", on_drag_start)
canvas.tag_bind(item, "<B1-Motion>", on_drag_motion)
canvas.tag_bind(item, "<ButtonRelease-1>", on_drag_stop)
r = canvas.coords(item)
cx0, cy0 = get_item_center(canvas, item)
cx1, cy1 = get_tile_center(canvas, item)
item_offset.update({item: (cx0 - cx1, cy0 - cy1)})
def find_tile(canvas, item):
cx, cy = get_item_center(canvas, item)
tile = canvas.find_overlapping(cx, cy, cx+1, cy+1)[0]
return tile
def find_closest_tile(canvas, x, y):
#tile = canvas.find_overlapping(x, y, x+1, y+1)[0]
data = canvas.tile_centers # assume canvas can reach board attributes
tile = None
last_r = 10000
for t in canvas.tile_centers:
cx, cy = data[t]
r = sqrt((x-cx)**2 + (y-cy)**2)
if r < last_r:
tile = t
last_r = r
return tile
def get_item_angle(canvas, item):
parent = canvas.fam_parents[item] if item in canvas.fam_parents else item
piece = canvas.item_piece[parent]
return (piece.last_direction - 90) % 360
def deselect_tiles(canvas):
tiles = canvas.selected_tiles
options = NORMAL_TILE_OPTIONS
for tile in tiles:
canvas.itemconfigure(tile, **options)
canvas.selected_tiles = []
def select_tiles(canvas, item):
# move this to Game
if 'selected_tiles' not in game.game_options:
return
piece = game.get_bee_from_item(item)
if canvas.active_item not in piece.items:
return
tiles = [find_tile(canvas, item)]
cx, cy = get_tile_center(canvas, item)
angle0 = get_item_angle(canvas, item)
for i in range(3):
direction = angle0 + (i - 1) * 60 + 90
alpha = direction * pi / 180
dx, dy = t_width * cos(alpha), -t_height * sin(alpha)
x, y = cx + dx, cy + dy
#t = canvas.find_overlapping(x, y, x+1, y+1)
t = find_closest_tile(canvas, x, y)
if t:
tiles.append(t)
canvas.selected_tiles = tiles
options = SELECTED_TILE_OPTIONS
for tile in tiles:
canvas.itemconfigure(tile, **options)
def deselect_item(canvas, call_modify_image=True):
if canvas.active_item:
item = canvas.active_item
parent = canvas.fam_parents[item] if item in canvas.fam_parents else item
piece = canvas.item_piece[parent]
canvas.delete(item)
canvas.delete_family(item)
modify_image(canvas, parent, select=0, edge=False, contrast=0.3, brightness=2.5, scale=0.93)
canvas.active_item = None
deselect_tiles(canvas)
def select_item(canvas, item):
piece = canvas.item_piece[item]
if canvas.active_item in piece.items:
return
deselect_item(canvas, False)
x0, y0, x1, y1 = scale(piece.bbox(), 0.65)
r = (x1 - 1, y0, x1, y0 + 1)
modify_image(canvas, item, select=piece.key_id, edge=True, scale=1.07)
canvas.active_item = canvas.create_oval(*r, fill='#ee8')
canvas._drag_item = piece.item
canvas.angle = (piece.last_direction - 90) % 360
piece.items.append(canvas.active_item)
canvas.add_family(piece.item, canvas.active_item)
lift_item(canvas, item)
select_tiles(canvas, item)
#def is_selected(canvas, item):
## active_item points to graphic showing activation
## not used - keep for future use
#parent = canvas.fam_parents[item] if item in canvas.fam_parents else item
#if parent not in canvas.item_piece: return False
#return canvas.active_item in piece.items
def lift_item(canvas, item):
item = item[0] if type(item) == tuple else item
if item in canvas.fam_parents or item in canvas.fam_children:
parent = canvas.fam_parents[item] if item in canvas.fam_parents else item
siblings = canvas.fam_children[parent]
canvas.lift(parent)
for child in siblings:
canvas.lift(child)
else:
canvas.lift(item)
def move_item(canvas, item, dx, dy):
item = item[0] if type(item) == tuple else item
if item in canvas.fam_parents or item in canvas.fam_children:
parent = canvas.fam_parents[item] if item in canvas.fam_parents else item
siblings = canvas.fam_children[parent]
canvas.move(parent, dx, dy)
for child in siblings:
canvas.move(child, dx, dy)
else:
canvas.move(item, dx, dy)
def on_drag_start(event):
x, y = event.x, event.y
_on_drag_start(x, y)
@send_to_server
@fifo_run_queue
def _on_drag_start(event_x, event_y):
global game
canvas = game.board
item = canvas.find_closest(event_x, event_y)
item = item[0] if type(item) == tuple else item
# handle case where we click on enemy bee on our turn
canvas._ignore_drag = False
if item in canvas.item_piece:
piece = canvas.item_piece[item]
toggle_team = game.game_options['toggle_team'][0] == 'on'
if piece and toggle_team and game.team and piece.team != game.team:
_on_board_click2(event_x, event_y)
canvas._ignore_drag = True
return
canvas._drag_item = None
canvas._drag_motion = False
if not is_draggable(canvas, item):
return
deselect_item(canvas)
canvas._drag_item = item
canvas._drag_first_x = event_x
canvas._drag_first_y = event_y
canvas._drag_last_x = event_x
canvas._drag_last_y = event_y
canvas._drag_item_offset = item_offset[item]
canvas.angle = 0
lift_item(canvas, item)
import cmath
def to_polar(dx, dy):
r, a = cmath.polar(complex(dx, dy))
return r, a % (2 * pi)
def on_drag_motion(event):
x, y = event.x, event.y
_on_drag_motion(x, y)
def _on_drag_motion(event_x, event_y):
global game
canvas = game.board
if canvas._ignore_drag:
return
item = canvas._drag_item
if item is None:
return
if abs(event_x - canvas._drag_first_x) + abs(event_y - canvas._drag_first_y) < 5:
return
canvas._drag_motion = True
dx = event_x - canvas._drag_last_x
dy = event_y - canvas._drag_last_y
canvas._drag_last_x = event_x
canvas._drag_last_y = event_y
move_item(canvas, item, dx, dy)
if 'angle' in canvas.options and 'drag_motion' in canvas.options['angle']:
r, angle = to_polar(event_x - canvas._drag_first_x, -(event_y - canvas._drag_first_y))
canvas.angle = int(angle * 180 / pi - 90) % 360
rotate_item(canvas, item, canvas.angle)
def animate_snap(canvas, cx1, cy1, angle1, i=20, fl=None):
# angle is in degrees
item = canvas._drag_item
cx0, cy0 = get_item_center(canvas, item)
angle0 = canvas.angle
if angle1 - angle0 > 185:
angle1 -= 360
elif angle1 - angle0 < -185:
angle1 += 360
if fl is None:
fl = fly.Fly((cx0, cy0, angle0), (cx1, cy1, angle1), next_point=fly.next_point_straight)
fl = iter(fl)
complete = False
try:
x, y, angle = next(fl)
dx, dy = x - cx0, y - cy0
except StopIteration:
angle = angle1
angle = round(angle / 60) * 60
dx, dy = cx1 - cx0, cy1 - cy0
complete = True
else:
fifo.keep_blocking(40)
canvas.after(20, animate_snap, canvas, cx1, cy1, angle1, i-1, fl)
move_item(canvas, item, dx, dy)
if 'angle' in canvas.options and 'animate_snap' in canvas.options['angle']:
rotate_item(canvas, item, angle)
if complete:
fifo.complete(angle=angle)
def animate_snap_old(canvas, cx1, cy1, angle1, i=20):
item = canvas._drag_item
cx0, cy0 = get_item_center(canvas, item)
angle0 = canvas.angle
dangle = (angle1 - angle0) * (20 - i) // 20
angle = angle0 + dangle
dx, dy = cx1 - cx0, cy1 - cy0
if i > 1 and abs(dx) + abs(dx) + abs(dangle) > 0:
sign = lambda x: -1 if x < 0 else 1
dx = round(sign(dx) * sqrt(abs(dx)) * 0.7)
dy = round(sign(dy) * sqrt(abs(dy)) * 0.7)
canvas.after(10, animate_snap_old, canvas, cx1, cy1, angle1, i-1)
move_item(canvas, item, dx, dy)
if 'angle' in canvas.options and 'drag_stop' in canvas.options['angle']:
rotate_item(canvas, item, angle)
def on_drag_stop(event):
x, y = event.x, event.y
_on_drag_stop(x, y)
@send_to_server
@fifo_run_queue
def _on_drag_stop(event_x, event_y):
global game
canvas = game.board
if canvas._ignore_drag:
return
item = canvas._drag_item
if item is None:
return
# this section tests multi-user case where drag is omitted
if not canvas._drag_motion:
dx = event_x - canvas._drag_last_x
dy = event_y - canvas._drag_last_y
canvas._drag_motion = (dx**2 + dy**2) > 25
if canvas._drag_motion:
_on_drag_motion(event_x, event_y)
if not canvas._drag_motion: # piece was not dragged, just clicked
piece = canvas.item_piece[item]
select_item(canvas, item)
if piece:
game.team = piece.team
game.team_bee_id.update({game.team:piece.key_id})
game.highlight_team_label(piece)
return
cx1, cy1 = get_tile_center(canvas, item)
offx, offy = canvas._drag_item_offset
angle = canvas.angle
animate_snap(canvas, cx1+offx, cy1+offy, angle)
def on_board_click(event):
# this accepts events from tkinter
x, y = event.x, event.y
_on_board_click(x, y, event.state)
@send_to_server
@fifo_run_queue
def _on_board_click(event_x, event_y, event_state=0):
# this is called by an event or on checking the server
_on_board_click2(event_x, event_y, event_state)
def _on_board_click2(event_x, event_y, event_state=0):
# this is called called to move a piece, simulating an on-board click
global game
canvas = game.board
item = canvas.active_item
if not item:
return
#canvas._drag_item = item
item = canvas.fam_parents[item] if item in canvas.fam_parents else item
board_item = canvas.find_closest_tile(event_x, event_y)
board_item = board_item[0] if type(board_item) == tuple else board_item
if ('selected_tiles' in game.game_options
and game.game_options['selected_tiles'][0] == 'on'):
if board_item not in canvas.selected_tiles:
game.label0.config(text='To move, you must click on a highlighted tile')
return
cx0, cy0 = get_tile_center(canvas, item)
if event_state & 1 == 1: # shift key down
cx1, cy1 = cx0, cy0
else:
cx1, cy1 = get_tile_center(canvas, board_item)
offx, offy = item_offset[item]
if 'angle' in canvas.options and 'animate_snap' in canvas.options['angle']:
if (cx1 == cx0) and (cy1 == cy0): # can happen if item is on edge of board
r, angle = to_polar(event_x - cx0, -(event_y - cy0))
else:
r, angle = to_polar(cx1 - cx0, -(cy1 - cy0))
angle = int(angle * 180 / pi - 90) % 360
#rotate_item(canvas, item, angle)
fifo.set_completion_routine(on_board_click_completion, item, cx1, cy1, angle=angle)
animate_snap(canvas, cx1+offx, cy1+offy, angle)
def on_board_click_completion(item, cx1, cy1, angle=0):
kill_msg = game.kill_bees(item, cx1, cy1)
bee = game.get_bee_from_item(item)
# on fifo time-out, animation may not be complete and angle may
# have a round-off error
angle = round(angle / 60) * 60
bee.last_direction = (angle + 90) % 360
assert (bee.last_direction - 30) % 60 == 0, 'last_direction 3'
board = bee.board
text = "bee {}, {}".format(bee.key_id, game.direction_msg[bee.last_direction]) + kill_msg
game.label0.config(text=text)
deselect_tiles(board)
game.toggle_team()
if board.active_item:
select_tiles(board, board.active_item)
def pattern_random(i, j):
from random import randint
ranx = lambda: f"{randint(0, 255):x}".zfill(2)
options = {'fill': f"#{ranx()}{ranx()}{ranx()}"}
return options
def pattern_checkered(i, j):
odd = (i + j) % 2
options = {'fill': "#866" if not odd else "#ddd"}
return options
def pattern_granite(i, j):
global imgs
odd = (i + j) % 2
filename = "light_granite_100.png" if not odd else "dark_granite_100.png"
img = tk.PhotoImage(file=filename)
imgs.append(img)
options = {'image': img, 'anchor': tk.NW}
return options
def pattern_hexagon(i, j, scheme='default'):
# table of offsets in x and y
long_axis = t_width * 4 // 3
x0, x1, x2, x3 = 0, long_axis // 4, long_axis * 3 // 4, long_axis
y0, y1, y2 = 0, t_height // 2, t_height
# get color of tile
if scheme == 'random':
options = pattern_random(i, j)
elif scheme == 'rgb':
color_index = (i % 2 + 2 - j % 3) % 3 # magic needed to alternate colors
colors = {0: '#c33', 1: '#3c3', 2: '#33c'}
options = {'fill': colors[color_index]}
else:
options = NORMAL_TILE_OPTIONS
# get shape of hexagon, then offset x, y
odd = (i + j) % 2
pgon = (0, y1, x1, 0, x2, 0, x3, y1, x2, y2, x1, y2)
pgon = (a if not odd else a for a in pgon)
options.update({'polygon': pgon})
return options
class Canvas(tk.Canvas):
options = {}
def __init__(self, *p, **kw):
super().__init__(*p, **kw)
self.draggable_items = []
self.fam_parents = {} # map child to parent id
self.fam_children = {} # map parent to set of children ids
self.item_piece = {}
self.place(x=0, y=0)
self.selected_tiles = [] # highlighted when a Piece is selected
self.active_item = None # usually refers to the active symbol
self._ignore_drag = None # work around a __getattr__ bug on line 675 (230413)
def __getattr__(self, attr):
return partial(globals()[attr], self)
# attach functions as methods, as alternative to Dispatcher example above
#setattr(Canvas, 'rotate_item', rotate_item)
class Board(Canvas):
def __init__(self, *p, **kw):
self.frame = p[0]
self.tile_centers = {}
global t_width, t_height, b_width, b_height, w_width, w_height, x_tiles, y_tiles
self.pattern = kw.pop('pattern') if 'pattern' in kw else pattern_checkered
jrange, irange = y_tiles, x_tiles # ranges for generation of tiles
if self.pattern == pattern_hexagon:
kw.update({'width': b_width, 'height': b_height})
if b_shape == 'hexagonal':
rmax = y_tiles // 2 + 1
hex_tile_spec = hex_math.tile_generation(rmax, t_height)
hex_iter = iter(hex_tile_spec)
jrange, irange = rmax, 6 # range of first two hex dimensions
super().__init__(*p, **kw)
self.rmax = jrange - 1 # used if b_shape == 'hexagonal'
self.rows = []
self.start_item = {} # map tuple(i, j, b) to board_item
for j in range(jrange):
row = []
irange = (6 if j > 0 else 1) if b_shape == 'hexagonal' else irange
for i in range(irange):
x, y = t_width * i, t_height * j
if self.pattern == pattern_granite:
item = self.create_image(x, y, **self.pattern(i, j))
cx, cy = x + t_width // 2, y + t_height // 2
self.tile_centers.update({item: (cx, cy)})
make_board_clickable(self, item)
row.append(item)
elif self.pattern == pattern_hexagon:
def draw_poly(i, j, x, y, y_offset):
pat = self.pattern(i, j)
poly0 = tuple(pat.pop('polygon'))
poly1 = tuple(v + x if iv % 2 == 0 else
v + y + y_offset for iv, v in enumerate(poly0))
item = self.create_polygon(*poly1, **pat)
polyx = tuple(x for i, x in enumerate(poly1) if i % 2 == 0)
polyy = tuple(y for i, y in enumerate(poly1) if i % 2 == 1)
cx, cy = sum(polyx) // len(polyx), sum(polyy) // len(polyy)
self.tile_centers.update({item: (cx, cy)})
make_board_clickable(self, item)
return item
if b_shape == 'hexagonal':
r0, alpha0 = j, i
item = []
for b in range(j if j > 0 else 1):
if b_shape == 'hexagonal':
try:
tile_spec = next(hex_iter)
except Exception:
break
tile, rab, xy = tile_spec
r, alpha, _b, x, y = rab + xy
x += b_width // 2 - t_width // 2
y += b_height // 2 - t_height // 2
y_offset = 0
bitem = draw_poly(i, j, x, y, y_offset)
item.append(bitem)
assert r == j and alpha == i and b == _b, 'hex math error'
self.start_item.update({rab: bitem})
else: # b_shape is 'rectangular'
x, y = t_width * i, t_height * j
y_offset = t_height // 2 if i % 2 == 1 else 0
item = draw_poly(i, j, x, y, y_offset)
row.append(item)
#print(f'{item}\t{cx}\t{cy}') # keep for debugging
else:
rec = (x, y, x + t_width, y + t_height)
cx, cy = x + t_width // 2, y + t_height // 2
self.tile_centers.update({item: (cx, cy)})
item = self.create_rectangle(*rec, **self.pattern(i, j))
make_board_clickable(self, item)
row.append(item)
self.rows.append(row)
class Piece:
last_piece_key_id = 0
def __init__(self, board, i, j, b, **options):
# i, j is the x, y position on the board
Piece.last_piece_key_id += 1
self.key_id = Piece.last_piece_key_id
self.board = board
canvas = self.board
if b_shape == 'hexagonal':
board_item = self.board.rows[i][j][b]
else:
board_item = self.board.rows[j][i]
canvas.active_item = None # points to the selection indicating item, not the parent
x0, y0, x1, y1 = bbox = canvas.bbox(board_item)
self.team = options.pop('team') if 'team' in options else ''
self.dead = False
if "filename" in options:
bbox2 = scale(bbox, 0.8)
options.update({'viewport':scale(bbox, 0.8)})
options.update({'key_id':self.key_id})
self.item = add_image(canvas, options)
self.items = [self.item]
canvas.center_item(self.items[0], canvas.bbox(board_item))
canvas.make_draggable(self.items[0])
else:
r = scale(bbox, 0.7)
r1 = scale(r, 0.7)
r2 = list(r)
r2[2] = r2[0] + 5
color = options["color"] if "color" in options else "#e50"
self.item = canvas.create_oval(*r, outline="#aaa", fill=color) # parent