-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMain.py
899 lines (691 loc) · 32.1 KB
/
Main.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
import PyQt5
from PyQt5 import QtGui, QtCore
from PyQt5.QtWidgets import (QApplication, QFileDialog, QHBoxLayout, QLabel,
QPushButton, QSizePolicy, QSlider, QStyle, QVBoxLayout, QWidget)
from PyQt5.QtWidgets import QMainWindow,QWidget, QPushButton, QAction, QComboBox, QGridLayout, QLineEdit, QMessageBox, QCheckBox
from PyQt5.QtGui import QPainter, QColor, QBrush, QIcon, QFont
from PyQt5.QtCore import QRect, QPoint, QTimer
import sys
from pynput.mouse import Controller
from inputs import devices, get_gamepad
import random
import pygame
from threading import Timer
import jsonify
import json
import time
from os import listdir
import os
class StartWindow(QMainWindow):
def __init__(self):
super(StartWindow, self).__init__()
## Generic window set up.
self.setWindowTitle("Main Menu")
self.layout = QGridLayout()
self.main_widget = QWidget()
self.setCentralWidget(self.main_widget)
self.main_widget.setLayout(self.layout)
## This object holds the settings set by the user.
self.infoPackage = InfoPackage()
## Add buttons and connect them to actions.
startButton = QPushButton("Start")
editButton = QPushButton("Edit")
self.layout.addWidget(startButton, 0, 0)
self.layout.addWidget(editButton, 1, 0)
startButton.clicked.connect(self.openMainWindow)
editButton.clicked.connect(self.openEditWindow)
self.show()
def openMainWindow(self):
self.mainWindow = MainWindow(self, self.infoPackage)
def openEditWindow(self):
self.editWindow = EditWindow(self, self.infoPackage)
def getInfoPackage(self):
return self.infoPackage
class InfoPackage():
def __init__(self):
## Trail settings.
self.Actions = list()
self.trial_length = 20 # Length of trial in seconds.
self.style = 0 # Style, this corresponds to style_list bellow.
self.show_time = False # Option to show time. (Default false)
self.show_points = False # Option to show points. (Default false)
self.add_points = True # Options to add points when the user scores. (Default true)
self.remove_points = True # Option to remove points when user misses. (Default true)
self.start_points = 0 # Defines starting points.
self.blocking = True # Allows user to hit the same box multiple times in a row if false. (Default true)
self.color_time = False # Time is now displayed with a color based on urgancy.
self.filename = "filename" # This is the name the file with be saved with.
self.legacy_tracking = False # if true, Mouse tracking is done by taking the difference from the centre (without persistence).
## These lists are required for exporting to excel.
self.style_list = ["light", "dark", "strange", "no feedback"]
self.action_types = ["sensitivity" , "square1x", "square2x", "square1width", "square2width", "invert"]
def setActions(self, actionList):
self.Actions = actionList
def setTrialTime(self, time, show, color):
self.trial_length = time
self.show_time = show
self.color_time = color
def setStyle(self, type, block):
self.style = type
self.blocking = block
def setPoints(self, amount, showPoints, addPoints, removePoints):
self.start_points = amount
self.show_points = showPoints
self.add_points = addPoints
self.remove_points = removePoints
def setFileName(self, name):
self.filename = name
def setLegacy(self, legacy):
self.legacy_tracking = legacy
class EditAction():
def __init__(self, type, value, time):
self.type = type;
self.value = value;
self.time = time;
class EditWindow(QMainWindow):
def __init__(self, parent, info):
super(EditWindow, self).__init__()
## General window set up.
self.info = info
self.parent = parent
self.layout = QGridLayout()
self.main_widget = QWidget()
self.setCentralWidget(self.main_widget)
self.main_widget.setLayout(self.layout)
self.setWindowTitle("Options")
###
## Global settings
###
# For ease of styling
# An increment in maxIndex is symbolised by ####
self.maxIndex = 0
# Create larger font for points
titleFont = QFont("Times", 10, QtGui.QFont.Bold)
self.saveTag = QLabel("Save filename: ")
self.saveInput = QLineEdit(self.info.filename)
self.layout.addWidget(self.saveTag, self.maxIndex, 0)
self.layout.addWidget(self.saveInput, self.maxIndex, 1)
####
self.maxIndex = self.maxIndex+1
self.timeTag = QLabel("Trial length (s)")
self.timeTag.setFont(titleFont)
self.layout.addWidget(self.timeTag, self.maxIndex, 0)
####
self.maxIndex = self.maxIndex+1
self.timeInput = QLineEdit(str(self.info.trial_length));
self.showTime = QCheckBox("Show time")
if(self.info.show_time):
self.showTime.toggle()
self.colorTime = QCheckBox("Color time")
if(self.info.color_time):
self.colorTime.toggle()
self.layout.addWidget(self.timeInput, self.maxIndex, 0)
self.layout.addWidget(self.showTime, self.maxIndex, 1)
self.layout.addWidget(self.colorTime, self.maxIndex, 2)
####
self.maxIndex = self.maxIndex+1
pointLabel = QLabel("Points")
self.layout.addWidget(pointLabel, self.maxIndex, 0)
self.Legacy = QCheckBox("Legacy tracking")
if(self.info.legacy_tracking):
self.Legacy.toggle()
self.layout.addWidget(self.Legacy, self.maxIndex, 1)
####
self.maxIndex = self.maxIndex+1
self.showPoints = QCheckBox("Show Points")
if(self.info.show_points):
self.showPoints.toggle()
self.startingPoints = QLineEdit(str(self.info.start_points))
self.addPoints = QCheckBox("Gain points")
if(self.info.add_points):
self.addPoints.toggle()
self.layout.addWidget(self.showPoints, self.maxIndex, 1)
self.layout.addWidget(self.startingPoints, self.maxIndex, 0)
self.layout.addWidget(self.addPoints, self.maxIndex, 2)
####
self.maxIndex = self.maxIndex+1
self.blocking = QCheckBox("Blocking")
if(self.info.blocking):
self.blocking.toggle()
self.removePoints = QCheckBox("Lose points")
if(self.info.remove_points):
self.removePoints.toggle()
self.layout.addWidget(self.blocking, self.maxIndex, 1)
self.layout.addWidget(self.removePoints, self.maxIndex, 2)
####
self.maxIndex = self.maxIndex+1
self.styleTag = QLabel("Styles")
self.layout.addWidget(self.styleTag, 6, 0)
self.styleTag.setFont(titleFont)
####
self.maxIndex = self.maxIndex+1
self.style = QComboBox(self)
self.style.addItem("light theme")
self.style.addItem("dark theme")
self.style.addItem("strange theme")
self.style.addItem("No feedback theme")
self.style.setCurrentIndex(self.info.style)
pointLabel.setFont(titleFont)
self.layout.addWidget(self.style, self.maxIndex, 0)
###
## Update settings.
###
self.Actions = self.info.Actions
self.ActionsTypes = list()
self.ActionsValues = list()
self.ActionsTimes = list()
addButton = QPushButton("+")
removeButton = QPushButton("-")
submitButton = QPushButton("Save")
typeTag = QLabel("type")
valueTag = QLabel("value")
timeTag = QLabel("time in sec")
addButton.clicked.connect(self.add)
removeButton.clicked.connect(self.remove)
submitButton.clicked.connect(self.submit)
####
self.maxIndex = self.maxIndex+1
self.layout.addWidget(addButton, self.maxIndex, 0)
self.layout.addWidget(removeButton, self.maxIndex, 1)
self.layout.addWidget(submitButton, self.maxIndex, 2)
####
self.maxIndex = self.maxIndex+1
self.layout.addWidget(typeTag, self.maxIndex, 0)
self.layout.addWidget(valueTag, self.maxIndex, 1)
self.layout.addWidget(timeTag, self.maxIndex, 2)
self.fill()
self.show()
def fill(self):
'''
Add actions for each actions currently in aciton list in info package.
'''
for a in self.Actions:
self.add(a.type, a.value, a.time)
def add(self, ty = 0, v = "1", ti = "0"):
'''
Add new action. Increment maxIndex.
Creates a combo box and two inputs for value and time.
'''
self.typeBox = QComboBox(self)
self.typeBox.addItem("sensitivity")
self.typeBox.addItem("square1x(%)")
self.typeBox.addItem("square2x(%)")
self.typeBox.addItem("square1width")
self.typeBox.addItem("square2width")
self.typeBox.addItem("invert(1/0)")
self.typeBox.setCurrentIndex(ty)
offset = 9
self.ActionsTypes.append(self.typeBox)
currentIndex = len(self.ActionsTypes)
self.layout.addWidget(self.typeBox, self.maxIndex, 0)
self.valueBox = QLineEdit(v)
self.ActionsValues.append(self.valueBox)
self.layout.addWidget(self.valueBox, self.maxIndex, 1)
self.timeBox = QLineEdit (ti)
self.ActionsTimes.append(self.timeBox)
self.layout.addWidget(self.timeBox, self.maxIndex, 2)
self.maxIndex = self.maxIndex + 1
def remove(self):
'''
Removes last action.
'''
if(len(self.ActionsTimes) != 0):
self.maxIndex = self.maxIndex - 1
self.ActionsTypes.pop().deleteLater()
self.ActionsValues.pop().deleteLater()
self.ActionsTimes.pop().deleteLater()
def submit(self):
'''
Submit all information for information package.
'''
## Initalise variables.
infoPackage = self.parent.getInfoPackage()
temp_list = list()
i = 0
startPoints = 0
## Catch if startpoints is not a number.
try:
startPoints = int(self.startingPoints.text())
except:
startingPoints = 0
## Set all other options.
self.info.setFileName(self.saveInput.text())
self.info.setTrialTime(self.timeInput.text(), self.showTime.isChecked(), self.colorTime.isChecked())
self.info.setStyle(self.style.currentIndex(), self.blocking.isChecked())
self.info.setPoints(startPoints, self.showPoints.isChecked(), self.addPoints.isChecked(), self.removePoints.isChecked())
self.info.setLegacy(self.Legacy.isChecked())
## Create actions list from inputs.
for i in range(0, len(self.ActionsTypes)):
type = self.ActionsTypes[i].currentIndex()
val = self.ActionsValues[i].text()
time = self.ActionsTimes[i].text()
# Create action object.
temp_action = EditAction(type, val, time)
# Add action object to queue.
temp_list.append(temp_action)
# Assign queue to info package.
self.info.setActions(temp_list)
# Close settings window.
self.close()
class MainWindow(QMainWindow):
def __init__(self, parent, info):
super(MainWindow, self).__init__()
## General initalisation.
self.setWindowTitle("Play")
self.info = info
self.recorder = Recorder()
## Set color scheme depending on style selected.
if(self.info.style == 0):
self.background_color = "white"
self.square_color_normal = "grey"
self.square_color_score = "green"
self.square_color_fail = "red"
if(self.info.style == 1):
self.background_color = "grey"
self.square_color_normal = "white"
self.square_color_score = "green"
self.square_color_fail = "red"
if(self.info.style == 2):
self.background_color = "blue"
self.square_color_normal = "yellow"
self.square_color_score = "green"
self.square_color_fail = "red"
if(self.info.style == 3):
self.background_color = "white"
self.square_color_normal = "grey"
self.square_color_score = "grey"
self.square_color_fail = "grey"
p = self.palette()
p.setColor(self.backgroundRole(), QColor(self.background_color))
self.setPalette(p)
## Create first rectangle details.
self.begin_one = QtCore.QPoint()
self.end_one = QtCore.QPoint()
self.color_one = QtGui.QColor(self.square_color_normal)
self.width_one= 140
self.x_one = 300
## Create second rectangle details.
self.begin_two = QtCore.QPoint()
self.end_two = QtCore.QPoint()
self.color_two = QtGui.QColor(self.square_color_normal)
self.width_two = 140
self.x_two = 1500
## Initalise Mouse
self.mouse = Controller()
## Create exit menu option.
exitAction = QAction(QIcon('exit.png'), "exit", self)
exitAction.setShortcut('Ctrl+E')
exitAction.triggered.connect(self.close_call)
## Add menu bar.
menuBar = self.menuBar()
fileMenu = menuBar.addMenu('&File')
fileMenu.addAction(exitAction)
## Initalise pygame and configer depending on if a joystick is available.
pygame.init()
if(pygame.joystick.get_count() < 1):
self.type = "mouse"
else:
if(pygame.joystick.get_count() == 1):
print("Joystick connected.")
self.my_joystick = pygame.joystick.Joystick(0)
self.my_joystick.init()
self.type = "joystick"
#if(pygame.joystick.get_count() == 2):
# print("Two joysticks connected")
# self.my_joystick = pygame.joystick.Joystick(0)
# self.my_joystick2 = pygame.joystick.Joystick(1)
# self.type = "joystick2"
# self.recorder2 = Recorder()
# self.mouse_position2 = self.geometry().width()/2
# self.mouse_indicator2 = self.geometry().width()/2
## Initalise basic variables.
# This identifies (actual in pixels) mouse position, be it from the mouse or another controller.
self.mouse_position = self.geometry().width()/2
# This identifies (adjusted/relative) mouse position, be it from the mouse or another controller.
self.mouse_indicator = self.geometry().width()/2
# This indicates the current sensitivity.
self.sensitivity = 1
# This indcates if the mouse movement is flipped.
self.flipSensitivity = 0
# This indicates the default y position of the rectangles on the screen.
self.default_y = 300
# This initalises the variable indicating the current activated square. 0 implies none are active.
self.current_activated = 0
# This blocks points from dropping after the an inital point has been lost.
self.lose_block = 0
# Inialises points based on Info class.
self.points = self.info.start_points
# Signal for trail status. Required because of the way pyqt5 uses threading.
self.trial_over = False
# Initalise square positions.
self.set_first_square(300, self.default_y, 140, 80)
self.set_second_square(1500, self.default_y, 140, 80)
# If time is active, create label and initalise it.
if(self.info.show_time):
self.time_left = int(self.info.trial_length)
self.timeLabel = QLabel(str(self.info.trial_length) + " seconds", self)
self.timeLabel.setStyleSheet('color: green')
timeFont = QFont()
self.timeLabel.setWordWrap(True)
self.timeLabel.setFont(timeFont)
self.timeLabel.move(20, 25)
self.clock_timer = QTimer()
self.clock_timer.timeout.connect(self.update_time)
self.clock_timer.start(1000)
# If show points is active, create label and initalise it.
if(self.info.show_points):
self.pointsLabel = QLabel(str(self.points), self)
pointsFont = QFont("Times", 15, QtGui.QFont.Bold)
self.pointsLabel.move(850,150)
self.pointsLabel.setFont(pointsFont)
# Maximize window and add auther tag.
self.initalize_tag()
self.showMaximized()
self.show()
# Create timer to call tracking function every 100ms.
self.timer = QTimer()
self.timer.timeout.connect(self.track)
self.timer.start(40)
self.startTime = time.time()
# Create timer for each action set in actions list.
for action in self.info.Actions:
t = Timer(float(action.time), self.call_action, [action])
t.start()
# Create timer to indicate end of trial.
t = Timer(float(self.info.trial_length), self.end_trial)
t.start()
def update_time(self):
if(self.trial_over):
return;
self.time_left = self.time_left-1
self.timeLabel.setText(str(self.time_left) + " seconds")
## If color time is active, set color depending on time relative to initial time.
if(self.info.color_time and self.time_left < int(self.info.trial_length)/2 and self.time_left > int(self.info.trial_length)/4):
self.timeLabel.setStyleSheet('color: orange')
elif(self.info.color_time and self.time_left < int(self.info.trial_length)/4):
self.timeLabel.setStyleSheet('color: red')
def end_trial(self):
self.trial_over = True
def closeEvent(self, event):
print ("Closing")
self.trial_over = True
self.timer.stop()
def call_action(self, action):
'''
Handles all action calling from actions list.
Returns if trial time is already over.
'''
if(self.trial_over):
print("Failed to call action. Trial already finished.")
return;
if(action.type == 0):
self.sensitivity = float(action.value)
if(action.type == 1):
self.x_one = xWidth = self.geometry().width()*float(action.value)/100
self.set_first_square(self.x_one, self.default_y, self.width_one, 80)
if(action.type == 2):
self.x_two = xWidth = self.geometry().width()*float(action.value)/100
self.set_second_square(self.x_two, self.default_y, self.width_two, 80)
if(action.type == 3):
self.width_one = float(action.value)
self.set_first_square(self.x_one, self.default_y, self.width_one, 80)
if(action.type == 4):
self.width_two = float(action.value)
self.set_second_square(self.x_two, self.default_y, self.width_two, 80)
if(action.type == 5):
self.flipSensitivity = float(action.value)
self.update_labels()
def close_call(self):
self.timer.stop()
self.close()
def set_first_square(self, x, y, w, h):
self.begin_one = QtCore.QPoint((x - w/2), (y - h/2))
self.end_one = QtCore.QPoint((x + w/2), (y + h/2))
def set_second_square(self, x, y, w, h):
self.begin_two = QtCore.QPoint((x - w/2), (y - h/2))
self.end_two = QtCore.QPoint((x + w/2), (y + h/2))
def update_labels(self):
if(self.info.show_points):
self.pointsLabel.setText(str(self.points))
def paintEvent(self, event):
'''
Draw rectangles. Two for goals, one for indicator.
'''
qp = QtGui.QPainter(self)
br = QtGui.QBrush(self.color_one)
qp.setBrush(br)
qp.drawRect(QtCore.QRect(self.begin_one, self.end_one))
br = QtGui.QBrush(self.color_two)
qp.setBrush(br)
qp.drawRect(QtCore.QRect(self.begin_two, self.end_two))
br = QtGui.QBrush(QtGui.QColor("black"))
qp.setBrush(br)
qp.drawRect(self.mouse_indicator-10, self.default_y , 20, 20)
def get_position(self):
'''
Get position dependant on wether the user is using a mouse or a joystick.
'''
if(self.type == "mouse"):
return self.mouse.position[0]
else:
pygame.event.pump()
#print(self.my_joystick.get_axis(0))
return (1+self.my_joystick.get_axis(0))*self.geometry().width()/2
def track(self):
'''
This is effectively the main loop of the 'game'.
This functions moves the mouse, handles color changes and other effects.
'''
self.curTime = time.time()
self.recorder.record_time(self.curTime-self.startTime)
# If trail is over, indicated by signal "trial_over" then end the trial. Begin saving process.
if(self.trial_over == True):
if(self.timer):
self.timer.stop()
QMessageBox.about(None, "Finish", "You finished with " + str(self.points) +" points.")
SaveFileWindow(self)
self.close_call()
# Get width of window.
xWidth = self.geometry().width()
# Get position of mouse or controler (x axis)
self.pos = self.get_position()
if(self.info.legacy_tracking):
self.mouse_indicator = ((self.pos - (xWidth/2))*self.sensitivity) + (xWidth/2)
else:
# Get difference between old position and new position
self.tick_difference = self.pos - self.mouse_position
# Set for next tracking.
self.mouse_position = self.pos
# Record position of input, before it is adjusted to sensitivity.
self.recorder.record_pos(self.pos)
# Adjust position by sensitivity settings.
if(self.flipSensitivity == 1):
self.mouse_indicator = self.mouse_indicator - self.tick_difference*self.sensitivity
else:
self.mouse_indicator = self.mouse_indicator + self.tick_difference*self.sensitivity
# Variables for non blocking mode.
not_in_square1 = False
not_in_square2 = False
# OLD # self.mouse_indicator = ((-self.pos + (xWidth/2))*self.sensitivity) + (xWidth/2)
# Recorder relative position of input. This is the position of the mouse indicator (hence after the application of sensitivity and flipping)
self.recorder.record_rel_pos(self.mouse_indicator)
# Check rect one
if(self.mouse_indicator < self.end_one.x() and self.mouse_indicator > self.begin_one.x()):
if(self.current_activated != 1):
## Pass case, gain a point.
self.color_one.setNamedColor(self.square_color_score)
self.color_two.setNamedColor(self.square_color_normal)
self.current_activated = 1
self.gain()
self.lose_block = 0
else:
not_in_square1 = True
if(self.mouse_indicator < self.begin_one.x() and self.lose_block != 1):
## Fail case, lose a point.
self.color_one.setNamedColor(self.square_color_fail)
self.lose()
self.lose_block = 1
# Check rect two
if(self.mouse_indicator < self.end_two.x() and self.mouse_indicator > self.begin_two.x()):
if(self.current_activated != 2):
## Pass case, gain a point.
self.color_two.setNamedColor(self.square_color_score)
self.color_one.setNamedColor(self.square_color_normal)
self.current_activated = 2
self.gain()
self.lose_block = 0
else:
not_in_square2 = True
if(self.mouse_indicator > self.end_two.x() and self.lose_block != 1):
## Fail case, lose a point.
self.color_two.setNamedColor(self.square_color_fail)
self.lose()
self.lose_block = 1
# If blocking is not active, then reset current square if between the two.
if(not_in_square1 and not_in_square2 and self.info.blocking == False and self.mouse_indicator > self.end_one.x() and self.mouse_indicator < self.begin_two.x()):
self.current_activated = 0
# Update the Ui.
self.update()
def gain(self):
if(self.info.add_points):
self.points = self.points+1
self.update_labels()
def lose(self):
if(self.info.remove_points):
self.points = self.points-1
if(self.points < 0):
self.points = 0
self.update_labels()
def initalize_tag(self):
titleLabel = QLabel("By Oliver Holder, \nRuud den Hartigh", self)
titleLabel.move(300,1300)
class Recorder():
def __init__(self):
self.mouseX = list()
self.relX = list()
self.realTime = list()
def record_pos(self, x):
self.mouseX.append(x)
def record_rel_pos(self, x):
self.relX.append(x)
def record_time(self, t):
self.realTime.append(t)
def get_real_time(self):
return self.realTime
def get_x_list(self):
return self.mouseX
def get_rel_x_list(self):
return self.relX
class SaveFileWindow(QMainWindow):
def __init__(self, parent=None):
super(SaveFileWindow, self).__init__(parent)
self.setWindowTitle("Save file as:")
self.parent = parent
self.layout = QGridLayout()
self.main_widget = QWidget()
self.setCentralWidget(self.main_widget)
self.main_widget.setLayout(self.layout)
self.file_name_label = QLabel(str(self.parent.info.filename))
self.layout.addWidget(self.file_name_label, 0, 0)
self.save_button = QPushButton("Save file")
self.save_button.clicked.connect(self.save_file)
self.layout.addWidget(self.save_button, 0, 1)
self.show()
def save_file(self):
'''
Attempts to save file with the name in the text box.
Saves both questions and form.
'''
file_name = self.parent.info.filename
# If there is no filename, then do nothing.
if (file_name == ""):
return
for name in listdir("saves/"):
if name == (self.parent.info.filename + ".txt") :
buttonReply = QMessageBox.question(self, 'Attempted Overwrite', "Are you sure you want to overwrite" + " [" + file_name + "]", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
if buttonReply == QMessageBox.No:
return
try:
f = open("saves/" + file_name + ".txt", "w+")
f.write(str(file_name) + " " + str(self.parent.points) + "//")
f.write(str(self.parent.info.trial_length) + "//")
f.write("Data (" + str(self.parent.points) + ") | Mouse x position | - " + json.dumps(self.parent.recorder.get_x_list()) + "//")
f.write("~")
f.close()
except:
print("Saving failed")
# Recur saving step, sometimes saving fails because the excel file to be overwritten is open. This recuring allows the user to clsoe excel.
save_file()
## From here it is saving the file in excel
import xlwt
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet("my sheet")
xPos = 0
yPos = 0
# Add in time stamps for data
tempList = self.parent.recorder.get_x_list()
realTimes = self.parent.recorder.get_real_time()
if(not len(self.parent.recorder.get_x_list()) == 0):
worksheet.write(0, 0, "Time (in ms)")
worksheet.write(0, 1, "X position")
worksheet.write(0, 2, "X position (normalized)")
time_index = 1
yPos = 1
for n in tempList:
worksheet.write(yPos, 0, str(int(1000*realTimes[yPos-1])))
worksheet.write(yPos, 1, str(n))
norm = (int)(100*(n/self.parent.geometry().width()))
worksheet.write(yPos, 2, str( norm/100))
yPos = yPos+1
tempList = self.parent.recorder.get_rel_x_list()
if(not len(self.parent.recorder.get_x_list()) == 0):
worksheet.write(0, 3, "Relative X position")
worksheet.write(0, 4, "Relative X position (normalized)")
time_index = 1
yPos = 1
for n in tempList:
worksheet.write(yPos, 3, str(n))
norm = (int)(100*(n/self.parent.geometry().width()))
worksheet.write(yPos, 4, str( norm/100))
yPos = yPos+1
worksheet.write(0, 5, "Points = " + str(self.parent.points))
## Trial options
trial_options_col = 6
worksheet.write(0, trial_options_col, "Length = " + str(self.parent.info.trial_length))
worksheet.write(1, trial_options_col, "Start points = " + str(self.parent.info.start_points))
if(self.parent.info.show_points):
worksheet.write(2,trial_options_col, "Show points: true")
else:
worksheet.write(2,trial_options_col, "Show points: false")
if(self.parent.info.add_points):
worksheet.write(3,trial_options_col, "Add points: true")
else:
worksheet.write(3,trial_options_col, "Add points: false")
if(self.parent.info.remove_points):
worksheet.write(4,trial_options_col, "Remove points: true")
else:
worksheet.write(4,trial_options_col, "Remove points: false")
if(self.parent.info.show_time):
worksheet.write(5,trial_options_col, "Show time: true")
else:
worksheet.write(5,trial_options_col, "Show time: false")
if(self.parent.info.color_time):
worksheet.write(6,trial_options_col, "Color time: true")
else:
worksheet.write(6,trial_options_col, "Color time: false")
if(self.parent.info.blocking):
worksheet.write(7,trial_options_col, "blocking: true")
else:
worksheet.write(7,trial_options_col, "blocking: false")
worksheet.write(8,trial_options_col, "Style: " + self.parent.info.style_list[self.parent.info.style])
worksheet.write(0, 7, "Actions [type, value, time(seconds)]")
yPos = 1
for n in self.parent.info.Actions:
worksheet.write(yPos, 7, "[" + str(self.parent.info.action_types[n.type]) + ", " + str(n.value) + ", " + str(n.time) + "]")
yPos = yPos+1
workbook.save("saves/" + self.parent.info.filename + ".xls")
self.close()
if __name__ == '__main__':
app = QApplication(sys.argv)
startWindow= StartWindow()
sys.exit(app.exec_())