#==================================================================== # Settings that we might want to tweak later on #==================================================================== # Directory to save data in (data) # Directory where imagesc an be found (image) # Image names (without the suffixes, like 1, 2, ...) # Suffix for the first image (a.jpg) # Suffix for the second image (b.jpg) # Screen size in pixels (1024x768) # Image freezing time (30s) # Image changing time (0.5s) # Number of bubbles overlayed on the image (40) #========================================== # Store info about the experiment session #========================================== # Get subject name, gender, age, handedness # Get date and time # Store this information for output # Create a unique filename for the experiment data #========================= # Prepare conditions lists #========================= # Make images list, in random order # - Find images and remember their names # - Randomize order of images # Make orientations list # - Half images upright, half inverted # - Randomize order of orientations #=============================== # Creation of window and stimuli #=============================== # Open window # Create the start message # Define stimuli (contents can still change) # Define bubbles (positions and sizes can still change) #========================= # Creation of TrialHandler #========================= # Define a list of trials with their properties: # - Which image # - Which orientation #===================== # Start the experiment #===================== # Display instructions # Run through the trials. On each trial: # - Wait for a spacebar to start a trial # - Read both image files, set their orientation # - Then switch the image every 0.5s, while: # - Repositioning and resizing bubbles each time # - Listening for a spacebar press # - Stop if spacebar has been pressed, or if 30s have passed # - Record response time # - Advance to the next trial # When all trials are done, write the data to a file and quit # Assign values to the three variable types # Here, we simply assign a literal my_int = 5 print my_int print type(my_int) my_float = 5.0 print my_float print type(my_float) my_boolean = False print my_boolean print type(my_boolean) first_number = 5 second_number = 5.0 ## Now we assign an expression to a variable ## Since an expression evaluates to a value, this is equivalent # Simple expression summed_numbers = first_number + second_number print summed_numbers, type(summed_numbers) # Re-assign a variable using an expression involving its own value first_number = first_number * 3 print first_number # A more complex expression result = ((first_number-3)*second_number)/1.3 print result a = 1 b = 2 if True: print a if False: print b a = 1 my_boolean = True if my_boolean: print a a = 1 # This expression evaluates to a boolean my_boolean = a > 0 print my_boolean # We can assign to a variable and use that if my_boolean: print a # Or we could use the full expression directly if a > 0: print a a = 1 b = 2 c = 3 if a > 0: print a elif b == 2: # Execute if b equals 2 # ...but ONLY if the first condition was False # Note the difference with the assignment symbol = print b elif c <= 3: # Execute if c is smaller than or equal to 3 # ...but ONLY if the first two conditions were False print c else: # Execute in any case # But ONLY if all others were False print 4 if b >= 0: # Execute if b is greater than or equal to 0 # A new if-statement, evaluated independent of previous conditions print b # This statement is not indented # ...and will therefore always execute print 5 a = 1 b = 2 c = 3 # We can logically combine booleans to create another boolean # using 'and', 'or' and 'not' my_boolean = a > 0 and b == 2 print my_boolean # Instead of assigning to a variable, again we can use # the full expression in the conditional statement if a > 0 and b == 2: print a, b elif b == 3 or c <= 3: print b, c elif not a < 0 and c == 3: print a, c # Instead of this: a = 1 print a a = a + 1 print a a = a + 1 print a a = a + 1 print a a = a + 1 print a # (copy-paste as many times as you need...) # We can write much shorter and far more flexibly: a = 1 maximum_number = 5 while a <= maximum_number: print a a = a + 1 a = 1 maximum_number = 5 while True: print a a = a + 1 if a > maximum_number: break # A string represents an ordered series of characters my_string = "a line of text" my_string = 'a line of text' print my_string print type(my_string) print len(my_string) # A tuple is an ordered series of values # ... but these values may consist of different data types my_tuple = (1, 2.0, False) print my_tuple print type(my_tuple) print len(my_tuple) # A list is similar (see below for the difference) # Note that tuples and lists may even have complex data types as elements my_list = [True, "a string!", (1,'tuple','in', 1, 'list')] print my_list print type(my_list) print len(my_list) # A dictionary connects values to one another # It is unordered; the order of elements does not matter # Again, all variable types may be used my_dictionary = {1:[1,1,1], 3:'three', False:2.0} print my_dictionary my_dictionary = {False:2.0, 1:[1,1,1], 3:'three'} print my_dictionary print type(my_dictionary) print len(my_dictionary) a = "kumbaya, milord" print a # Fetch and print the first element of a string print a[0] # Fetch the first until, but not including, the fifth element # This is called 'slicing' print a[0:4] # -1 is the index of the last element # -2 of the second-to-last, etc print a[-2] print a[-5:-1] print a[-5:] # Reverse the order or change step size # Syntax: [start:end:step] print a[-1:-10:-1] print a[0::3] # The same applies to the other ordered data types b = [1, 2.0, True] print b # In lists, you can change existing elements # Change the second element in a list b[1] = 'foo' print b # Print the elements in reverse print b[::-1] # '+' performs concatenation on strings, tuples and lists # Since we do not re-assign the result to a variable however # ...nothing changes in the original ordered series a = "kumbaya, milord" print a print a + '!!!' print a # Same goes for a tuple (or a list) b = (1, 2.0, True) print b print b + (5,) print b # By re-assigning, we do change the tuple b = b + (5,) print b # Retrieve the value corresponding to 1 in the dictionary # Note that this retrieval is one-way only # ...therefore the first values (the 'keys') need to be unique d = {1:'one', 2:'two', 3:'three'} print d[1] # Add a value to the dictionary d[4] = 'four' print d # String a = 'example' result = 'i' in a print result # Tuple b = (1,2,3) print 0 in b # List c = [1,2,3] print 5 in c # In case of a dictionary, this pertains only to the keys d = {1:'one', 2:'two', 3:'three'} print 2 in d print 'two' in d # Without the for-syntax, we could do it like this a = 'hi!' n = 0 while n < len(a): print a[n] n = n + 1 # With the for-syntax, this becomes much more intuitive a = 'hi!' for letter in a: print letter a = -1 if a < 0: raise Exception('Your dog cannot have a negative number of paws!') print 'My dog has', a, 'paw(s).' aseries = (0,2,3) a_series[0] = 1 my_string = 'Hi!' my_list = [] # We try to turn a string into a list # of individual characters n = 0 while True: my_list + [my_string[n]] n = n + 1 if n > len(my_string): break print my_list #==================================================================== # Settings that we might want to tweak later on #==================================================================== datapath = 'data' # directory to save data in impath = 'images' # directory where images can be found imlist = ['1','2','3','4','5','6'] # image names (without the suffixes) asfx = 'a.jpg' # suffix for the first image bsfx = 'b.jpg' # suffix for the second image scrsize = (1024,768) # screen size (pixels) timelimit = 30 # image freezes after this time (seconds) changetime = .5 # how often images are changing (seconds) n_bubbles = 40 # number of bubbles overlayed on the image #========================================== # Store info about the experiment session #========================================== # Show a dialog box to enter session information exp_name = 'Change Detection' exp_info = {} # Get subject name # Get date and time # Put both in the exp_info dictionary data_fname = exp_info['participant'] + '_' + exp_info['date'] #========================= # Prepare conditions lists #========================= # Make images list, in random order # - Find images and remember their names # - Randomize order of images # Make orientations list # - Half images upright, half inverted # - Randomize order of orientations #=============================== # Creation of window and stimuli #=============================== # Open window # Create the start message start_text = 'Press space to start the experiment' # Define stimuli (contents can still change) # Define bubbles (positions and sizes can still change) #========================= # Creation of TrialHandler #========================= # Define a list of trials with their properties: # - Which image # - Which orientation #===================== # Start the experiment #===================== # Display instructions # Run through the trials for trial in trials: # - Wait for a spacebar to start a trial # - Read both image files while no_response and time < timelimit: # - Switch the image every 0.5s # - Reposition and resize the bubbles # - Stop if spacebar has been pressed, or if 30s have passed # - Record response time # When all trials are done, write the data to a file and quit def print_something(): print "preparing to print" print "the function is printing" print "done printing" print_something() print_something() # Function definition def print_and_sum(a, b): print 'The first number is', a print 'The second number is', b return a + b # Assign function output to a variable c = print_and_sum(3,5) print 'Their sum is', c # Print function output directly print print_and_sum(10,20) def my_len(inp): x = 0 for el in inp: x = x + 1 return x a = [1, True, 'T'] print len(a) print my_len(a) def times_two(x): print x*2 def times_three(x): print x*3 import multiplications a = 5 multiplications.times_two(a) multiplications.times_three(a) import multiplications as mt mt.times_two(5) from multiplications import times_two times_two(5) a = [1,2,3] print a def append_element(old_list, new_element): return old_list + [new_element] a = append_element(a,4) print a # Do the same thing # ...using the append member function of the list object a = [1,2,3] a.append(4) print a # reverse() reverses the list a.reverse() print a # remove() removes its first encounter of the specified element a.remove(2) print a # sort() sorts the list from low to high a.sort() print a # pop() returns AND removes the last element print a.pop() print a print a print a.reverse() print a a = 'kumbaya, milord' # Split at spaces, and return a list of strings print a.split(' ') # To print the second word in a sentence, you could then do print a.split(' ')[1] # Check whether a string starts or ends with certain characters # Returns a boolean print a.startswith('kumba') print a.endswith('ard') # Remove the first/last part of a string # ...note that the original string is not changed # A new, different string is returned instead print a.lstrip('kumba') print a.rstrip('ord') print a # Replace part of a string # Again, a new string is returned print a.replace('lord', 'lard') # Here we assign the result to the original string variable # To the same effect as an in-place function a = a.replace('u','x') print a im_order = [5, 6, 3, 2, 1, 4] ori_order = [0, 1, 1, 0, 1, 0] trials_n = [1, 2, 3, 4, 5, 6] data_acc = [] data_rt = [] for trn in trials_n: current_image = im_order[trn-1] current_orientation = ori_order[trn-1] # Present the correct stimuli # ...then gather the responses as acc and rt # e.g., acc = 1 rt = 0.32 data_acc.append(acc) data_rt.append(rt) print data_acc print data_rt # Find some function that turns all these lists into a text file # Preferably easily loadable by your statistics program # import the TrialHandler from psychopy.data import TrialHandler # Define conditions values as a list of dicts stim_order = [{'im':5,'ori':0}, {'im':6,'ori':1}, {'im':3,'ori':1}, {'im':2,'ori':0}, {'im':1,'ori':1}, {'im':4,'ori':0}] # Construct the TrialHandler object # nReps = number of repeats # method = randomization method (here: no randomization) trials = TrialHandler(stim_order, nReps=1, method='sequential') # Loop over the trials for trial in trials: print trial['im'], trial['ori'] # Present the correct stimuli # ...then gather the responses as acc and rt # e.g., acc = 1 rt = 0.32 trials.addData('acc',acc) trials.addData('rt',rt) # And save everything to a file trials.saveAsWideText('test.csv', delim=',') #=============== # Import modules #=============== from psychopy import data #==================================================================== # Settings that we might want to tweak later on #==================================================================== datapath = 'data' # directory to save data in impath = 'images' # directory where images can be found imlist = ['1','2','3','4','5','6'] # image names (without the suffixes) asfx = 'a.jpg' # suffix for the first image bsfx = 'b.jpg' # suffix for the second image scrsize = (1024,768) # screen size (pixels) timelimit = 30 # image freezes after this time (seconds) changetime = .5 # how often images are changing (seconds) n_bubbles = 40 # number of bubbles overlayed on the image #========================================== # Store info about the experiment session #========================================== # Show a dialog box to enter session information exp_name = 'Change Detection' exp_info = {} # Get subject name # Get date and time # Put both in the exp_info dictionary data_fname = exp_info['participant'] + '_' + exp_info['date'] #========================= # Prepare conditions lists #========================= # Make images list, in random order # - Find images and remember their names # - Randomize order of images # Make orientations list # - Half images upright, half inverted # - Randomize order of orientations #=============================== # Creation of window and stimuli #=============================== # Open window # Create the start message start_text = 'Press space to start the experiment' # Define stimuli (contents can still change) # Define bubbles (positions and sizes can still change) #========================= # Creation of TrialHandler #========================= # Create a list of dictionaries stim_order = [{},{},{},{},{},{}] # Fill this in using im_order and ori_order # We can do this already, but we'll learn a shorter way trials = data.TrialHandler(stim_order, nReps=1, extraInfo=exp_info, originPath=datapath) #===================== # Start the experiment #===================== # Display the start message # Run through the trials for trial in trials: # - Wait for a spacebar to start a trial # - Read both image files, using: trial['image'] trial['ori'] while no_response and time < timelimit: # - Switch the image every 0.5s # - Reposition and resize the bubbles # - Stop if spacebar has been pressed, or if 30s have passed # Add the current trial's data to the TrialHandler trials.addData('rt', rt) trials.addData('acc', acc) #====================== # End of the experiment #====================== # Save all data to a file trials.saveAsWideText(data_fname + '.csv', delim=',') # Quit the experiment # zip() takes two ordered series of equal length # ...and creates a list of tuple pairs from their elements print zip('haha', 'hihi') print zip([1,2,4],[4,5,6]) # range() creates a sequence of integers # ...by default, starting from 0 and not including the specified integer print range(10) # The (included) starting value can however be specified print range(1,10) # As can the step size print range(1,10,2) import os my_file = 'multiplications' my_ext = '.py' # Get the current working directory # Returns a string my_dir = os.getcwd() print my_dir # Check whether a directory exists # Returns a boolean print os.path.isdir(my_dir) # Summarize the files in a directory # Returns a list of strings print os.listdir(my_dir) # Creates a directory if not os.path.isdir('temp'): os.makedirs('temp') # Joins together different parts of a file path # Returns a string my_full_path = os.path.join(my_dir, my_file+my_ext) print my_full_path # Check whether a file exists # Returns a boolean print os.path.exists(my_full_path) import numpy.random as rnd a = [1, 2, 3, 4, 5] print a # Shuffle the order of a rnd.shuffle(a) print a # Generate 5 random floats between 0 and 1 b = rnd.random(5) print b # Generate 5 integers up to but not including 10 # Also notice how we specify the 'size' argument here # It is an OPTIONAL argument; specified by name rather than order c = rnd.randint(10, size=5) print c #=============== # Import modules #=============== import os # for file/folder operations import numpy.random as rnd # for random number generators from psychopy import data #==================================================================== # Settings that we might want to tweak later on #==================================================================== datapath = 'data' # directory to save data in impath = 'images' # directory where images can be found imlist = ['1','2','3','4','5','6'] # image names (without the suffixes) asfx = 'a.jpg' # suffix for the first image bsfx = 'b.jpg' # suffix for the second image scrsize = (1024,768) # screen size (pixels) timelimit = 30 # image freezes after this time (seconds) changetime = .5 # how often images are changing (seconds) n_bubbles = 40 # number of bubbles overlayed on the image #========================================== # Store info about the experiment session #========================================== # Show a dialog box to enter session information exp_name = 'Change Detection' exp_info = {} # Get subject name # Get date and time # Put both in the exp_info dictionary # Set up filename for saving data if not os.path.isdir(datapath): os.makedirs(datapath) data_fname = exp_info['participant'] + '_' + exp_info['date'] data_fname = os.path.join(datapath, data_fname) #========================= # Prepare conditions lists #========================= # Check if all images exist for im in imlist: if (not os.path.exists(os.path.join(impath, im+asfx)) or not os.path.exists(os.path.join(impath, im+bsfx))): raise Exception('Image files not found in image folder: ' + str(im)) # Randomize the image order rnd.shuffle(imlist) # Make the orientations list, in random order # Half upright (0), half inverted (1) orilist = [0,1]*(len(imlist)/2) rnd.shuffle(orilist) #=============================== # Creation of window and stimuli #=============================== # Open window # Create the start message start_text = 'Press space to start the experiment' # Define stimuli (contents can still change) # Define bubbles (positions and sizes can still change) #========================= # Creation of TrialHandler #========================= stim_order = [] for im, ori in zip(imlist, orilist): stim_order.append({'im': im, 'ori': ori}) trials = data.TrialHandler(stim_order, nReps=1, extraInfo=exp_info, method='sequential', originPath=datapath) #===================== # Start the experiment #===================== # Display the start message # Run through the trials for trial in trials: # - Wait for a spacebar to start a trial # - Read both image files, using: im_fname = os.path.join(impath, trial['image']) trial['ori'] while no_response and time < timelimit: # - Switch the image every 0.5s # - Reposition and resize the bubbles # - Stop if spacebar has been pressed, or if 30s have passed # Add the current trial's data to the TrialHandler trials.addData('rt', rt) trials.addData('acc', acc) # Save data to a file, and quit the experiment trials.saveAsWideText(data_fname + '.csv', delim=',') core.quit() from psychopy import gui exp_name = 'Change detection' exp_info = {'participant': ''} gui.DlgFromDict(dictionary=exp_info, title=exp_name) print exp_info from psychopy import gui exp_name = 'Change detection' exp_info = {'participant': ''} dlg = gui.DlgFromDict(dictionary=exp_info, title=exp_name) if dlg.OK == False: core.quit() # user pressed cancel, so we quit exp_info['exp_name'] = exp_name from psychopy import data exp_info['date'] = data.getDateStr() from psychopy import visual visual.Window() # don't run this line from psychopy import visual, core win = visual.Window() core.wait(3) # seconds win.close() win = visual.Window(size=(1024,768), color='white') core.wait(3) win.close() win = visual.Window(fullscr=True) core.wait(3) win.close() from psychopy import visual, core win = visual.Window(size=(1024,768), color='white', units='pix') bitmap = visual.SimpleImageStim(win, 'images/1a.jpg') core.wait(3) win.close() win = visual.Window(size=(1024,768), color='white', units='pix') bitmap = visual.SimpleImageStim(win, 'images/1a.jpg') bitmap.draw() core.wait(3) win.close() win = visual.Window(size=(1024,768), color='white', units='pix') bitmap = visual.SimpleImageStim(win, 'images/1a.jpg') bitmap.draw() # draw bitmap on the window win.flip() # make bitmap visible core.wait(3) win.close() win = visual.Window(size=(1024,768), color='white', units='pix') bubble = visual.Circle(win, fillColor='black', lineColor='black', radius=30) bubble.draw() win.flip() core.wait(3) # seconds win.close() win = visual.Window(size=(1024,768), color='white', units='pix') text = visual.TextStim(win, text='Press space to start the experiment', color='red', height=100) text.draw() win.flip() core.wait(3) # seconds win.close() from psychopy import visual, core, event win = visual.Window(size=(1024,768), color='white', units='pix') text = visual.TextStim(win, text='Press space to start the experiment', color='red', height=100) text.draw() win.flip() keypress = event.waitKeys(keyList=['space', 'escape']) print keypress if keypress[0] == 'escape': win.close() else: print 'Start of experiment' win.close() from psychopy import visual, core win = visual.Window(size=(1024,768), color='white', units='pix') bitmap = visual.SimpleImageStim(win, 'images/1a.jpg') bitmap.draw() # draw bitmap on the window win.flip() # make bitmap visible core.wait(3) bitmap.setImage('images/1b.jpg') bitmap.draw() win.flip() core.wait(3) win.close() from psychopy import visual, core win = visual.Window(size=(1024,768), color='white', units='pix') bitmap = visual.SimpleImageStim(win, 'images/1a.jpg') for i in range(5): bitmap.setImage('images/1a.jpg') bitmap.draw() # draw bitmap on the window win.flip() # make bitmap visible core.wait(.5) bitmap.setImage('images/1b.jpg') bitmap.draw() win.flip() core.wait(.5) win.close() from psychopy import visual, core win = visual.Window(size=(1024,768), color='white', units='pix') bitmap = visual.SimpleImageStim(win, 'images/1a.jpg') for i in range(10): # note that we now need 6, not 3 iterations # change the bitmap if bitmap.image == 'images/1a.jpg': bitmap.setImage('images/1b.jpg') else: bitmap.setImage('images/1a.jpg') bitmap.draw() win.flip() core.wait(.5) win.close() from psychopy import visual, core, event win = visual.Window(size=(1024,768), color='white', units='pix') bitmap = visual.SimpleImageStim(win, 'images/1a.jpg') # Initialize clock to register response time rt_clock = core.Clock() rt_clock.reset() # start rt clock done = False # Start the trial keys = None while keys is None and rt_clock.getTime() < 30: # Change the bitmap if bitmap.image == 'images/1a.jpg': bitmap.setImage('images/1b.jpg') else: bitmap.setImage('images/1a.jpg') bitmap.draw() # Show the new screen we've drawn win.flip() # For 500 ms, do nothing except wait for the participant's response keys = event.waitKeys(maxWait=.5, keyList=['space', 'escape'], timeStamped=rt_clock) print keys win.close() change_clock = core.Clock() keys = [] # this list will fill up once a participant responds while len(keys) == 0 and rt_clock.getTime() < 30: ... # For 500 ms, do nothing except wait for the participant's response change_clock.reset() while change_clock.getTime() < .5: # Register spacebar or escape press keys = event.getKeys(keyList=['space', 'escape']) if len(keys) > 0: break # Draw bubbles at new random positions for radius in range(40): bubble.setRadius(radius) bubble.setPos(((rnd.random()-.5) * scrsize[0], (rnd.random()-.5) * scrsize[1] )) bubble.draw() # Check if participant responded if len(keys) > 0: # Was it an escape button? if 'escape' in keys: core.quit() else: # Take only the last key press last_key = keys[-1] rt = keys[-1][1] acc = keys[-1][0] else: rt = timelimit acc = 0 # no response is an incorrect response # Display the start message start_message.draw() win.flip() # Start the main loop that goes through all trials for trial in trials: # Wait for spacebar press to start (or escape to quit) keys = event.waitKeys(keyList=['space', 'escape']) if 'escape' in keys: core.quit() # Fetch the image path (minus the suffix) im_fname = os.path.join(impath, trial['im']) # Flip image upside down if necessary bitmap.setFlipHoriz(trial['ori']) # Show stimuli, collect responses # ... #=============== # Import modules #=============== import os # for file/folder operations import numpy.random as rnd # for random number generators from psychopy import visual, event, core, gui, data #============================================== # Settings that we might want to tweak later on #============================================== datapath = 'data' # directory to save data in impath = 'images' # directory where images can be found imlist = ['1','2','3','4','5','6'] # image names (without the suffixes) asfx = 'a.jpg' # suffix for the first image bsfx = 'b.jpg' # suffix for the second image scrsize = (1024,768) # screen size (pixels) timelimit = 30 # image freezes after this time (seconds) changetime = .5 # how often images are changing (seconds) n_bubbles = 40 # number of bubbles overlayed on the image #======================================== # Store info about the experiment session #======================================== # Show a dialog box to enter session information exp_name = 'Change Detection' exp_info = { 'participant': '', 'gender': ('male', 'female'), 'age':'', 'left-handed':False } dlg = gui.DlgFromDict(dictionary=exp_info, title=exp_name) # If 'Cancel' is pressed, quit if dlg.OK == False: core.quit() # Add the date and the experiment name exp_info['date'] = data.getDateStr() exp_info['exp_name'] = exp_name # Set up filename for saving data if not os.path.isdir(datapath): os.makedirs(datapath) data_fname = exp_info['participant'] + '_' + exp_info['date'] data_fname = os.path.join(datapath, data_fname) #========================= # Prepare conditions lists #========================= # Check if all images exist for im in imlist: if (not os.path.exists(os.path.join(impath, im+asfx)) or not os.path.exists(os.path.join(impath, im+bsfx))): raise Exception('Image files not found in image folder: ' + str(im)) # Randomize the image order rnd.shuffle(imlist) # Make the orientations list, in random order # Half upright (0), half inverted (1) orilist = [0,1]*(len(imlist)/2) rnd.shuffle(orilist) #=============================== # Creation of window and stimuli #=============================== # Open a window win = visual.Window(size=scrsize, color='white', units='pix', fullscr=False) # Create the start message start_message = visual.TextStim(win, text="Press space to start the experiment", color='red', height=20) # Create the bitmap object; its contents can still change bitmap = visual.SimpleImageStim(win, image=os.path.join(impath, imlist[0]+asfx)) # Create the bubble object bubble = visual.Circle(win, fillColor='black', lineColor='black') #========================= # Creation of TrialHandler #========================= stim_order = [] for im, ori in zip(imlist, orilist): stim_order.append({'im': im, 'ori': ori}) trials = data.TrialHandler(stim_order, nReps=1, extraInfo=exp_info, method='sequential', originPath=datapath) #===================== # Start the experiment #===================== # Display the start message start_message.draw() win.flip() # Initialize two clocks: # - for image change time # - for response time change_clock = core.Clock() rt_clock = core.Clock() # Start the main loop that goes through all trials for trial in trials: # Wait for spacebar press to start (or escape to quit) keys = event.waitKeys(keyList=['space', 'escape']) if 'escape' in keys: core.quit() # Fetch the image path (minus the suffix) im_fname = os.path.join(impath, trial['im']) # Flip image upside down if necessary bitmap.setFlipHoriz(trial['ori']) # Set the reaction time clock to 0 rt_clock.reset() # Start the trial keys = [] # this list will fill up once a participant responds while len(keys) == 0 and rt_clock.getTime() < timelimit: # Change the bitmap if bitmap.image == im_fname + asfx: bitmap.setImage(im_fname + bsfx) else: bitmap.setImage(im_fname + asfx) bitmap.draw() # Draw bubbles at new random positions for radius in range(n_bubbles): bubble.setRadius(radius) bubble.setPos(((rnd.random()-.5) * scrsize[0], (rnd.random()-.5) * scrsize[1] )) bubble.draw() # Show the new screen we've drawn win.flip() # For 500 ms, do nothing except wait for the participant's response change_clock.reset() while change_clock.getTime() <= changetime: # Register spacebar or escape press keys = event.getKeys(keyList=['space','escape']) if len(keys) > 0: break # Check if participant responded if len(keys) > 0: # Was it an escape button? if 'escape' in keys: core.quit() else: # Take only the last key press last_key = keys[-1] rt = keys[-1][1] acc = keys[-1][0] else: rt = timelimit acc = 0 # no response is an incorrect response # Add the current trial's data to the TrialHandler trials.addData('rt', rt) trials.addData('acc', acc) #====================== # End of the experiment #====================== # Save all data to a file trials.saveAsWideText(data_fname + '.csv', delim=',') # Quit the experiment core.quit()