-
Notifications
You must be signed in to change notification settings - Fork 0
/
ipy_lib.py
3396 lines (2864 loc) · 133 KB
/
ipy_lib.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
'''
Created on 30 Jan. 2012
Finished on 6 Feb. 2012
Improvements:
- 1 Mar. 2012 to 2 Mar. 2012: fixed a rare threading related crash
- 3 Mar. 2012 to 5 Mar. 2012: fixed a bug in showing names of the barchart
- 17 Mar. 2012 to 18 Mar. 2012: fixed not running on Linux
- 31 Jul. 2012 to 31 Jul. 2012: added UserInput and 'privatised' most classes and imports
- 1 Aug. 2012 to 2 Aug. 2012: fixed another bug with showing names of the barchart and a bug with displaying text in othello
- 4 Aug. 2012 to 4 Aug. 2012: fixed bug with opening a file and fixed functionality of closing the window
- 6 Aug. 2012 to 7 Aug. 2012: fixed multiple windows crashing the UI, reverted change to UserInput with this change
- 21 Aug. 2012 to 21 Aug. 2012: adjusted naming from JAVA to Python convention, changed UserInput to a function that returns all input, added Life interface
- 22 Aug. 2012 to 22 Aug. 2012: added scrollbar to othello, snake and life interfaces, added type checking and exceptions for all input
- 2 Sep. 2012 to 2 Sep. 2012: fixed another bug with names of the barchart, allowed ints to be given to floats, fixed spelling
- 13 Sep. 2012 to 13 Sep. 2012: fixed more spelling, added functionality for multiple answers per question
- 27 Sep. 2012 to 27 Sep. 2012: changed multiple answers from array to arbitrary arguments list, added exception if argument list is empty
- 6 Dec. 2012 to 6. Dec. 2012: fixed resets of auto alarm speed by adding a timer
- 2 Oct. 2013 to 3. Oct. 2013: fixed ranged errors, fixed closing bug in Windows and Linux when only calling ask_user or file_input,
fixed typos, added Escape as window closer, fixed window not getting focus when started, added Mac support (!)
- 9 Oct. 2013 to 9. Oct. 2013: fixed get_event (Mac version) to properly give refresh events
- 12 Nov. 2014 to 12. Nov. 2014: fixed OS X to not use PIL anymore and instead of images draw some simple shapes
- 21 Nov. 2014 to 21. Nov. 2014: fixed OS X BarChartUI to properly show bar names without calling show
- 15 May. 2015 to 15 May. 2015: added user interfaces for programming for economy -- Sebastian
- 22 Jun. 2015 to 22 Jun. 2015: fixed asking twice for file_input on Windows -- Gerben
@author: Gerben Rozie
@author: Sebastian Osterlund
'''
import tkinter as _tk
import tkinter.dialog as _Dialog
import tkinter.filedialog as _tkFileDialog
import tkinter.messagebox as _tkMessageBox
import queue as _Queue
import threading as _threading
import time as _time
import os as _os
import random as _random
import sys as _sys
have_mpl = False
try:
import matplotlib as mpl
if _sys.platform == 'linux' or _sys.platform == 'linux2':
mpl.rcParams['backend'] = 'QT4Agg'
import pylab as plt
if _sys.platform == 'linux' or _sys.platform == 'linux2':
plt.switch_backend('QT4Agg') # Use QT4 for linux. Bug in TK.
have_mpl = True
except ImportError:
print("Could not import matplotlib. HouseMarketUserInterface and StockMarketUserInterface have been disabled.")
import time as _time
import datetime as _datetime
import pickle as _pickle
import urllib, json
YAHOO_URL = 'https://query.yahooapis.com/v1/public/yql'
have_pil = False
try:
from PIL import Image as _Image, ImageTk as _ImageTk
have_pil = True
except ImportError:
print("Could not import the Python Imaging Library (PIL).")
print("Usage of OthelloReplay-, Snake- and LifeUserInterface are disabled.")
class _IPyException(Exception):
def __init__(self, value):
self.parameter = value
def __str__(self):
return repr(self.parameter)
def _verify_int(value_var, string_var, minimum=None, maximum=None):
if not isinstance(value_var, int):
value = "%s not an int for %s, got %s" % (value_var, string_var, str(type(value_var))[1:-1])
raise _IPyException(value)
_verify_input(value_var, string_var, minimum, maximum)
def _verify_float(value_var, string_var, minimum=None, maximum=None):
if not isinstance(value_var, float):
if not isinstance(value_var, int):
value = "%s is not a float or int for %s, got %s" % (value_var, string_var, str(type(value_var))[1:-1])
raise _IPyException(value)
_verify_input(value_var, string_var, minimum, maximum)
def _verify_str(value_var, string_var):
if not isinstance(value_var, str):
value = "%s is not a string for %s, got %s" % (value_var, string_var, str(type(value_var))[1:-1])
raise _IPyException(value)
def _verify_bool(value_var, string_var):
if not isinstance(value_var, bool):
value = "%s is not a boolean for %s, got %s" % (value_var, string_var, str(type(value_var))[1:-1])
raise _IPyException(value)
def _verify_input(value_var, string_var, minimum=None, maximum=None):
if minimum is None:
minimum = float('-inf')
if maximum is None:
maximum = float('inf')
if value_var >= minimum:
if value_var <= maximum:
return
value = "%s is out of bounds, expected range: %s to %s, got: %s" % (string_var, minimum, maximum, value_var)
raise _IPyException(value)
class _OthelloReplayHolder(object):
#used in the queue to hold values of the changes to be made
def __init__(self, x, y, color):
self.x = x
self.y = y
self.color = color
class _BarChartHolder(object):
#used in the queue to hold values of the changes to be made
def __init__(self, bar_index):
self.bar_index = bar_index
class _BarChartNameHolder(object):
#used in the queue to hold values of the changes to be made
def __init__(self, bar_index, bar_name):
self.bar_index = bar_index
self.bar_name = bar_name
class _SnakeHolder(object):
def __init__(self, x, y, color):
self.x = x
self.y = y
self.color = color
class _LifeHolder(object):
def __init__(self, x, y, color):
self.x = x
self.y = y
self.color = color
if _sys.platform == 'darwin':
_ui_factory = None
def file_input():
"""This function lets the user select a file to use for input.
Returns the file contents in a string.
"""
global _ui_factory
f = _AskInput(_ui_factory.mainroot).f
if f == '':
return None
return str(_sys.stdin.read())
def ask_user(question, *options):
"""Ask the user a question.
Parameters:
- question: the string to ask the user
- options: arbitrary list of arguments (at least 1)
Returns the chosen option by the user or None if nothing was chosen (e.g. hit Escape).
"""
if len(options) == 0:
value = "User needs to be able to select at least 1 answer"
raise _IPyException(value)
global _ui_factory
return _AskUser(_ui_factory.mainroot, question, options).answer
class _Factory():
def __init__(self):
self.mainroot = _tk.Tk()
self.mainroot.withdraw()
self.mainroot.update()
class _AskInput(object):
def __init__(self, mainroot):
root = _tk.Toplevel(mainroot)
root.withdraw()
self.f = _tkFileDialog.askopenfilename(parent=root)
if self.f != '':
_sys.stdin = file(self.f)
root.destroy()
class _AskUser(object):
def __init__(self, mainroot, question, options):
root = _tk.Toplevel(mainroot)
root.withdraw()
dg = _Dialog.Dialog(None,
title="",
text=question,
default=0,
bitmap=_tkMessageBox.QUESTION,
strings=options)
self.answer = options[dg.num]
root.destroy()
class OthelloReplayUserInterface(object):
def __init__(self, scale=1.0):
"""This class starts the OthelloReplayUserInterface.
Constants:
- NUMBER_OF_ROWS
- NUMBER_OF_COLUMNS
- EMPTY
- WHITE
- BLACK
Parameters for the class: (none)
Optional parameters:
- scale: 0.25 to 1.0
"""
if not have_pil:
value = "OthelloReplay: PIL wasn't found, can't use this interface right now."
raise _IPyException(value)
_verify_float(scale, 'Scale', 0.25, 1.0)
global _ui_factory
self.othello_replay = _Othello(_ui_factory.mainroot, scale)
self.NUMBER_OF_ROWS = _Othello.NUMBER_OF_ROWS
self.NUMBER_OF_COLUMNS = _Othello.NUMBER_OF_COLUMNS
self.EMPTY = _Othello.EMPTY
self.WHITE = _Othello.WHITE
self.BLACK = _Othello.BLACK
def place(self, x, y, color):
"""Place an Othello piece (defined by 'color') on the given X and Y coordinates.
"""
_verify_int(x, 'X', 0, self.NUMBER_OF_COLUMNS - 1)
_verify_int(y, 'Y', 0, self.NUMBER_OF_ROWS - 1)
# 0 = empty, 1 = white, 2 = black, 3 = white_t, 4 = black_t
_verify_int(color, 'Color', 0, 4)
self.othello_replay.place(x, y, color)
def place_transparent(self, x, y, color):
"""Place a semi-transparent Othello piece (defined by 'color') on the given X and Y coordinates.
"""
_verify_int(x, 'X', 0, self.NUMBER_OF_COLUMNS - 1)
_verify_int(y, 'Y', 0, self.NUMBER_OF_ROWS - 1)
# 0 = empty, 1 = white_t, 2 = black_t (before next step in code)
_verify_int(color, 'Color', 0, 2)
if color == self.EMPTY:
self.place(x, y, self.EMPTY)
else:
self.place(x, y, color+2)
def clear(self):
"""Clears the display.
Note: this does not clear the text area!
"""
self.othello_replay.clear()
def show(self):
"""Show the changes made to the display (i.e. after calling place or clear).
"""
self.othello_replay.show()
def print_(self, text):
"""Print text to the text area on the display.
This function does not add a trailing newline by itself.
"""
_verify_str(text, "Text")
self.othello_replay.print_(text)
def clear_text(self):
"""Clears the text area on the display.
"""
self.othello_replay.clear_text()
def wait(self, ms):
"""Let your program wait for an amount of milliseconds.
This function only guarantees that it will wait at least this amount of time.
If the system, i.e., is too busy, then this time might increase.
- Python time module.
"""
_verify_int(ms, "Waiting time", 0)
self.othello_replay.wait(ms)
def close(self):
"""Closes the display and stops your program.
"""
self.othello_replay.close()
def stay_open(self):
"""Force the window to remain open.
Only has effect on Mac OS to prevent the window from closing after the execution finishes.
Make sure that this is the last statement you call when including it because the code does NOT continue after this.
"""
global _ui_factory
_ui_factory.mainroot.mainloop()
class _Othello(object):
#one cannot prevent users from editing 'constants', as constants simply do not exist in Python
NUMBER_OF_ROWS = 8
NUMBER_OF_COLUMNS = 8
EMPTY = 0
WHITE = 1
BLACK = 2
r = 20
g = 120
b = 0
BACKGROUND = "#%02X%02X%02X" % (r,g,b) #BACKGROUND = "#147800"?
def __init__(self, mainroot, scale=1.0):
#create queue to store changes to placings
self.to_show_queue = _Queue.Queue(maxsize=0)
#start the main window
self.root = _tk.Toplevel(mainroot)
self.root.title("OthelloReplayUserInterface")
self.root.protocol("WM_DELETE_WINDOW", self.callback)
self.root.bind("<Escape>", self.callback)
self.root.resizable(False, False)
#calculate sizes
self.text_height = int(200 * scale)
self.othello_size = int(800 * scale)
#create main frame
self.frame = _tk.Frame(self.root, width=self.othello_size, height=self.othello_size+self.text_height)
self.frame.pack_propagate(0)
self.frame.pack()
#create board to hold references to othello-pieces
self.white_board = [] # for storing references to create_image
self.black_board = []
self.white_ghost_board = []
self.black_ghost_board = []
self.img_refs = [] # for storing references to images - order: white, black
#create and fill the canvas --> paintable area
self.c = _tk.Canvas(self.frame, width=self.othello_size, height=self.othello_size, bg=self.BACKGROUND, bd=0, highlightthickness=0)
self.c.pack()
self.c.focus_set()
self.fill_canvas()
#create the textholder
self.scrollbar = _tk.Scrollbar(self.frame)
self.scrollbar.pack(side=_tk.RIGHT, fill=_tk.Y)
self.textarea = _tk.Text(self.frame, yscrollcommand=self.scrollbar.set)
self.textarea.pack(side=_tk.LEFT, fill=_tk.BOTH)
self.scrollbar.config(command=self.textarea.yview)
self.textarea.config(state=_tk.DISABLED)
global _ui_factory
_ui_factory.mainroot.update()
def callback(self, event=None):
self.root.destroy()
_os._exit(0)
def place(self, x, y, color):
element = _OthelloReplayHolder(x, y, color)
self.to_show_queue.put(element)
def clear(self):
for x in range(self.NUMBER_OF_COLUMNS):
for y in range(self.NUMBER_OF_ROWS):
self.place(x, y, self.EMPTY)
def show(self):
try:
while True:
element = self.to_show_queue.get_nowait()
position = []
position.append(self.white_board[element.x][element.y])
position.append(self.black_board[element.x][element.y])
position.append(self.white_ghost_board[element.x][element.y])
position.append(self.black_ghost_board[element.x][element.y])
for i in range(len(position)):
if element.color == i+1:
for e in position[i]:
self.c.itemconfig(e, state=_tk.NORMAL)
else:
for e in position[i]:
self.c.itemconfig(e, state=_tk.HIDDEN)
except _Queue.Empty:
pass
global _ui_factory
_ui_factory.mainroot.update()
def print_(self, text):
self.textarea.config(state=_tk.NORMAL)
self.textarea.insert(_tk.END, text)
self.textarea.see(_tk.END)
self.textarea.config(state=_tk.DISABLED)
global _ui_factory
_ui_factory.mainroot.update()
def clear_text(self):
self.textarea.config(state=_tk.NORMAL)
self.textarea.delete(1.0, _tk.END)
self.textarea.see(_tk.END)
self.textarea.config(state=_tk.DISABLED)
global _ui_factory
_ui_factory.mainroot.update()
def wait(self, ms):
try:
_time.sleep(ms * 0.001)
except:
self.close()
def close(self):
self.root.destroy()
_os._exit(0)
def create_othello_grid(self):
for i in range(self.NUMBER_OF_COLUMNS+1):
x0 = self.xpad + self.xstep * i
y0 = self.ypad
x1 = x0
y1 = self.ypad + self.ystep * self.NUMBER_OF_ROWS + 1
coords = x0, y0, x1, y1
self.c.create_line(coords, fill='black')
for j in range(self.NUMBER_OF_ROWS+1):
x0 = self.xpad
y0 = self.ypad + self.ystep * j
x1 = self.xpad + self.xstep * self.NUMBER_OF_COLUMNS + 1
y1 = y0
coords = x0, y0, x1, y1
self.c.create_line(coords, fill='black')
for i in range(self.NUMBER_OF_COLUMNS):
x0 = self.xpad + self.xstep / 2 + self.xstep * i
y0 = self.ypad / 2
x1 = x0
y1 = self.othello_size - self.ystep / 2
coords0 = x0, y0
coords1 = x1, y1
self.c.create_text(coords0, text=chr(ord('a')+i))
self.c.create_text(coords1, text=chr(ord('a')+i))
for j in range(self.NUMBER_OF_ROWS):
x0 = self.xpad / 2
y0 = self.ypad + self.ystep / 2 + self.ystep * j
x1 = self.othello_size - self.xstep / 2
y1 = y0
coords0 = x0, y0
coords1 = x1, y1
self.c.create_text(coords0, text='%s'%(j+1))
self.c.create_text(coords1, text='%s'%(j+1))
def mix_color(self, c1, c2, mix):
return c1 if mix == 0 else (c1 + c2) / 2
def create_piece(self, x0, y0, img, mix):
result = []
if img == self.WHITE:
r = self.mix_color(255, self.r, mix)
g = self.mix_color(255, self.g, mix)
b = self.mix_color(255, self.b, mix)
scale = 0.8
x1 = x0 + (1.0 - scale) / 2.0 * self.xstep
y1 = y0 + (1.0 - scale) / 2.0 * self.ystep
x2 = x0 + (1.0 - (1.0 - scale) / 2.0) * self.xstep
y2 = y0 + (1.0 - (1.0 - scale) / 2.0) * self.ystep
result.append(self.c.create_oval(x1, y1, x2, y2, state=_tk.HIDDEN, fill="#%02X%02X%02X" % (r, g, b), width=0))
if img == self.BLACK:
r = self.mix_color(0, self.r, mix)
g = self.mix_color(0, self.g, mix)
b = self.mix_color(0, self.b, mix)
scale = 0.8
x1 = x0 + (1.0 - scale) / 2.0 * self.xstep
y1 = y0 + (1.0 - scale) / 2.0 * self.ystep
x2 = x0 + (1.0 - (1.0 - scale) / 2.0) * self.xstep
y2 = y0 + (1.0 - (1.0 - scale) / 2.0) * self.ystep
result.append(self.c.create_oval(x1, y1, x2, y2, state=_tk.HIDDEN, fill="#%02X%02X%02X" % (r, g, b), width=0))
return result
def create_othello_pieces(self):
mixer = 0, 0, 1, 1
imgtype = self.WHITE, self.BLACK, self.WHITE, self.BLACK
boards = self.white_board, self.black_board, self.white_ghost_board, self.black_ghost_board
for n in range(len(boards)):
for i in range(self.NUMBER_OF_COLUMNS):
boards[n].append([])
for j in range(self.NUMBER_OF_ROWS):
x0 = self.xpad + self.xstep * i
y0 = self.ypad + self.ystep * j
img = self.create_piece(x0, y0, imgtype[n], mixer[n])
boards[n][i].append(img)
def fill_canvas(self):
self.xstep = self.othello_size / (self.NUMBER_OF_COLUMNS + 2)
self.ystep = self.othello_size / (self.NUMBER_OF_ROWS + 2)
self.xpad = (self.othello_size - self.NUMBER_OF_COLUMNS * self.xstep) / 2
self.ypad = (self.othello_size - self.NUMBER_OF_ROWS * self.ystep) / 2
self.create_othello_grid()
self.create_othello_pieces()
class BarChartUserInterface(object):
def __init__(self, bar_count):
"""This class starts the BarChartUserInterface.
Constants: (none)
Parameters for the class:
- bar_count: at least 1
Optional parameters: (none)
"""
_verify_int(bar_count, "Bar count", 1)
global _ui_factory
self.bar_chart = _BarChart(bar_count, _ui_factory.mainroot)
def set_bar_name(self, bar_index, text):
"""Set a name, provided by 'text', to a given bar_index.
Note: this function's effects are visible without calling show.
"""
_verify_int(bar_index, "Bar index", 0, self.bar_chart.bar_count - 1)
_verify_str(text, "Text")
self.bar_chart.set_bar_name(bar_index, text)
def raise_bar(self, bar_index):
"""Increment the given bar_index by 1.
"""
_verify_int(bar_index, "Bar index", 0, self.bar_chart.bar_count - 1)
self.bar_chart.raise_bar(bar_index)
def show(self):
"""Show the changes made to the display (i.e. after calling raise_bar).
"""
self.bar_chart.show()
def show_names(self, value):
"""Whether or not to show the names of the bars.
Value given must be a boolean.
Default at start is False.
"""
_verify_bool(value, "Show names")
self.bar_chart.show_names(value)
def show_values(self, value):
"""Whether or not to show the values of the bars.
Value given must be a boolean.
Default at start is True.
"""
_verify_bool(value, "Show values")
self.bar_chart.show_values(value)
def wait(self, ms):
"""Let your program wait for an amount of milliseconds.
This function only guarantees that it will wait at least this amount of time.
If the system, i.e., is too busy, then this time might increase.
- Python time module.
"""
_verify_int(ms, "Waiting time", 0)
self.bar_chart.wait(ms)
def close(self):
"""Closes the display and stops your program.
"""
self.bar_chart.close()
def stay_open(self):
"""Force the window to remain open.
Only has effect on Mac OS to prevent the window from closing after the execution finishes.
Make sure that this is the last statement you call when including it because the code does NOT continue after this.
"""
global _ui_factory
_ui_factory.mainroot.mainloop()
class _BarChart(object):
def __init__(self, bar_count, mainroot):
#create queue to store changes to placings
self.to_show_queue = _Queue.Queue(maxsize=0)
#variables used to keep the number of refreshes of names and values in check
self.show_names_bool = False
self.show_values_bool = True
self.bar_count = bar_count
#start the main window
self.root = _tk.Toplevel(mainroot)
self.root.title("BarChartUserInterface")
self.root.protocol("WM_DELETE_WINDOW", self.callback)
self.root.bind("<Escape>", self.callback)
self.frame = _tk.Frame(self.root)
self.frame.pack(fill=_tk.BOTH, expand=_tk.YES)
self.height = 575
self.width = 400
self.c = _tk.Canvas(self.frame, width=self.width, height=self.height, bg='white', bd=0, highlightthickness=0)
self.c.pack(fill=_tk.BOTH, expand=_tk.YES)
self.c.focus_set()
self.c.bind('<Configure>', self.redraw)
self.bar_max = 0
self.bars = []
self.names = []
self.create_bars()
self.redraw()
global _ui_factory
_ui_factory.mainroot.update()
def callback(self, event=None):
self.root.destroy()
_os._exit(0)
def set_bar_name(self, bar_index, text):
self.names[bar_index] = text;
self.redraw()
global _ui_factory
_ui_factory.mainroot.update()
def raise_bar(self, bar_index):
element = _BarChartHolder(bar_index)
self.to_show_queue.put(element)
def inc_bar(self, bar_index):
if (self.bars[bar_index] + 1) > self.bar_max:
self.bar_max = self.bars[bar_index] + 1
self.bars[bar_index] += 1
def show(self):
try:
while True:
element = self.to_show_queue.get_nowait()
self.inc_bar(element.bar_index)
except _Queue.Empty:
pass
self.redraw()
global _ui_factory
_ui_factory.mainroot.update()
def show_names(self, value):
self.show_names_bool = value
self.redraw()
global _ui_factory
_ui_factory.mainroot.update()
def show_values(self, value):
self.show_values_bool = value
self.redraw()
global _ui_factory
_ui_factory.mainroot.update()
def wait(self, ms):
try:
_time.sleep(ms * 0.001)
except:
self.close()
global _ui_factory
_ui_factory.mainroot.update()
def close(self):
self.root.destroy()
_os._exit(0)
return
def create_bars(self):
for i in range(self.bar_count): #@UnusedVariable
self.bars.append(0)
self.names.append('')
def redraw(self, event=None):
if event != None:
self.width = event.width
self.height = event.height
for e in self.c.find_all():
self.c.delete(e)
self.fill_canvas()
def fill_canvas(self):
xstep = self.width / (self.bar_count + 2)
xpad = (self.width - xstep * self.bar_count) / 2
xspacing = xstep / 10
ypad = self.height / 10
ypadtext = ypad / 3
for i in range(self.bar_count):
#draw the bar
x0 = xpad + xstep * i + xspacing
y0 = self.height - ypad
x1 = xpad + xstep * (i + 1) - xspacing
y1 = self.height - ypad
color = 0
if self.bar_max > 0:
y_len = self.bars[i] * (self.height - 2 * ypad) / self.bar_max
y1 -= y_len
color = self.bars[i] * 255 / self.bar_max
coords = x0, y0, x1, y1
hex_color = "#%02x%02x%02x" % (color, 0, 0) #red, green, blue
self.c.create_rectangle(coords, fill=hex_color)
#draw the values
x1 = xpad + xstep * i + xstep / 2
y1 -= ypadtext
coords = x1, y1
value = ("%d" % self.bars[i]) if self.show_values_bool else ''
self.c.create_text(coords, text=value)
#draw the names
x0 = xpad + xstep * i + xstep / 2
y0 += ypadtext
coords = x0, y0
name = self.names[i] if self.show_names_bool else ''
self.c.create_text(coords, text=name)
class SnakeUserInterface(object):
def __init__(self, width, height, scale=1.0):
"""This class starts the SnakeUserInterface.
Constants:
- EMPTY
- FOOD
- SNAKE
- WALL
Parameters for the class:
- width: at least 1
- height: at least 1
Optional parameters:
- scale: 0.25 to 1.0
"""
_verify_int(width, "Width", 1)
_verify_int(height, "Height", 1)
_verify_float(scale, 'Scale', 0.25, 1.0)
global _ui_factory
self.snake_interface = _Snake(width, height, _ui_factory.mainroot, scale)
self.EMPTY = _Snake.EMPTY
self.FOOD = _Snake.FOOD
self.SNAKE = _Snake.SNAKE
self.WALL = _Snake.WALL
def place(self, x, y, color):
"""Place a Snake piece (defined by 'color') on the given X and Y coordinates.
"""
_verify_int(x, 'X', 0, self.snake_interface.width - 1)
_verify_int(y, 'Y', 0, self.snake_interface.height - 1)
# 0 = empty, 1 = food, 2 = snake, 3 = wall, 4 = food_t, 5 = snake_t, 6 = wall_t
_verify_int(color, 'Color', 0, 6)
self.snake_interface.place(x, y, color)
def place_transparent(self, x, y, color):
"""Place a semi-transparent Snake piece (defined by 'color') on the given X and Y coordinates.
"""
_verify_int(x, 'X', 0, self.snake_interface.width - 1)
_verify_int(y, 'Y', 0, self.snake_interface.height - 1)
# 0 = empty, 1 = food_t, 2 = snake_t, 3 = wall_t (before next step in code)
_verify_int(color, 'Color', 0, 6)
if color == self.EMPTY:
self.place(x, y, self.EMPTY)
else:
self.place(x, y, color+3)
def clear(self):
"""Clears the display.
Note: this does not clear the text area!
"""
self.snake_interface.clear()
def show(self):
"""Show the changes made to the display (i.e. after calling place or clear)
"""
self.snake_interface.show()
def get_event(self):
"""Returns an event generated from the display.
The returned object has 2 properties:
- name: holds the group which the event belongs to.
- data: holds useful information for the user.
"""
return self.snake_interface.get_event()
def set_animation_speed(self, fps):
"""Set an event to repeat 'fps' times per second.
If the value is set to 0 or less, the repeating will halt.
In theory the maximum value is 1000, but this depends on activity of the system.
The generated events (available by using get_event) have these properties:
- name: 'alarm'.
- data: 'refresh'.
"""
_verify_float(fps, "Animation speed")
self.snake_interface.set_animation_speed(fps)
def print_(self, text):
"""Print text to the text area on the display.
This function does not add a trailing newline by itself.
"""
_verify_str(text, "Text")
self.snake_interface.print_(text)
def clear_text(self):
"""Clears the text area on the display.
"""
self.snake_interface.clear_text()
def wait(self, ms):
"""Let your program wait for an amount of milliseconds.
This function only guarantees that it will wait at least this amount of time.
If the system, i.e., is too busy, then this time might increase.
- Python time module.
"""
_verify_int(ms, "Waiting time", 0)
self.snake_interface.wait(ms)
def random(self, maximum):
"""Picks a random integer ranging from 0 <= x < maximum
Minimum for maximum is 1
"""
_verify_int(maximum, 'Random', 1)
return self.snake_interface.random(maximum)
def close(self):
"""Closes the display and stops your program.
"""
self.snake_interface.close()
def stay_open(self):
"""Force the window to remain open.
Only has effect on Mac OS to prevent the window from closing after the execution finishes.
Make sure that this is the last statement you call when including it because the code does NOT continue after this.
"""
global _ui_factory
_ui_factory.mainroot.mainloop()
class _Snake(object):
#one cannot prevent users from editing 'constants', as constants simply do not exist in Python
EMPTY = 0
FOOD = 1
SNAKE = 2
WALL = 3
def __init__(self, width, height, mainroot, scale=1.0):
#create queue to store changes to placings
self.to_show_queue = _Queue.Queue(maxsize=0)
self.event_queue = _Queue.Queue(maxsize=0)
#copy params
self.width = width
self.height = height
self.scale = scale
self.closing_window = False
#start the main window
self.root = _tk.Toplevel(mainroot)
self.root.title("SnakeUserInterface")
self.root.protocol("WM_DELETE_WINDOW", self.callback)
self.root.bind("<Escape>", self.callback)
self.root.resizable(False, False)
#calculate sizes
self.size_per_coord = int(25 * scale)
self.text_height = int(200 * scale)
#create main frame
self.frame = _tk.Frame(self.root, width=self.size_per_coord*self.width, height=self.size_per_coord*self.height+self.text_height)
self.frame.pack_propagate(0)
self.frame.pack()
#create board to hold references to snake-pieces
self.food_board = [] # for storing references to create_image
self.snake_board = []
self.wall_board = []
self.food_ghost_board = []
self.snake_ghost_board = []
self.wall_ghost_board = []
self.img_refs = [] # for storing references to images - order: food, snake, wall, food_t, snake_t, wall_t
#create and fill the canvas --> paintable area
self.c = _tk.Canvas(self.frame, width=self.size_per_coord*self.width, height=self.size_per_coord*self.height, bg="black", bd=0, highlightthickness=0)
self.c.pack()
self.last_x = -1 # used to generate mouseOver/Exit events
self.last_y = -1 # used to generate mouseOver/Exit events
self.fill_canvas()
#create the textholder
self.scrollbar = _tk.Scrollbar(self.frame)
self.scrollbar.pack(side=_tk.RIGHT, fill=_tk.Y)
self.textarea = _tk.Text(self.frame, yscrollcommand=self.scrollbar.set)
self.textarea.pack(side=_tk.LEFT, fill=_tk.BOTH)
self.scrollbar.config(command=self.textarea.yview)
self.textarea.config(state=_tk.DISABLED)
self.interval = 0
self.alarm_speed = 0
self.timer = self.milliseconds()
global _ui_factory
_ui_factory.mainroot.update()
def callback(self, event=None):
self.root.destroy()
_os._exit(0)
def milliseconds(self):
return _time.time() * 1000
def place(self, x, y, color):
element = _SnakeHolder(x, y, color)
self.to_show_queue.put(element)
def clear(self):
for x in range(self.width):
for y in range(self.height):
self.place(x, y, self.EMPTY)
def show(self):
try:
while True:
element = self.to_show_queue.get_nowait()
position = []
position.append(self.food_board[element.x][element.y])
position.append(self.snake_board[element.x][element.y])
position.append(self.wall_board[element.x][element.y])
position.append(self.food_ghost_board[element.x][element.y])
position.append(self.snake_ghost_board[element.x][element.y])
position.append(self.wall_ghost_board[element.x][element.y])
for i in range(len(position)):
# add 1 to i, because 0 is empty [same as doing color - 1]
# thus, if 0, then it doesn't match with 1 to 6
# therefore putting the whole position to hidden
if element.color == i+1:
for e in position[i]:
self.c.itemconfig(e, state=_tk.NORMAL)
else:
for e in position[i]:
self.c.itemconfig(e, state=_tk.HIDDEN)
except _Queue.Empty:
pass
global _ui_factory
_ui_factory.mainroot.update()
def get_event(self):
global _ui_factory
_ui_factory.mainroot.update()
while True:
try:
self.refresh_event()
event = self.event_queue.get_nowait()
return event
except _Queue.Empty:
wait_time = min(self.interval, 10)
self.wait(wait_time)
_ui_factory.mainroot.update()
def set_animation_speed(self, fps):
current_time = self.milliseconds()
if fps <= 0:
self.interval = 0
self.timer = current_time
return
if fps > 1000:
fps = 1000
self.interval = int(1000.0 / fps)
self.refresh_event()
def print_(self, text):
self.textarea.config(state=_tk.NORMAL)
self.textarea.insert(_tk.END, text)
self.textarea.see(_tk.END)
self.textarea.config(state=_tk.DISABLED)
global _ui_factory
_ui_factory.mainroot.update()
def clear_text(self):
self.textarea.config(state=_tk.NORMAL)
self.textarea.delete(1.0, _tk.END)
self.textarea.see(_tk.END)
self.textarea.config(state=_tk.DISABLED)
global _ui_factory
_ui_factory.mainroot.update()
def wait(self, ms):