-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathequations.py
More file actions
executable file
·2065 lines (1844 loc) · 90.7 KB
/
equations.py
File metadata and controls
executable file
·2065 lines (1844 loc) · 90.7 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
#!/bin/env python
from PyQt4 import QtGui
from PyQt4 import QtSvg
from PyQt4 import QtCore
import sys
import random
import subprocess
import os
import pickle
from os.path import expanduser
from os import listdir
import datetime
import argparse
import time
import math
import threading
# TODO:
# config: one time session length,
# division fibonacci, derivatives
# Open netflix in kids profile
# Make a function with setting comnmandline (avoid copy paste)
# Dungeon keeper on an other game to start alternatively to netflix
# TODO: fix unit test so it show a maze
# TODO: make rectungalar mazes
# TODO: unit tests for clock puzzle
class Maze():
class Sector:
def __init__(self,left,right,up,down):
self.visited = False
self.up = up
self.down = down
self.right = right
self.left = left
def __init__(self, mazeHeight, mazeWidth, tts):
# maze generation
self.tts = tts
self.width = mazeWidth
self.height = mazeHeight
self.sectors = []
for j in range(0,mazeHeight):
for i in range(0,mazeWidth):
self.sectors.append(
self.Sector(self.calculateSectorIndex(j,i-1),
self.calculateSectorIndex(j,i+1),
self.calculateSectorIndex(j-1,i),
self.calculateSectorIndex(j+1,i)))
self.generateMaze(mazeHeight,mazeWidth)
def say(self, text=None):
# This is one is for espeak tts
#subprocess.Popen(["espeak","-s 150",text])
# this one is for festival tts
if text == None:
text = self.description
p1 = subprocess.Popen(["echo", text], stdout=subprocess.PIPE)
subprocess.Popen(["padsp",self.tts,"--tts"], stdin=p1.stdout)
def generateMaze(self, mazeHeight, mazeWidth):
""" Pick a random sector and start generating"""
random.seed()
startx = random.randint(0,mazeWidth-1)
starty = random.randint(0,mazeHeight-1)
# Pick random location
self.routeLength = 0
self.longestRoute = 0
self.distantSector = 0
self.traverseSector(starty,startx,"none")
# print("Route: %d Longest route: %d finalSector=%d" %(self.routeLength,self.longestRoute,self.distantSector))
# Revert all negative , and clear other fields
self.clearSectors()
self.princessPosX = startx
self.princessPosY = starty
self.knightPosX = self.distantSector % mazeWidth
self.knightPosY = self.distantSector / mazeWidth
return
def calculateSectorIndex(self, posy, posx):
if posx < 0 or posx >= self.width:
return "none"
if posy < 0 or posy >= self.height:
return "none"
return posy*self.width + posx
def traverseSector(self, posy, posx, movingDirection):
currentSector = self.calculateSectorIndex(posy,posx)
if currentSector == "none" or self.sectors[currentSector].visited == True :
return
# mark sector as visited
self.sectors[currentSector].visited = True
# put into this sector where we came from
noGoDirection = "none"
if movingDirection == "none":
pass
elif movingDirection == "left":
# if we moved left then previous sector is on the right and we do not go right
self.sectors[currentSector].right = self.sectors[currentSector].right *(-1)
prevSector = self.calculateSectorIndex(posy,posx+1)
self.sectors[prevSector].left = self.sectors[prevSector].left *(-1)
noGoDirection = "right"
elif movingDirection == "right":
self.sectors[currentSector].left = self.sectors[currentSector].left *(-1)
prevSector = self.calculateSectorIndex(posy,posx-1)
self.sectors[prevSector].right = self.sectors[prevSector].right *(-1)
noGoDirection = "left"
elif movingDirection == "up":
self.sectors[currentSector].down = self.sectors[currentSector].down *(-1)
prevSector = self.calculateSectorIndex(posy+1,posx)
self.sectors[prevSector].up = self.sectors[prevSector].up *(-1)
noGoDirection = "down"
elif movingDirection == "down":
self.sectors[currentSector].up = self.sectors[currentSector].up *(-1)
prevSector = self.calculateSectorIndex(posy-1,posx)
self.sectors[prevSector].down = self.sectors[prevSector].down *(-1)
noGoDirection = "up"
# Choose next sector from does not visited
directions = ["left","right","up","down"]
# No point of going where we came from
if noGoDirection != "none":
directions.remove(noGoDirection)
while len(directions) > 0:
direction = random.choice(directions)
directions.remove(direction)
if direction == "left":
nextPosX = posx-1
nextPosY = posy
elif direction == "right":
nextPosX = posx+1
nextPosY = posy
elif direction == "up":
nextPosX = posx
nextPosY = posy-1
elif direction == "down":
nextPosX = posx
nextPosY = posy+1
# If current route is longer that
# the longest among routes then update
# the longest command
self.routeLength = self.routeLength + 1
if self.routeLength > self.longestRoute:
self.longestRoute = self.routeLength
self.distantSector = currentSector
self.traverseSector(nextPosY,nextPosX,direction)
self.routeLength = self.routeLength - 1
# TODO: Sector 0???
def clearSectors(self):
for sector in self.sectors:
assert(sector.visited == True)
if sector.left > 0 :
sector.left = "none"
elif sector.left < 0:
sector.left = sector.left*(-1)
if sector.right > 0 :
sector.right = "none"
elif sector.right < 0:
sector.right = sector.right*(-1)
if sector.up > 0 :
sector.up = "none"
elif sector.up < 0:
sector.up = sector.up*(-1)
if sector.down > 0 :
sector.down = "none"
elif sector.down < 0:
sector.down = sector.down*(-1)
return
class EquationsConfig:
"""Class to define object for serialization"""
def __init__(self, args):
self.terminate = False
self.data = { 'num_adds' : 1, 'num_subs' : 1,'num_muls' : 1,'num_divs' : 1, 'num_lang_puzzles' : 1, 'num_dialogues_puzzles' : 1,
'num_clock_puzzles' : 1, 'num_text_puzzles' : 1, 'num_buying_puzzles' : 1, 'num_arrangement_puzzles' : 1, 'num_snail_puzzles' : 1, 'num_memory_puzzles' : 1, 'num_mazes' : 1, 'num_typings' : 1,'day' : 0 , 'daily_counter' : 0, 'maximum_daily_counter' : 3, 'maximum_bears' : 15 , 'maximum_value' : 10, 'maximum_arrangement_size' : 2,
'maze_size' : 8, 'memory_size' : 4, 'content' : {}, 'tts' : "festival"}
# If there is a file unpickle it
# then check the data
# if data is obsolete then reinstantate date and zero the counter of daily watching
# if data is present then read counter
# if counter meets maximum then prevent from watching
# If counter is not in maximal state then increment
configDir = expanduser("~")+"/.equations/"
if os.path.isfile(configDir+"config"):
configFile = open(configDir+"config","r")
self.data = pickle.load(configFile)
self.process_arg(configDir,'num_adds', args.set_num_adds, -1)
self.process_arg(configDir,'num_subs', args.set_num_subs, -1)
self.process_arg(configDir,'num_muls', args.set_num_muls, -1)
self.process_arg(configDir,'num_divs', args.set_num_divs, -1)
self.process_arg(configDir,'num_lang_puzzles', args.set_num_lang_puzzles, -1)
self.process_arg(configDir,'num_dialogues_puzzles', args.set_num_dialogues_puzzles, -1)
self.process_arg(configDir,'num_text_puzzles', args.set_num_text_puzzles, -1)
self.process_arg(configDir,'num_snail_puzzles', args.set_num_snail_puzzles, -1)
self.process_arg(configDir,'num_memory_puzzles', args.set_num_memory_puzzles, -1)
self.process_arg(configDir,'num_buying_puzzles', args.set_num_buying_puzzles, -1)
self.process_arg(configDir,'num_arrangement_puzzles', args.set_num_arrangement_puzzles, -1)
self.process_arg(configDir,'num_clock_puzzles', args.set_num_clock_puzzles, -1)
self.process_arg(configDir,'num_mazes', args.set_num_mazes, -1)
self.process_arg(configDir,'num_typing_puzzles', args.set_num_typing_puzzles, -1)
self.process_arg(configDir,'daily_counter', args.set_daily_counter, -1)
self.process_arg(configDir,'maximum_daily_counter', args.set_maximum_daily_counter, 0)
self.process_arg(configDir,'maximum_value', args.set_maximum_value, -1)
self.process_arg(configDir,'maze_size', args.set_maze_size, -1)
self.process_arg(configDir,'memory_size', args.set_memory_size, -1)
self.process_arg(configDir,'maximum_arrangement_size', args.set_maximum_arrangement_size, -1)
self.process_arg(configDir,'maximum_bears', args.set_maximum_bears, -1)
if 'tts' not in self.data:
self.data['tts'] = "festival"
if args.tts <> "":
self.data['tts'] = args.tts
self.terminate = True;
self.print_config();
configFile = open(configDir+"config","w")
pickle.dump(self.data,configFile)
return;
if args.add_content != "":
self.terminate = True;
self.add_content(args.add_content)
self.list_content()
configFile = open(configDir+"config","w")
pickle.dump(self.data,configFile)
return
if args.remove_content != -1:
self.terminate = True;
self.remove_content(args.remove_content)
self.list_content()
configFile = open(configDir+"config","w")
pickle.dump(self.data,configFile)
return
# If there was option to print config then
# do so, and make program terminated
if args.print_config == True:
self.print_config();
self.terminate = True;
return;
# List pool of content
if args.list_content == True:
self.list_content()
self.terminate = True;
return;
if self.terminate == False:
if self.data['day'] != datetime.datetime.now().day:
self.data['day'] = datetime.datetime.now().day
self.data['daily_counter'] = 1
self.run = True
elif self.data['daily_counter'] < self.data['maximum_daily_counter']:
self.data['daily_counter'] = self.data['daily_counter'] + 1
self.run = True
else:
self.run = False
else:
if args.print_config == True:
print("\n No Config found!\n");
self.terminate = True;
return;
# If there is no file then create one a by pickling this object
if os.path.isdir(configDir) == False:
os.mkdir(configDir)
# Fill in new data
self.data['day'] = datetime.datetime.now().day
self.data['daily_counter'] = 1
self.run = True
configFile = open(configDir+"config","w")
pickle.dump(self.data,configFile)
def process_arg(self, configDir, key, arg_value, default_value):
if key not in self.data or arg_value > default_value:
self.data[key] = arg_value
self.terminate = True;
self.print_config();
configFile = open(configDir+"config","w")
pickle.dump(self.data,configFile)
return;
def print_attrib_int(self, key):
if key in self.data:
print("%s: %d" %(key,self.data[key]))
return
def print_attrib_str(self, key):
if key in self.data:
print("%s: %s" %(key,self.data[key]))
return
def print_config(self):
print(" Configuration: ")
self.print_attrib_int('num_adds')
self.print_attrib_int('num_subs')
self.print_attrib_int('num_muls')
self.print_attrib_int('num_divs')
self.print_attrib_int('num_lang_puzzles')
self.print_attrib_int('num_dialogues_puzzles')
self.print_attrib_int('num_clock_puzzles')
self.print_attrib_int('num_mazes')
self.print_attrib_int('num_text_puzzles')
self.print_attrib_int('num_buying_puzzles')
self.print_attrib_int('num_arrangement_puzzles')
self.print_attrib_int('num_snail_puzzles')
self.print_attrib_int('num_memory_puzzles')
self.print_attrib_int('num_typing_puzzles')
self.print_attrib_int('daily_counter')
self.print_attrib_int('maximum_daily_counter')
self.print_attrib_int('maximum_value')
self.print_attrib_int('maze_size')
self.print_attrib_int('memory_size')
self.print_attrib_int('maximum_bears')
self.print_attrib_int('maximum_arrangement_size')
self.print_attrib_str('tts')
if 'content' in self.data:
print("%s: %d" %('content',len(self.data['content'])))
def list_content(self):
i = 0
print("Content:\n")
for entry in self.data['content']:
print(str(i)+" "+entry+" : "+self.data['content'][entry])
i+=1
return
def add_content(self, entry):
command = entry[0:entry.find(':')]
picture = entry[entry.find(':')+1:]
if os.path.isfile(picture) and command != "":
self.data['content'][command] = picture
else:
print("\nError adding content! eg. --add_content <command>:<path to picture>")
return
def remove_content(self, index):
i = 0
if index < 0 or index > len(self.data['content']):
print("Error removing content: invalid index")
return
key = ""
for entry in self.data['content']:
print(str(i)+" "+entry)
if i == index:
key = entry
i+=1
self.data['content'].pop(key, None)
return
def shouldRun(self):
""" Function to decide if this session is legitimate to play cartoons"""
return self.run
def shouldTerminate(self):
return self.terminate
def getMaximumValue(self):
return self.data['maximum_value']
def getMazeSize(self):
return self.data['maze_size']
def getMemorySize(self):
return self.data['memory_size']
def getMaximumBears(self):
return self.data['maximum_bears']
def getMaximumArrangementSize(self):
return self.data['maximum_arrangement_size']
def getContent(self):
return self.data['content']
def getTTS(self):
return self.data['tts']
def isEnabled(self, key):
# In case of unknown key (there is not updated config stored on platform
# create relevant entry and set value to 1
if self.data.has_key(key) == False:
self.data[key] = 1
return self.data[key]
class Stop(QtGui.QWidget):
def __init__(self,args):
super(Stop, self).__init__()
# TODO make it in the middle
pic = QtGui.QLabel(self)
pic.setGeometry(300,100,757,767)
pic.setPixmap(QtGui.QPixmap(os.path.realpath(__file__).replace("equations.py","") + "/stop.png"))
pic.show()
self.update()
if args.dry_run == False:
subprocess.call(["sudo","shutdown","-c"])
subprocess.call(["sudo","shutdown","-h","+1"])
elif args.dry_run == "Test":
pass
else:
exit()
self.showFullScreen()
class Equation(QtGui.QWidget):
class Visualization:
def __init__(self,tts):
self.tts = tts
self.description = ""
self.stringToPrint = ""
# There is five minutes ofr each puzzle apart of memory which is 10
subprocess.call(["sudo","shutdown","-c"])
subprocess.call(["sudo","shutdown","-h","+5"])
def say(self, text=None):
# This is one is for espeak tts
#subprocess.Popen(["espeak","-s 150",text])
# this one is for festival tts
if text == None:
text = self.description
p1 = subprocess.Popen(["echo", text], stdout=subprocess.PIPE)
subprocess.Popen(["padsp",self.tts,"--tts"], stdin=p1.stdout)
def Render(self, qp, rect):
qp.setPen(QtGui.QColor(0,0,255))
qp.setFont(QtGui.QFont('Decorative',200))
qp.drawText(rect, QtCore.Qt.AlignCenter, self.stringToPrint)
pass
def setStringToPrint(self,stringToPrint):
self.stringToPrint = stringToPrint
def solved(self):
pass
def cleanup(self):
pass
class LangPuzzleVisualization(Visualization):
def __init__(self, label, pic, width, height, tts, stringToPrint):
Equation.Visualization.__init__(self,tts)
# TODO: put this in the middle
self.tts = tts
self.label = label
self.stringToPrint = stringToPrint
self.sizeOfAnimal = height/4
pixmap = pic.scaled(self.sizeOfAnimal,self.sizeOfAnimal)
self.tempImages = []
startx = width/2 - self.sizeOfAnimal/2
starty = 0
label.setGeometry(startx,starty,self.sizeOfAnimal,self.sizeOfAnimal)
label.setPixmap(pixmap)
label.show()
self.tempImages.append(label)
self.description = self.makeDescription(self.stringToPrint)
self.say()
def cleanup(self):
self.label.setHidden(True)
pass
def makeDescription(self,stringToPrint):
""" Function that generates message to be uttered when Lang puzzle is presented"""
return "What is on the picture? Possible answers: " + stringToPrint.replace("Answer:","")
def Render(self, qp, rect):
qp.setPen(QtGui.QColor(0,0,255))
qp.setFont(QtGui.QFont('Decorative',50))
qp.drawText(rect, QtCore.Qt.AlignCenter, self.stringToPrint)
class TypingPuzzleVisualization(Visualization):
def __init__(self, label, pic, width, height, tts, objectName, stringToPrint):
#super(TypingPuzzleVisualization, self).__init__(tts)
Equation.Visualization.__init__(self,tts)
subprocess.call(["sudo","shutdown","-c"])
subprocess.call(["sudo","shutdown","-h","+10"])
# TODO: put this in the middle
self.tts = tts
self.label = label
self.stringToPrint = stringToPrint
self.sizeOfAnimal = height/4
pixmap = pic.scaled(self.sizeOfAnimal,self.sizeOfAnimal)
self.tempImages = []
startx = width/2 - self.sizeOfAnimal/2
starty = 0
label.setGeometry(startx,starty,self.sizeOfAnimal,self.sizeOfAnimal)
label.setPixmap(pixmap)
label.show()
self.tempImages.append(label)
self.description = self.makeDescription(objectName)
self.say()
print("object name: " + objectName)
def cleanup(self):
self.label.setHidden(True)
pass
def makeDescription(self, objectName):
""" Function that generates message to be uttered when Lang puzzle is presented"""
return "Please type: " + objectName
def Render(self, qp, rect):
qp.setPen(QtGui.QColor(0,0,255))
qp.setFont(QtGui.QFont('Decorative',50))
qp.drawText(rect, QtCore.Qt.AlignCenter, self.stringToPrint)
class DialoguesPuzzleVisualization(Visualization):
def __init__(self, label, description, width, height, tts, stringToPrint):
Equation.Visualization.__init__(self,tts)
self.tts = tts
self.label = label
self.stringToPrint = stringToPrint
self.description = self.makeDescription(description, self.stringToPrint)
self.say()
def cleanup(self):
pass
def makeDescription(self, description, stringToPrint):
""" Function that generates message to be uttered when Lang puzzle is presented"""
return "Pick the best option. " + stringToPrint.replace("Answer:","")
def Render(self, qp, rect):
qp.setPen(QtGui.QColor(0,0,255))
qp.setFont(QtGui.QFont('Decorative',30))
qp.drawText(rect, QtCore.Qt.AlignCenter, self.stringToPrint)
class BearsPuzzleVisualization(Visualization):
def __init__(self, picName, qparent, x, y, width, height, tts, numBears):
Equation.Visualization.__init__(self,tts)
self.tts = tts
self.tempImages = []
self.stringToPrint = "? ="
is_svg = picName[-4:] == ".svg"
self.animals = picName[picName.rfind('/')+1:-4] + "s"
for pos in range(0,numBears):
sizeOfBear = width/10
if (pos+1)*sizeOfBear >= width:
posx = x+(pos+1)*sizeOfBear - width
posy = y+sizeOfBear
else:
posx = x+pos*sizeOfBear
posy = y
if is_svg:
pic = QtSvg.QSvgWidget(picName, qparent)
pic.setGeometry(posx,posy,sizeOfBear,sizeOfBear)
else:
im = QtGui.QPixmap(picName).scaled(sizeOfBear,sizeOfBear)
pic = QtGui.QLabel(qparent)
pic.setGeometry(posx,posy,sizeOfBear,sizeOfBear)
pic.setPixmap(im)
pic.show()
self.tempImages.append(pic)
self.description = self.makeDescription()
time.sleep(1)
self.say()
pass
def makeDescription(self):
return "How many "+self.animals+" You can see?"
def cleanup(self):
for widget in self.tempImages:
widget.setHidden(True)
class ArrangementPuzzleVisualization(Visualization):
def __init__(self, qparent, sofaName, toyName, x, y, width, height, tts, stringToPrint, numBears):
Equation.Visualization.__init__(self,tts)
self.tts = tts
self.tempImages = []
self.stringToPrint = stringToPrint
self.sofa = QtSvg.QSvgWidget(sofaName, qparent)
self.sofa.setGeometry(0,0,width,height/2)
self.sofa.show()
for pos in range(0,numBears):
pic = QtSvg.QSvgWidget(toyName, qparent)
sizeOfBear = width/10
posx = x+(-numBears/2 + pos)*sizeOfBear + width/2
posy = y + 2*height/7 - sizeOfBear
pic.setGeometry(posx,posy,sizeOfBear,sizeOfBear)
effect = QtGui.QGraphicsColorizeEffect(qparent)
effect.setColor(QtGui.QColor(50,200*(pos%2),50*(pos%5)))
pic.setGraphicsEffect(effect)
pic.show()
self.tempImages.append(pic)
self.description = self.makeDescription(numBears)
time.sleep(1)
self.say()
pass
def makeDescription(self, numBears):
phrase = ""
if numBears == 1:
phrase = "one bear "
else:
phrase = str(numBears)+" bears "
return "How many ways You can sit "+phrase+"on the sofa?"
def cleanup(self):
self.sofa.setHidden(True)
for widget in self.tempImages:
widget.setHidden(True)
def Render(self, qp, rect):
qp.setPen(QtGui.QColor(0,0,255))
qp.setFont(QtGui.QFont('Decorative',150))
qp.drawText(rect, QtCore.Qt.AlignCenter, self.stringToPrint)
pass
class ClockPuzzleVisualization(Visualization):
def __init__(self, qp, pic, x, y, width, height, tts, stringToPrint, correctTime):
Equation.Visualization.__init__(self,tts)
self.tts = tts
self.sizeOfClock = width/5
self.tempImages = []
posx = width/2 - self.sizeOfClock/2
posy = 0
pic.setGeometry(posx,posy,self.sizeOfClock,self.sizeOfClock)
self.tempImages.append(pic)
self.visualized = True
time.sleep(1)
self.description = self.makeDescription(stringToPrint)
self.stringToPrint = stringToPrint
self.say()
pic.show()
self.pic = pic
# remove answer enumeration and leave only hour
self.degrees = correctTime * 360/12
# Big pointer
self.midx = width/2
self.midy = self.sizeOfClock*0.42
qp.setPen(QtGui.QPen(QtCore.Qt.black, 10, QtCore.Qt.SolidLine))
qp.drawLine(self.midx,self.midy,self.midx,0 + self.sizeOfClock*0.2 )
# small pointer
qp.setPen(QtGui.QPen(QtCore.Qt.black, 13, QtCore.Qt.SolidLine))
qp.translate(self.midx,self.midy)
qp.rotate(self.degrees)
qp.drawLine(0,0,0 , 0 - self.sizeOfClock*0.15)
def makeDescription(self,stringToPrint):
""" Function that generates message to be uttered when Clock puzzle is presented"""
return "What time is it?"
def Render(self,qp, rect):
qp.setPen(QtGui.QColor(0,0,255))
qp.setFont(QtGui.QFont('Decorative',50))
qp.drawText(rect, QtCore.Qt.AlignCenter, self.stringToPrint)
qp.setPen(QtGui.QPen(QtCore.Qt.black, 10, QtCore.Qt.SolidLine))
qp.drawLine(self.midx,self.midy,self.midx,0 + self.sizeOfClock*0.2 )
# small pointer
qp.setPen(QtGui.QPen(QtCore.Qt.black, 13, QtCore.Qt.SolidLine))
qp.translate(self.midx,self.midy)
qp.rotate(self.degrees)
qp.drawLine(0,0,0 , 0 - self.sizeOfClock*0.15)
def cleanup(self):
self.pic.setHidden(True)
class SnailPuzzleVisualization(Visualization):
def __init__(self, qparent, raceFileName, animalFileName, animalName, animalSpeed, x, y, width, height, tts, stringToPrint, distance):
Equation.Visualization.__init__(self,tts)
subprocess.call(["sudo","shutdown","-c"])
subprocess.call(["sudo","shutdown","-h","+10"])
self.tts = tts
self.sizeOfClock = width/5
self.tempImages = []
# Load Animal picture
# Get Animal name for utterance
self.animalName = animalName
# Get speed of animal
self.animalSpeed = animalSpeed
self.distance = str(distance)
self.race = QtSvg.QSvgWidget(raceFileName, qparent)
self.race.setGeometry(0,0,width,height/2.5)
self.race.show()
posx = 0
posy = 0
pic = QtSvg.QSvgWidget(animalFileName, qparent)
pic.setGeometry(posx,posy,self.sizeOfClock,self.sizeOfClock)
time.sleep(1)
self.description = self.makeDescription(stringToPrint)
self.stringToPrint = stringToPrint
self.say()
pic.show()
self.pic = pic
def makeDescription(self,stringToPrint):
""" Function that generates message to be uttered when Clock puzzle is presented"""
speed = self.animalSpeed
if speed == "one" or speed == "1":
speed += " meter"
else:
speed += " meters"
total_distance = self.distance
if total_distance == "one" or total_distance == "1":
total_distance += " meter"
else:
total_distance += " meters"
return "A "+self.animalName + "can travel " + speed +" per minute. How many minutes does the "+self.animalName+ " need to travel " +total_distance +" ?"
def Render(self,qp, rect):
qp.setPen(QtGui.QColor(0,0,255))
qp.setFont(QtGui.QFont('Decorative',50))
qp.drawText(rect, QtCore.Qt.AlignCenter, self.stringToPrint)
def cleanup(self):
self.pic.setHidden(True)
self.race.setHidden(True)
class TextPuzzleVisualization(Visualization):
def __init__(self, qparent, picName, x, y, width, height, tts, stringToPrint, kasiaItems, numItems, relation):
Equation.Visualization.__init__(self,tts)
self.tts = tts
self.tempImages = []
self.stringToPrint = stringToPrint
for pos in range(0,numItems):
pic = QtSvg.QSvgWidget(picName, qparent)
sizeOfItem = width/10
if (pos+1)*sizeOfItem >= width:
posx = x+(pos+1)*sizeOfItem - width
posy = y+sizeOfItem
else:
posx = x+pos*sizeOfItem
posy = y
pic.setGeometry(posx,posy,sizeOfItem,sizeOfItem)
pic.show()
self.tempImages.append(pic)
time.sleep(1)
self.description = self.makeDescription(numItems, relation)
self.say()
def Render(self,qp, rect):
qp.setPen(QtGui.QColor(0,0,255))
qp.setFont(QtGui.QFont('Decorative',50))
qp.drawText(rect, QtCore.Qt.AlignCenter, self.stringToPrint)
def makeDescription(self, sumItems, relationText):
return "Katie and Stephanie have " + str(sumItems) + " ice creams all together. Stephanie has " + relationText + " Katie has. How many ice creams does Katie have?"
def cleanup(self):
for widget in self.tempImages:
widget.setHidden(True)
class MemoryPuzzleVisualization(Visualization):
class Card:
def __init__(self, qparent, imageFile, cardBackFile, col, row, x, y, cardSize, margin ):
self.revealed = False
self.imageFile = imageFile
image = QtGui.QPixmap(imageFile)
im = image.scaled(cardSize,cardSize)
self.pic = QtGui.QLabel(qparent)
self.stepx = cardSize*margin
self.stepy = cardSize*margin
x += (margin - 1)/2*cardSize
y += (margin - 1)/2*cardSize
self.pic.setGeometry(x + col*self.stepx,y + row*self.stepy, cardSize, cardSize)
self.pic.setPixmap(im)
backIm = QtGui.QPixmap(cardBackFile)
backCard = backIm.scaled(cardSize,cardSize)
self.back = QtGui.QLabel(qparent)
self.back.setGeometry(x + col*self.stepx,y + row*self.stepy, cardSize, cardSize)
self.back.setPixmap(backCard)
def show(self):
if self.revealed == True:
self.back.setHidden(True)
self.pic.show()
else:
self.pic.setHidden(True)
self.back.show()
def cleanup(self):
self.pic.setHidden(True)
self.back.setHidden(True)
def getMaxDivisor(self,n):
divisor = n
for i in range(n/2,1,-1):
if n % i == 0:
divisor = i
break
return divisor
def __init__(self, qparent, imagesDir, imagesFiles, x, y, width, height, tts ):
Equation.Visualization.__init__(self,tts)
subprocess.call(["sudo","shutdown","-c"])
subprocess.call(["sudo","shutdown","-h","+10"])
self.tts = tts
self.x = x
self.y = y
self.width = width
self.height = height
self.choicex = 0
self.choicey = 0
self.margin = 1.1
self.chosenx = -1
self.choseny = -1
self.timer = threading.Timer(0.5, self.hideCards)
self.timer.cancel()
# Generate
self.cols = self.getMaxDivisor(len(imagesFiles)/2)
self.rows = len(imagesFiles)/self.cols
self.cardSize = min(width/10,width/self.margin/self.cols)
# Go through list and get two indeces for each of it
# Then load image and remove from the list
# make it open or closed state
row = 0
col = 0
self.cards = {}
while len(imagesFiles) > 0 :
im = random.choice(imagesFiles)
imagesFiles.remove(im)
self.cards[(col,row)] = self.Card(qparent, imagesDir + "/" + im, imagesDir + "/../../cardback.png", col, row, x, y, self.cardSize, self.margin)
col += 1
if col == self.cols:
col = 0
row += 1
self.description = "Can you solve memory puzzle?"
self.say()
def solved(self):
solved = True
for card in self.cards.values():
solved = solved and card.revealed
return solved
def hideCards(self):
self.cards[(self.choicex,self.choicey)].revealed = False
self.cards[(self.chosenx,self.choseny)].revealed = False
self.chosenx = -1
self.choseny = -1
def Render(self,qp, rect):
for card in self.cards.values():
card.show()
# Draw rectangle around chosen card
if self.chosenx <> -1:
self.drawRectangle(qp, self.chosenx, self.choseny, QtCore.Qt.green)
self.drawRectangle(qp, self.choicex, self.choicey, QtCore.Qt.blue)
def drawRectangle(self, qp, col, row, color):
# Draw rectangule of choice
offsetx = self.cardSize*self.margin*col
offsety = self.cardSize*self.margin*row
qp.setPen(QtGui.QPen(color, 10, QtCore.Qt.SolidLine))
# top horizontal
qp.drawLine(self.x + offsetx,self.y + offsety,self.x + offsetx + self.cardSize*self.margin, self.y + offsety)
# left vertical
qp.drawLine(self.x + offsetx,self.y + offsety,self.x + offsetx, self.y + offsety + self.cardSize*self.margin)
# bottom horizontal
qp.drawLine(self.x + offsetx,self.y + offsety + self.cardSize*self.margin,self.x + offsetx + self.cardSize*self.margin, self.y + offsety + self.cardSize*self.margin)
# right vertical
qp.drawLine(self.x + offsetx + self.cardSize*self.margin, self.y + offsety, self.x + offsetx + self.cardSize*self.margin, self.y + offsety + self.cardSize*self.margin)
def updateState(self,e):
if self.timer.isAlive():
return
if e.key() == QtCore.Qt.Key_Up and self.choicey > 0:
self.choicey-=1
elif e.key() == QtCore.Qt.Key_Down and self.choicey < self.rows - 1:
self.choicey+=1
elif e.key() == QtCore.Qt.Key_Left and self.choicex > 0 :
self.choicex-=1
elif e.key() == QtCore.Qt.Key_Right and self.choicex < self.cols - 1:
self.choicex+=1
elif e.key() == QtCore.Qt.Key_Return:
revealed = self.cards[(self.choicex,self.choicey)].revealed
if self.chosenx == -1:
if revealed == False:
self.cards[(self.choicex,self.choicey)].revealed = True
self.chosenx = self.choicex
self.choseny = self.choicey
else:
if revealed == False:
self.cards[(self.choicex,self.choicey)].revealed = True
# If they match then reset state...
if self.cards[(self.choicex,self.choicey)].imageFile != self.cards[(self.chosenx,self.choseny)].imageFile:
# if they do not then leave them open for a split second
self.timer = threading.Timer(0.5, self.hideCards)
self.timer.start()
else:
self.chosenx = -1
self.choseny = -1
if e.key() == QtCore.Qt.Key_R:
self.say()
def cleanup(self):
for card in self.cards.values():
card.cleanup()
class BuyingPuzzleVisualization(Visualization):
def __init__(self, qparent, x, y, width, height, tts, stringToPrint, answer, pocket_coins, resourcesPath, item_file):
Equation.Visualization.__init__(self,tts)
self.tts = tts
self.x = x
self.y = y
self.width = width
self.height = height
self.resourcesPath = resourcesPath
self.tempImages = []
self.stringToPrint = stringToPrint
self.sizeOfItem = width/10
data = item_file.split('-')
pos = 0
# TODO: Make various items to be chosen
self.pic = QtSvg.QSvgWidget(resourcesPath + "/" + item_file, qparent)
if (pos+1)*self.sizeOfItem >= width:
posx = x+(pos+1)*self.sizeOfItem - width
posy = y+self.sizeOfItem
else:
posx = x+pos*self.sizeOfItem
posy = y
self.pic.setGeometry(posx,posy,self.sizeOfItem,self.sizeOfItem)
self.pic.show()
# Presenting pocket money
self.drawCoins(qparent, pocket_coins,0,self.sizeOfItem*1.75,self.sizeOfItem,self.sizeOfItem*0.75)
self.description = self.makeDescription(data[0].replace("_"," "), data[1], data[2].replace(".svg",""))
self.say()
time.sleep(1)
def cleanup(self):
self.pic.setHidden(True)
for widget in self.tempImages:
widget.setHidden(True)
def drawCoins(self, qparent, pocket_coins,startx,starty,zloty_size,grosz_size):
posx = startx
posy = starty
fives = pocket_coins[(5,0)]
self.drawCoin(qparent, self.resourcesPath + "/piec.svg",posx,posy,zloty_size,fives)
posx += fives*zloty_size
twos = pocket_coins[(2,0)]
self.drawCoin(qparent, self.resourcesPath + "/dwa.svg",posx,posy,zloty_size,twos)
posx += twos*zloty_size
ones = pocket_coins[(1,0)]
self.drawCoin(qparent, self.resourcesPath + "/jeden.svg",posx,posy,zloty_size,ones)
posx += ones*zloty_size
fives = pocket_coins[(0,50)]
self.drawCoin(qparent, self.resourcesPath + "/50cents.svg",posx,posy,grosz_size,fives)
posx += fives*grosz_size
twos = pocket_coins[(0,20)]
self.drawCoin(qparent, self.resourcesPath + "/20cents.svg",posx,posy,grosz_size,twos)
posx += twos*grosz_size
ones = pocket_coins[(0,10)]
self.drawCoin(qparent, self.resourcesPath + "/10cents.svg",posx,posy,grosz_size,ones)
posx += ones*grosz_size
return