﻿#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This experiment was created using PsychoPy3 Experiment Builder (v2020.1.3),
    on October 22, 2021, at 19:23
If you publish work using this script the most relevant publication is:

    Peirce J, Gray JR, Simpson S, MacAskill M, Höchenberger R, Sogo H, Kastman E, Lindeløv JK. (2019) 
        PsychoPy2: Experiments in behavior made easy Behav Res 51: 195. 
        https://doi.org/10.3758/s13428-018-01193-y

"""

from __future__ import absolute_import, division

from psychopy import locale_setup
from psychopy import prefs
prefs.hardware['audioLib'] = 'ptb'
from psychopy import sound, gui, visual, core, data, event, logging, clock
from psychopy.constants import (NOT_STARTED, STARTED, PLAYING, PAUSED,
                                STOPPED, FINISHED, PRESSED, RELEASED, FOREVER)

import numpy as np  # whole numpy lib is available, prepend 'np.'
from numpy import (sin, cos, tan, log, log10, pi, average,
                   sqrt, std, deg2rad, rad2deg, linspace, asarray)
from numpy.random import random, randint, normal, shuffle
import os  # handy system and path functions
import sys  # to get file system encoding

from psychopy.hardware import keyboard



# Ensure that relative paths start from the same directory as this script
_thisDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(_thisDir)

# Store info about the experiment session
psychopyVersion = '2020.1.3'
expName = 'Task_1L'  # from the Builder filename that created this script
expInfo = {'participant': '', 'age': '', 'gender': ['m', 'f'], 'Eye Tracker': ''}
dlg = gui.DlgFromDict(dictionary=expInfo, sortKeys=False, title=expName)
if dlg.OK == False:
    core.quit()  # user pressed cancel
expInfo['date'] = data.getDateStr()  # add a simple timestamp
expInfo['expName'] = expName
expInfo['psychopyVersion'] = psychopyVersion

# Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc
filename = _thisDir + os.sep + u'data/%s_%s_%s' % (expInfo['participant'], expName, expInfo['date'])

# An ExperimentHandler isn't essential but helps with data saving
thisExp = data.ExperimentHandler(name=expName, version='',
    extraInfo=expInfo, runtimeInfo=None,
    originPath='C:\\Users\\presi\\Desktop\\PhD\\Children experiment\\Tasks\\Task1\\Task_1L_lastrun.py',
    savePickle=True, saveWideText=True,
    dataFileName=filename)
# save a log file for detail verbose info
logFile = logging.LogFile(filename+'.log', level=logging.EXP)
logging.console.setLevel(logging.WARNING)  # this outputs to the screen, not a file

endExpNow = False  # flag for 'escape' or other condition => quit the exp
frameTolerance = 0.001  # how close to onset before 'same' frame

# Start Code - component code to be run before the window creation

# Setup the Window
win = visual.Window(
    size=[1920, 1080], fullscr=True, screen=0, 
    winType='pyglet', allowGUI=True, allowStencil=False,
    monitor='PHILIPS', color=[0.506,0.506,0.506], colorSpace='rgb',
    blendMode='avg', useFBO=True, 
    units='pix')
# store frame rate of monitor if we can measure it
expInfo['frameRate'] = win.getActualFrameRate()
if expInfo['frameRate'] != None:
    frameDur = 1.0 / round(expInfo['frameRate'])
else:
    frameDur = 1.0 / 60.0  # could not measure, so guess

# create a default keyboard (e.g. to check for escape)
defaultKeyboard = keyboard.Keyboard()

# Initialize components for Routine "Welcome_screen"
Welcome_screenClock = core.Clock()
instructions = visual.ImageStim(
    win=win,
    name='instructions', 
    image='Stimuli/instruct.png', mask=None,
    ori=0, pos=(0, 0), size=(900, 980),
    color=[1,1,1], colorSpace='rgb', opacity=1,
    flipHoriz=False, flipVert=False,
    texRes=128, interpolate=True, depth=0.0)
next = visual.ImageStim(
    win=win,
    name='next', 
    image='Stimuli/next1.png', mask=None,
    ori=0, pos=(880, -490), size=(140, 80),
    color=[1,1,1], colorSpace='rgb', opacity=1,
    flipHoriz=False, flipVert=False,
    texRes=128, interpolate=True, depth=-1.0)
#Assign different condition file based on participant number:
if int(expInfo['participant'])%2==0:
    condition='LearningB.xlsx'
else:
    condition='LearningA.xlsx'

#Fixation boundary in pixels
fixation_boundary=60

eyetracker=False
participant=expInfo['participant']
date=expInfo['date']

#Establish connection with Gazepoint EyeTracker:
if expInfo['Eye Tracker']:
    try:
        from opengaze import GazePointTracker
        import os.path
        import time
        
        # Construct the path to the log file.
        save_path=r'C:\Users\presi\Desktop\PhD\Children experiment\Tasks\Task1\ET_Data'
        file_name = os.path.join(save_path, f'L_{participant}_{date}.tsv')
        
        # Open the connection to the tracker.
        eyetracker = GazePointTracker(logfile=file_name, debug=False)
        time.sleep(1.0)
    except Exception as e:
       print("!! Error starting Gazepoint: ",e," Exiting...")
       core.quit()
       
    display_gaze=False
    x,y=0,0



# Initialize components for Routine "calibrate"
calibrateClock = core.Clock()
text_2 = visual.TextStim(win=win, name='text_2',
    text='Περιμέντε όσο η κάμερα μπαίνει σε λειτουργία...',
    font='Arila',
    pos=(0, 0), height=40, wrapWidth=1000, ori=0, 
    color='Black', colorSpace='rgb', opacity=1, 
    languageStyle='LTR',
    depth=-1.0);

# Initialize components for Routine "start_recording"
start_recordingClock = core.Clock()
text = visual.TextStim(win=win, name='text',
    text='Οι δοκιμές ξεκινάνε σύντομα...',
    font='Arial',
    pos=(0, 0), height=40, wrapWidth=1000, ori=0, 
    color='black', colorSpace='rgb', opacity=1, 
    languageStyle='LTR',
    depth=0.0);

# Initialize components for Routine "fixation"
fixationClock = core.Clock()
fix_cross = visual.ShapeStim(
    win=win, name='fix_cross', vertices='cross',
    size=(30, 30),
    ori=0, pos=(0, 0),
    lineWidth=2, lineColor=[-1.000,-1.000,-1.000], lineColorSpace='rgb',
    fillColor=[-1.000,-1.000,-1.000], fillColorSpace='rgb',
    opacity=1, depth=0.0, interpolate=True)

# Initialize components for Routine "Practise_trials"
Practise_trialsClock = core.Clock()
mouse = event.Mouse(win=win)
x, y = [None, None]
mouse.mouseClock = core.Clock()
background = visual.ImageStim(
    win=win,
    name='background', 
    image='sin', mask=None,
    ori=0, pos=(0, 0), size=(1920, 1080),
    color=[1,1,1], colorSpace='rgb', opacity=1,
    flipHoriz=False, flipVert=False,
    texRes=128, interpolate=True, depth=-1.0)
star = visual.ImageStim(
    win=win,
    name='star', 
    image='Stimuli/20x20t.png', mask=None,
    ori=0, pos=[0,0], size=None,
    color=[1,1,1], colorSpace='rgb', opacity=1,
    flipHoriz=False, flipVert=False,
    texRes=128, interpolate=True, depth=-2.0)
gaze_cursor = visual.GratingStim(
    win=win, name='gaze_cursor',
    tex='sin', mask=None,
    ori=0, pos=[0,0], size=1.0, sf=None, phase=0.0,
    color=[1.000,1.000,-1.000], colorSpace='rgb', opacity=1.0,blendmode='avg',
    texRes=128, interpolate=True, depth=-3.0)

# Initialize components for Routine "Practise_feedback"
Practise_feedbackClock = core.Clock()



sound_1 = sound.Sound('A', secs=0.7, stereo=True, hamming=False,
    name='sound_1')
sound_1.setVolume(1)

# Initialize components for Routine "Start"
StartClock = core.Clock()
worldmap = visual.ImageStim(
    win=win,
    name='worldmap', 
    image='Stimuli/fullmap.png', mask=None,
    ori=0, pos=(0, 0), size=(1920, 1080),
    color=[1,1,1], colorSpace='rgb', opacity=1,
    flipHoriz=False, flipVert=False,
    texRes=128, interpolate=True, depth=0.0)
plot2 = visual.ImageStim(
    win=win,
    name='plot2', 
    image='Stimuli/start.png', mask=None,
    ori=0, pos=(0, 0), size=(1180, 670),
    color=[1,1,1], colorSpace='rgb', opacity=1,
    flipHoriz=False, flipVert=False,
    texRes=128, interpolate=True, depth=-1.0)
next2 = visual.ImageStim(
    win=win,
    name='next2', 
    image='Stimuli/next1.png', mask=None,
    ori=0, pos=(880, -490), size=(140, 80),
    color=[1,1,1], colorSpace='rgb', opacity=1,
    flipHoriz=False, flipVert=False,
    texRes=128, interpolate=True, depth=-2.0)

# Initialize components for Routine "fixation"
fixationClock = core.Clock()
fix_cross = visual.ShapeStim(
    win=win, name='fix_cross', vertices='cross',
    size=(30, 30),
    ori=0, pos=(0, 0),
    lineWidth=2, lineColor=[-1.000,-1.000,-1.000], lineColorSpace='rgb',
    fillColor=[-1.000,-1.000,-1.000], fillColorSpace='rgb',
    opacity=1, depth=0.0, interpolate=True)

# Initialize components for Routine "Learning_trials"
Learning_trialsClock = core.Clock()
mouse2 = event.Mouse(win=win)
x, y = [None, None]
mouse2.mouseClock = core.Clock()
background2 = visual.ImageStim(
    win=win,
    name='background2', 
    image='sin', mask=None,
    ori=0, pos=(0, 0), size=(1920, 1080),
    color=[1,1,1], colorSpace='rgb', opacity=1,
    flipHoriz=False, flipVert=False,
    texRes=128, interpolate=True, depth=-1.0)
Star = visual.ImageStim(
    win=win,
    name='Star', 
    image='sin', mask=None,
    ori=0, pos=[0,0], size=None,
    color=[1,1,1], colorSpace='rgb', opacity=1,
    flipHoriz=False, flipVert=False,
    texRes=128, interpolate=True, depth=-2.0)
gaze_Cursor = visual.GratingStim(
    win=win, name='gaze_Cursor',
    tex='sin', mask=None,
    ori=0, pos=[0,0], size=(20, 20), sf=None, phase=0.0,
    color=[-1.000,1.000,-1.000], colorSpace='rgb', opacity=1.0,blendmode='avg',
    texRes=128, interpolate=True, depth=-3.0)

# Initialize components for Routine "Learning_feedback"
Learning_feedbackClock = core.Clock()
my_trial=0
Acc_blocks=0
Acc_trials=0
sound_2 = sound.Sound('A', secs=0.7, stereo=True, hamming=False,
    name='sound_2')
sound_2.setVolume(1)

# Initialize components for Routine "Trial_Break"
Trial_BreakClock = core.Clock()
msg_3=""

break_text = visual.TextStim(win=win, name='break_text',
    text='default text',
    font='Calibri',
    pos=(65, 30), height=60, wrapWidth=1000, ori=0, 
    color=[0.192,-0.216,-0.702], colorSpace='rgb', opacity=1, 
    languageStyle='LTR',
    depth=-1.0);
next3 = visual.ImageStim(
    win=win,
    name='next3', 
    image='Stimuli/next.png', mask=None,
    ori=0, pos=(880, -490), size=(150, 90),
    color=[1,1,1], colorSpace='rgb', opacity=1,
    flipHoriz=False, flipVert=False,
    texRes=128, interpolate=True, depth=-2.0)

# Initialize components for Routine "Block_Break"
Block_BreakClock = core.Clock()
msg_4=""
map=None
block_break_text = visual.TextStim(win=win, name='block_break_text',
    text='default text',
    font='Calibri',
    pos=(105, -45), height=80, wrapWidth=1350, ori=0, 
    color=[0.192,-0.216,-0.702], colorSpace='rgb', opacity=1, 
    languageStyle='LTR',
    depth=-1.0);
next_5 = visual.ImageStim(
    win=win,
    name='next_5', 
    image='Stimuli/next.png', mask=None,
    ori=0, pos=(880,-490), size=(150, 90),
    color=[1,1,1], colorSpace='rgb', opacity=1,
    flipHoriz=False, flipVert=False,
    texRes=128, interpolate=True, depth=-2.0)

# Initialize components for Routine "gap"
gapClock = core.Clock()

# Initialize components for Routine "End"
EndClock = core.Clock()
cloud = visual.ImageStim(
    win=win,
    name='cloud', 
    image='Stimuli/kamecloud.png', mask=None,
    ori=0, pos=(0, 0), size=(1920, 1080),
    color=[1,1,1], colorSpace='rgb', opacity=1,
    flipHoriz=False, flipVert=False,
    texRes=128, interpolate=True, depth=0.0)
family = visual.ImageStim(
    win=win,
    name='family', 
    image='Stimuli/kamehouse.jpg', mask=None,
    ori=0, pos=(0, 0), size=(1920, 1080),
    color=[1,1,1], colorSpace='rgb', opacity=1,
    flipHoriz=False, flipVert=False,
    texRes=128, interpolate=True, depth=-1.0)

# Create some handy timers
globalClock = core.Clock()  # to track the time since experiment started
routineTimer = core.CountdownTimer()  # to track time remaining of each (non-slip) routine 

# ------Prepare to start Routine "Welcome_screen"-------
continueRoutine = True
# update component parameters for each repeat
# keep track of which components have finished
Welcome_screenComponents = [instructions, next]
for thisComponent in Welcome_screenComponents:
    thisComponent.tStart = None
    thisComponent.tStop = None
    thisComponent.tStartRefresh = None
    thisComponent.tStopRefresh = None
    if hasattr(thisComponent, 'status'):
        thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
Welcome_screenClock.reset(-_timeToFirstFrame)  # t0 is time of first possible flip
frameN = -1

# -------Run Routine "Welcome_screen"-------
while continueRoutine:
    # get current time
    t = Welcome_screenClock.getTime()
    tThisFlip = win.getFutureFlipTime(clock=Welcome_screenClock)
    tThisFlipGlobal = win.getFutureFlipTime(clock=None)
    frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
    # update/draw components on each frame
    
    # *instructions* updates
    if instructions.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
        # keep track of start time/frame for later
        instructions.frameNStart = frameN  # exact frame index
        instructions.tStart = t  # local t and not account for scr refresh
        instructions.tStartRefresh = tThisFlipGlobal  # on global time
        win.timeOnFlip(instructions, 'tStartRefresh')  # time at next scr refresh
        instructions.setAutoDraw(True)
    
    # *next* updates
    if next.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
        # keep track of start time/frame for later
        next.frameNStart = frameN  # exact frame index
        next.tStart = t  # local t and not account for scr refresh
        next.tStartRefresh = tThisFlipGlobal  # on global time
        win.timeOnFlip(next, 'tStartRefresh')  # time at next scr refresh
        next.setAutoDraw(True)
    if mouse.isPressedIn(next, buttons=[0]):
        continueRoutine=False
    
    # check for quit (typically the Esc key)
    if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
        core.quit()
    
    # check if all components have finished
    if not continueRoutine:  # a component has requested a forced-end of Routine
        break
    continueRoutine = False  # will revert to True if at least one component still running
    for thisComponent in Welcome_screenComponents:
        if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
            continueRoutine = True
            break  # at least one component has not yet finished
    
    # refresh the screen
    if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
        win.flip()

# -------Ending Routine "Welcome_screen"-------
for thisComponent in Welcome_screenComponents:
    if hasattr(thisComponent, "setAutoDraw"):
        thisComponent.setAutoDraw(False)
# the Routine "Welcome_screen" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()

# set up handler to look after randomisation of conditions etc
calibration_loop = data.TrialHandler(nReps=0, method='sequential', 
    extraInfo=expInfo, originPath=-1,
    trialList=[None],
    seed=None, name='calibration_loop')
thisExp.addLoop(calibration_loop)  # add the loop to the experiment
thisCalibration_loop = calibration_loop.trialList[0]  # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb = thisCalibration_loop.rgb)
if thisCalibration_loop != None:
    for paramName in thisCalibration_loop:
        exec('{} = thisCalibration_loop[paramName]'.format(paramName))

for thisCalibration_loop in calibration_loop:
    currentLoop = calibration_loop
    # abbreviate parameter names if possible (e.g. rgb = thisCalibration_loop.rgb)
    if thisCalibration_loop != None:
        for paramName in thisCalibration_loop:
            exec('{} = thisCalibration_loop[paramName]'.format(paramName))
    
    # ------Prepare to start Routine "calibrate"-------
    continueRoutine = True
    routineTimer.add(35.000000)
    # update component parameters for each repeat
    win.winHandle.minimize()
    win.winHandle.set_fullscreen(False)
    #win.flip()
    # keep track of which components have finished
    calibrateComponents = [text_2]
    for thisComponent in calibrateComponents:
        thisComponent.tStart = None
        thisComponent.tStop = None
        thisComponent.tStartRefresh = None
        thisComponent.tStopRefresh = None
        if hasattr(thisComponent, 'status'):
            thisComponent.status = NOT_STARTED
    # reset timers
    t = 0
    _timeToFirstFrame = win.getFutureFlipTime(clock="now")
    calibrateClock.reset(-_timeToFirstFrame)  # t0 is time of first possible flip
    frameN = -1
    
    # -------Run Routine "calibrate"-------
    while continueRoutine and routineTimer.getTime() > 0:
        # get current time
        t = calibrateClock.getTime()
        tThisFlip = win.getFutureFlipTime(clock=calibrateClock)
        tThisFlipGlobal = win.getFutureFlipTime(clock=None)
        frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
        # update/draw components on each frame
        
        # *text_2* updates
        if text_2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
            # keep track of start time/frame for later
            text_2.frameNStart = frameN  # exact frame index
            text_2.tStart = t  # local t and not account for scr refresh
            text_2.tStartRefresh = tThisFlipGlobal  # on global time
            win.timeOnFlip(text_2, 'tStartRefresh')  # time at next scr refresh
            text_2.setAutoDraw(True)
        if text_2.status == STARTED:
            # is it time to stop? (based on global clock, using actual start)
            if tThisFlipGlobal > text_2.tStartRefresh + 35-frameTolerance:
                # keep track of stop time/frame for later
                text_2.tStop = t  # not accounting for scr refresh
                text_2.frameNStop = frameN  # exact frame index
                win.timeOnFlip(text_2, 'tStopRefresh')  # time at next scr refresh
                text_2.setAutoDraw(False)
        
        # check for quit (typically the Esc key)
        if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
            core.quit()
        
        # check if all components have finished
        if not continueRoutine:  # a component has requested a forced-end of Routine
            break
        continueRoutine = False  # will revert to True if at least one component still running
        for thisComponent in calibrateComponents:
            if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
                continueRoutine = True
                break  # at least one component has not yet finished
        
        # refresh the screen
        if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
            win.flip()
    
    # -------Ending Routine "calibrate"-------
    for thisComponent in calibrateComponents:
        if hasattr(thisComponent, "setAutoDraw"):
            thisComponent.setAutoDraw(False)
    win.winHandle.maximize()
    win.winHandle.set_fullscreen(True) 
    win.winHandle.activate()
    win.flip()
    thisExp.nextEntry()
    
# completed 0 repeats of 'calibration_loop'


# ------Prepare to start Routine "start_recording"-------
continueRoutine = True
routineTimer.add(5.000000)
# update component parameters for each repeat
#Start data stream
eyetracker.start_recording()
# keep track of which components have finished
start_recordingComponents = [text]
for thisComponent in start_recordingComponents:
    thisComponent.tStart = None
    thisComponent.tStop = None
    thisComponent.tStartRefresh = None
    thisComponent.tStopRefresh = None
    if hasattr(thisComponent, 'status'):
        thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
start_recordingClock.reset(-_timeToFirstFrame)  # t0 is time of first possible flip
frameN = -1

# -------Run Routine "start_recording"-------
while continueRoutine and routineTimer.getTime() > 0:
    # get current time
    t = start_recordingClock.getTime()
    tThisFlip = win.getFutureFlipTime(clock=start_recordingClock)
    tThisFlipGlobal = win.getFutureFlipTime(clock=None)
    frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
    # update/draw components on each frame
    
    # *text* updates
    if text.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
        # keep track of start time/frame for later
        text.frameNStart = frameN  # exact frame index
        text.tStart = t  # local t and not account for scr refresh
        text.tStartRefresh = tThisFlipGlobal  # on global time
        win.timeOnFlip(text, 'tStartRefresh')  # time at next scr refresh
        text.setAutoDraw(True)
    if text.status == STARTED:
        # is it time to stop? (based on global clock, using actual start)
        if tThisFlipGlobal > text.tStartRefresh + 5-frameTolerance:
            # keep track of stop time/frame for later
            text.tStop = t  # not accounting for scr refresh
            text.frameNStop = frameN  # exact frame index
            win.timeOnFlip(text, 'tStopRefresh')  # time at next scr refresh
            text.setAutoDraw(False)
    
    # check for quit (typically the Esc key)
    if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
        core.quit()
    
    # check if all components have finished
    if not continueRoutine:  # a component has requested a forced-end of Routine
        break
    continueRoutine = False  # will revert to True if at least one component still running
    for thisComponent in start_recordingComponents:
        if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
            continueRoutine = True
            break  # at least one component has not yet finished
    
    # refresh the screen
    if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
        win.flip()

# -------Ending Routine "start_recording"-------
for thisComponent in start_recordingComponents:
    if hasattr(thisComponent, "setAutoDraw"):
        thisComponent.setAutoDraw(False)

# set up handler to look after randomisation of conditions etc
Practise_loop = data.TrialHandler(nReps=1, method='random', 
    extraInfo=expInfo, originPath=-1,
    trialList=data.importConditions('Practise.xlsx'),
    seed=None, name='Practise_loop')
thisExp.addLoop(Practise_loop)  # add the loop to the experiment
thisPractise_loop = Practise_loop.trialList[0]  # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb = thisPractise_loop.rgb)
if thisPractise_loop != None:
    for paramName in thisPractise_loop:
        exec('{} = thisPractise_loop[paramName]'.format(paramName))

for thisPractise_loop in Practise_loop:
    currentLoop = Practise_loop
    # abbreviate parameter names if possible (e.g. rgb = thisPractise_loop.rgb)
    if thisPractise_loop != None:
        for paramName in thisPractise_loop:
            exec('{} = thisPractise_loop[paramName]'.format(paramName))
    
    # ------Prepare to start Routine "fixation"-------
    continueRoutine = True
    # update component parameters for each repeat
    fixation_started=False 
    # keep track of which components have finished
    fixationComponents = [fix_cross]
    for thisComponent in fixationComponents:
        thisComponent.tStart = None
        thisComponent.tStop = None
        thisComponent.tStartRefresh = None
        thisComponent.tStopRefresh = None
        if hasattr(thisComponent, 'status'):
            thisComponent.status = NOT_STARTED
    # reset timers
    t = 0
    _timeToFirstFrame = win.getFutureFlipTime(clock="now")
    fixationClock.reset(-_timeToFirstFrame)  # t0 is time of first possible flip
    frameN = -1
    
    # -------Run Routine "fixation"-------
    while continueRoutine:
        # get current time
        t = fixationClock.getTime()
        tThisFlip = win.getFutureFlipTime(clock=fixationClock)
        tThisFlipGlobal = win.getFutureFlipTime(clock=None)
        frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
        # update/draw components on each frame
        
        # *fix_cross* updates
        if fix_cross.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
            # keep track of start time/frame for later
            fix_cross.frameNStart = frameN  # exact frame index
            fix_cross.tStart = t  # local t and not account for scr refresh
            fix_cross.tStartRefresh = tThisFlipGlobal  # on global time
            win.timeOnFlip(fix_cross, 'tStartRefresh')  # time at next scr refresh
            fix_cross.setAutoDraw(True)
        if eyetracker:
            gpos=eyetracker.sample()
            if type(gpos) in [list,tuple]:
                x,y=gpos[0],gpos[1]
                distance_from_center=np.sqrt(abs(x-0)**2+abs(y-0)**2)
                if distance_from_center<=80:
                    if not fixation_started:
                        fixation_started=True
                        fixation_start_time=t
                    if fixation_start_time>0.40:
                        continueRoutine=False
                    else:
                        fixation_started=False 
        
        # check for quit (typically the Esc key)
        if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
            core.quit()
        
        # check if all components have finished
        if not continueRoutine:  # a component has requested a forced-end of Routine
            break
        continueRoutine = False  # will revert to True if at least one component still running
        for thisComponent in fixationComponents:
            if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
                continueRoutine = True
                break  # at least one component has not yet finished
        
        # refresh the screen
        if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
            win.flip()
    
    # -------Ending Routine "fixation"-------
    for thisComponent in fixationComponents:
        if hasattr(thisComponent, "setAutoDraw"):
            thisComponent.setAutoDraw(False)
    # the Routine "fixation" was not non-slip safe, so reset the non-slip timer
    routineTimer.reset()
    
    # ------Prepare to start Routine "Practise_trials"-------
    continueRoutine = True
    routineTimer.add(30.000000)
    # update component parameters for each repeat
    # setup some python lists for storing info about the mouse
    mouse.x = []
    mouse.y = []
    mouse.leftButton = []
    mouse.midButton = []
    mouse.rightButton = []
    mouse.time = []
    mouse.clicked_name = []
    gotValidClick = False  # until a click is received
    mouse.mouseClock.reset()
    background.setImage(Scenes)
    star.setPos((p_Star_x,p_Star_y))
    mouse.setPos([0,0])
    #eyetracker.user_data("%s_START" %Img) 
    
    # keep track of which components have finished
    Practise_trialsComponents = [mouse, background, star, gaze_cursor]
    for thisComponent in Practise_trialsComponents:
        thisComponent.tStart = None
        thisComponent.tStop = None
        thisComponent.tStartRefresh = None
        thisComponent.tStopRefresh = None
        if hasattr(thisComponent, 'status'):
            thisComponent.status = NOT_STARTED
    # reset timers
    t = 0
    _timeToFirstFrame = win.getFutureFlipTime(clock="now")
    Practise_trialsClock.reset(-_timeToFirstFrame)  # t0 is time of first possible flip
    frameN = -1
    
    # -------Run Routine "Practise_trials"-------
    while continueRoutine and routineTimer.getTime() > 0:
        # get current time
        t = Practise_trialsClock.getTime()
        tThisFlip = win.getFutureFlipTime(clock=Practise_trialsClock)
        tThisFlipGlobal = win.getFutureFlipTime(clock=None)
        frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
        # update/draw components on each frame
        # *mouse* updates
        if mouse.status == NOT_STARTED and t >= 0.0-frameTolerance:
            # keep track of start time/frame for later
            mouse.frameNStart = frameN  # exact frame index
            mouse.tStart = t  # local t and not account for scr refresh
            mouse.tStartRefresh = tThisFlipGlobal  # on global time
            win.timeOnFlip(mouse, 'tStartRefresh')  # time at next scr refresh
            mouse.status = STARTED
            prevButtonState = mouse.getPressed()  # if button is down already this ISN'T a new click
        if mouse.status == STARTED:
            # is it time to stop? (based on global clock, using actual start)
            if tThisFlipGlobal > mouse.tStartRefresh + 30-frameTolerance:
                # keep track of stop time/frame for later
                mouse.tStop = t  # not accounting for scr refresh
                mouse.frameNStop = frameN  # exact frame index
                win.timeOnFlip(mouse, 'tStopRefresh')  # time at next scr refresh
                mouse.status = FINISHED
        if mouse.status == STARTED:  # only update if started and not finished!
            buttons = mouse.getPressed()
            if buttons != prevButtonState:  # button state changed?
                prevButtonState = buttons
                if sum(buttons) > 0:  # state changed to a new click
                    # check if the mouse was inside our 'clickable' objects
                    gotValidClick = False
                    for obj in [star,background]:
                        if obj.contains(mouse):
                            gotValidClick = True
                            mouse.clicked_name.append(obj.name)
                    x, y = mouse.getPos()
                    mouse.x.append(x)
                    mouse.y.append(y)
                    buttons = mouse.getPressed()
                    mouse.leftButton.append(buttons[0])
                    mouse.midButton.append(buttons[1])
                    mouse.rightButton.append(buttons[2])
                    mouse.time.append(mouse.mouseClock.getTime())
        
        # *background* updates
        if background.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
            # keep track of start time/frame for later
            background.frameNStart = frameN  # exact frame index
            background.tStart = t  # local t and not account for scr refresh
            background.tStartRefresh = tThisFlipGlobal  # on global time
            win.timeOnFlip(background, 'tStartRefresh')  # time at next scr refresh
            background.setAutoDraw(True)
        if background.status == STARTED:
            # is it time to stop? (based on global clock, using actual start)
            if tThisFlipGlobal > background.tStartRefresh + 30-frameTolerance:
                # keep track of stop time/frame for later
                background.tStop = t  # not accounting for scr refresh
                background.frameNStop = frameN  # exact frame index
                win.timeOnFlip(background, 'tStopRefresh')  # time at next scr refresh
                background.setAutoDraw(False)
        
        # *star* updates
        if star.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
            # keep track of start time/frame for later
            star.frameNStart = frameN  # exact frame index
            star.tStart = t  # local t and not account for scr refresh
            star.tStartRefresh = tThisFlipGlobal  # on global time
            win.timeOnFlip(star, 'tStartRefresh')  # time at next scr refresh
            star.setAutoDraw(True)
        if star.status == STARTED:
            # is it time to stop? (based on global clock, using actual start)
            if tThisFlipGlobal > star.tStartRefresh + 30-frameTolerance:
                # keep track of stop time/frame for later
                star.tStop = t  # not accounting for scr refresh
                star.frameNStop = frameN  # exact frame index
                win.timeOnFlip(star, 'tStopRefresh')  # time at next scr refresh
                star.setAutoDraw(False)
        
        # *gaze_cursor* updates
        if gaze_cursor.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
            # keep track of start time/frame for later
            gaze_cursor.frameNStart = frameN  # exact frame index
            gaze_cursor.tStart = t  # local t and not account for scr refresh
            gaze_cursor.tStartRefresh = tThisFlipGlobal  # on global time
            win.timeOnFlip(gaze_cursor, 'tStartRefresh')  # time at next scr refresh
            gaze_cursor.setAutoDraw(True)
        if gaze_cursor.status == STARTED:
            # is it time to stop? (based on global clock, using actual start)
            if tThisFlipGlobal > gaze_cursor.tStartRefresh + 30-frameTolerance:
                # keep track of stop time/frame for later
                gaze_cursor.tStop = t  # not accounting for scr refresh
                gaze_cursor.frameNStop = frameN  # exact frame index
                win.timeOnFlip(gaze_cursor, 'tStopRefresh')  # time at next scr refresh
                gaze_cursor.setAutoDraw(False)
        if gaze_cursor.status == STARTED:  # only update if drawing
            gaze_cursor.setOpacity(display_gaze, log=False)
            gaze_cursor.setPos([x,y], log=False)
            gaze_cursor.setSize((20, 20), log=False)
        if eyetracker:
            if event.getKeys(keyList=['g',]):
                display_gaze=not display_gaze
            gpos=eyetracker.sample()
            if type(gpos) in [list,tuple]:
                x,y=gpos[0],gpos[1]
                d=np.sqrt(abs(x-p_Star_x)**2+abs(y-p_Star_y)**2)
                if d<= fixation_boundary and mouse.clicked_name==["star","background"]:
                    continueRoutine=False
                elif mouse.clicked_name==["background"]:
                    continueRoutine=False
                else:
                    continueRoutine=True
        
        # check for quit (typically the Esc key)
        if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
            core.quit()
        
        # check if all components have finished
        if not continueRoutine:  # a component has requested a forced-end of Routine
            break
        continueRoutine = False  # will revert to True if at least one component still running
        for thisComponent in Practise_trialsComponents:
            if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
                continueRoutine = True
                break  # at least one component has not yet finished
        
        # refresh the screen
        if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
            win.flip()
    
    # -------Ending Routine "Practise_trials"-------
    for thisComponent in Practise_trialsComponents:
        if hasattr(thisComponent, "setAutoDraw"):
            thisComponent.setAutoDraw(False)
    # store data for Practise_loop (TrialHandler)
    Practise_loop.addData('mouse.x', mouse.x)
    Practise_loop.addData('mouse.y', mouse.y)
    Practise_loop.addData('mouse.leftButton', mouse.leftButton)
    Practise_loop.addData('mouse.midButton', mouse.midButton)
    Practise_loop.addData('mouse.rightButton', mouse.rightButton)
    Practise_loop.addData('mouse.time', mouse.time)
    Practise_loop.addData('mouse.clicked_name', mouse.clicked_name)
    Practise_loop.addData('mouse.started', mouse.tStart)
    Practise_loop.addData('mouse.stopped', mouse.tStop)
    #eyetracker.user_data("%s_END" %Img)
    #time.sleep(0.0066)
    #eyetracker.user_data("0")
    
    # ------Prepare to start Routine "Practise_feedback"-------
    continueRoutine = True
    routineTimer.add(0.700000)
    # update component parameters for each repeat
    if mouse.clicked_name==["star","background"]:
        sound='Sounds/correct3.wav'
        Practise_loop.addData('Practise_acc', 1)
        Practise_loop.addData('Mouse_click_X', mouse.x[-1])
        Practise_loop.addData('Mouse_click_Y', mouse.y[-1])
        Practise_loop.addData('Reaction_time', mouse.time[-1])
    elif mouse.clicked_name==["background"]:
        sound='Sounds/wrong2.wav'
        Practise_loop.addData('Practise_acc', 0)
        Practise_loop.addData('Mouse_click_X', mouse.x[-1])
        Practise_loop.addData('Mouse_click_Y', mouse.y[-1])
        Practise_loop.addData('Reaction_time', mouse.time[-1])
    else:
        sound='Sounds/cuckoo.wav'
        Practise_loop.addData('Practise_acc', -9)
    
    
    sound_1.setSound(sound, secs=0.7, hamming=False)
    sound_1.setVolume(1, log=False)
    # keep track of which components have finished
    Practise_feedbackComponents = [sound_1]
    for thisComponent in Practise_feedbackComponents:
        thisComponent.tStart = None
        thisComponent.tStop = None
        thisComponent.tStartRefresh = None
        thisComponent.tStopRefresh = None
        if hasattr(thisComponent, 'status'):
            thisComponent.status = NOT_STARTED
    # reset timers
    t = 0
    _timeToFirstFrame = win.getFutureFlipTime(clock="now")
    Practise_feedbackClock.reset(-_timeToFirstFrame)  # t0 is time of first possible flip
    frameN = -1
    
    # -------Run Routine "Practise_feedback"-------
    while continueRoutine and routineTimer.getTime() > 0:
        # get current time
        t = Practise_feedbackClock.getTime()
        tThisFlip = win.getFutureFlipTime(clock=Practise_feedbackClock)
        tThisFlipGlobal = win.getFutureFlipTime(clock=None)
        frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
        # update/draw components on each frame
        if mouse.clicked_name==["star","background"]:
            v=visual.ImageStim(win=win, image='Stimuli/v.png', pos=(0, 0),size=(150,150))
            v.draw()
        elif mouse.clicked_name==["background"]:
            x=visual.ImageStim(win=win, image='Stimuli/x.png', pos=(0, 0),size=(150,150))
            x.draw()
        else:
            clock=visual.ImageStim(win=win, image='Stimuli/clock_.png', pos=(0, 0))
            clock.draw()
        # start/stop sound_1
        if sound_1.status == NOT_STARTED and t >= 0.0-frameTolerance:
            # keep track of start time/frame for later
            sound_1.frameNStart = frameN  # exact frame index
            sound_1.tStart = t  # local t and not account for scr refresh
            sound_1.tStartRefresh = tThisFlipGlobal  # on global time
            sound_1.play()  # start the sound (it finishes automatically)
        if sound_1.status == STARTED:
            # is it time to stop? (based on global clock, using actual start)
            if tThisFlipGlobal > sound_1.tStartRefresh + 0.7-frameTolerance:
                # keep track of stop time/frame for later
                sound_1.tStop = t  # not accounting for scr refresh
                sound_1.frameNStop = frameN  # exact frame index
                win.timeOnFlip(sound_1, 'tStopRefresh')  # time at next scr refresh
                sound_1.stop()
        
        # check for quit (typically the Esc key)
        if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
            core.quit()
        
        # check if all components have finished
        if not continueRoutine:  # a component has requested a forced-end of Routine
            break
        continueRoutine = False  # will revert to True if at least one component still running
        for thisComponent in Practise_feedbackComponents:
            if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
                continueRoutine = True
                break  # at least one component has not yet finished
        
        # refresh the screen
        if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
            win.flip()
    
    # -------Ending Routine "Practise_feedback"-------
    for thisComponent in Practise_feedbackComponents:
        if hasattr(thisComponent, "setAutoDraw"):
            thisComponent.setAutoDraw(False)
    sound_1.stop()  # ensure sound has stopped at end of routine
    thisExp.nextEntry()
    
# completed 1 repeats of 'Practise_loop'


# ------Prepare to start Routine "Start"-------
continueRoutine = True
# update component parameters for each repeat
# keep track of which components have finished
StartComponents = [worldmap, plot2, next2]
for thisComponent in StartComponents:
    thisComponent.tStart = None
    thisComponent.tStop = None
    thisComponent.tStartRefresh = None
    thisComponent.tStopRefresh = None
    if hasattr(thisComponent, 'status'):
        thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
StartClock.reset(-_timeToFirstFrame)  # t0 is time of first possible flip
frameN = -1

# -------Run Routine "Start"-------
while continueRoutine:
    # get current time
    t = StartClock.getTime()
    tThisFlip = win.getFutureFlipTime(clock=StartClock)
    tThisFlipGlobal = win.getFutureFlipTime(clock=None)
    frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
    # update/draw components on each frame
    
    # *worldmap* updates
    if worldmap.status == NOT_STARTED and tThisFlip >= 0-frameTolerance:
        # keep track of start time/frame for later
        worldmap.frameNStart = frameN  # exact frame index
        worldmap.tStart = t  # local t and not account for scr refresh
        worldmap.tStartRefresh = tThisFlipGlobal  # on global time
        win.timeOnFlip(worldmap, 'tStartRefresh')  # time at next scr refresh
        worldmap.setAutoDraw(True)
    if worldmap.status == STARTED:
        # is it time to stop? (based on global clock, using actual start)
        if tThisFlipGlobal > worldmap.tStartRefresh + 6-frameTolerance:
            # keep track of stop time/frame for later
            worldmap.tStop = t  # not accounting for scr refresh
            worldmap.frameNStop = frameN  # exact frame index
            win.timeOnFlip(worldmap, 'tStopRefresh')  # time at next scr refresh
            worldmap.setAutoDraw(False)
    
    # *plot2* updates
    if plot2.status == NOT_STARTED and tThisFlip >= 6-frameTolerance:
        # keep track of start time/frame for later
        plot2.frameNStart = frameN  # exact frame index
        plot2.tStart = t  # local t and not account for scr refresh
        plot2.tStartRefresh = tThisFlipGlobal  # on global time
        win.timeOnFlip(plot2, 'tStartRefresh')  # time at next scr refresh
        plot2.setAutoDraw(True)
    
    # *next2* updates
    if next2.status == NOT_STARTED and tThisFlip >= 6-frameTolerance:
        # keep track of start time/frame for later
        next2.frameNStart = frameN  # exact frame index
        next2.tStart = t  # local t and not account for scr refresh
        next2.tStartRefresh = tThisFlipGlobal  # on global time
        win.timeOnFlip(next2, 'tStartRefresh')  # time at next scr refresh
        next2.setAutoDraw(True)
    if mouse.isPressedIn(next2):
        continueRoutine=False
    
    # check for quit (typically the Esc key)
    if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
        core.quit()
    
    # check if all components have finished
    if not continueRoutine:  # a component has requested a forced-end of Routine
        break
    continueRoutine = False  # will revert to True if at least one component still running
    for thisComponent in StartComponents:
        if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
            continueRoutine = True
            break  # at least one component has not yet finished
    
    # refresh the screen
    if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
        win.flip()

# -------Ending Routine "Start"-------
for thisComponent in StartComponents:
    if hasattr(thisComponent, "setAutoDraw"):
        thisComponent.setAutoDraw(False)
thisExp.addData('worldmap.started', worldmap.tStartRefresh)
thisExp.addData('worldmap.stopped', worldmap.tStopRefresh)
thisExp.addData('plot2.started', plot2.tStartRefresh)
thisExp.addData('plot2.stopped', plot2.tStopRefresh)
thisExp.addData('next2.started', next2.tStartRefresh)
thisExp.addData('next2.stopped', next2.tStopRefresh)
# the Routine "Start" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()

# set up handler to look after randomisation of conditions etc
Learning_loop = data.TrialHandler(nReps=4, method='random', 
    extraInfo=expInfo, originPath=-1,
    trialList=data.importConditions(condition),
    seed=None, name='Learning_loop')
thisExp.addLoop(Learning_loop)  # add the loop to the experiment
thisLearning_loop = Learning_loop.trialList[0]  # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb = thisLearning_loop.rgb)
if thisLearning_loop != None:
    for paramName in thisLearning_loop:
        exec('{} = thisLearning_loop[paramName]'.format(paramName))

for thisLearning_loop in Learning_loop:
    currentLoop = Learning_loop
    # abbreviate parameter names if possible (e.g. rgb = thisLearning_loop.rgb)
    if thisLearning_loop != None:
        for paramName in thisLearning_loop:
            exec('{} = thisLearning_loop[paramName]'.format(paramName))
    
    # ------Prepare to start Routine "fixation"-------
    continueRoutine = True
    # update component parameters for each repeat
    fixation_started=False 
    # keep track of which components have finished
    fixationComponents = [fix_cross]
    for thisComponent in fixationComponents:
        thisComponent.tStart = None
        thisComponent.tStop = None
        thisComponent.tStartRefresh = None
        thisComponent.tStopRefresh = None
        if hasattr(thisComponent, 'status'):
            thisComponent.status = NOT_STARTED
    # reset timers
    t = 0
    _timeToFirstFrame = win.getFutureFlipTime(clock="now")
    fixationClock.reset(-_timeToFirstFrame)  # t0 is time of first possible flip
    frameN = -1
    
    # -------Run Routine "fixation"-------
    while continueRoutine:
        # get current time
        t = fixationClock.getTime()
        tThisFlip = win.getFutureFlipTime(clock=fixationClock)
        tThisFlipGlobal = win.getFutureFlipTime(clock=None)
        frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
        # update/draw components on each frame
        
        # *fix_cross* updates
        if fix_cross.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
            # keep track of start time/frame for later
            fix_cross.frameNStart = frameN  # exact frame index
            fix_cross.tStart = t  # local t and not account for scr refresh
            fix_cross.tStartRefresh = tThisFlipGlobal  # on global time
            win.timeOnFlip(fix_cross, 'tStartRefresh')  # time at next scr refresh
            fix_cross.setAutoDraw(True)
        if eyetracker:
            gpos=eyetracker.sample()
            if type(gpos) in [list,tuple]:
                x,y=gpos[0],gpos[1]
                distance_from_center=np.sqrt(abs(x-0)**2+abs(y-0)**2)
                if distance_from_center<=80:
                    if not fixation_started:
                        fixation_started=True
                        fixation_start_time=t
                    if fixation_start_time>0.40:
                        continueRoutine=False
                    else:
                        fixation_started=False 
        
        # check for quit (typically the Esc key)
        if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
            core.quit()
        
        # check if all components have finished
        if not continueRoutine:  # a component has requested a forced-end of Routine
            break
        continueRoutine = False  # will revert to True if at least one component still running
        for thisComponent in fixationComponents:
            if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
                continueRoutine = True
                break  # at least one component has not yet finished
        
        # refresh the screen
        if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
            win.flip()
    
    # -------Ending Routine "fixation"-------
    for thisComponent in fixationComponents:
        if hasattr(thisComponent, "setAutoDraw"):
            thisComponent.setAutoDraw(False)
    # the Routine "fixation" was not non-slip safe, so reset the non-slip timer
    routineTimer.reset()
    
    # ------Prepare to start Routine "Learning_trials"-------
    continueRoutine = True
    # update component parameters for each repeat
    # setup some python lists for storing info about the mouse2
    mouse2.x = []
    mouse2.y = []
    mouse2.leftButton = []
    mouse2.midButton = []
    mouse2.rightButton = []
    mouse2.time = []
    mouse2.clicked_name = []
    gotValidClick = False  # until a click is received
    background2.setImage(List)
    Star.setPos((StarX,StarY))
    Star.setImage('Stimuli/20x20t.png')
    if Learning_loop.thisRepN ==0:
        duration=30
    elif Learning_loop.thisRepN ==1:
        duration=25
    elif Learning_loop.thisRepN ==2:
        duration=20
    else:
        duration=15
    
    mouse2.setPos([0,0])
    eyetracker.user_data("%s_%s_%s_START" % (Images,Clutter_Level,Learning_loop.thisRepN)) 
    # keep track of which components have finished
    Learning_trialsComponents = [mouse2, background2, Star, gaze_Cursor]
    for thisComponent in Learning_trialsComponents:
        thisComponent.tStart = None
        thisComponent.tStop = None
        thisComponent.tStartRefresh = None
        thisComponent.tStopRefresh = None
        if hasattr(thisComponent, 'status'):
            thisComponent.status = NOT_STARTED
    # reset timers
    t = 0
    _timeToFirstFrame = win.getFutureFlipTime(clock="now")
    Learning_trialsClock.reset(-_timeToFirstFrame)  # t0 is time of first possible flip
    frameN = -1
    
    # -------Run Routine "Learning_trials"-------
    while continueRoutine:
        # get current time
        t = Learning_trialsClock.getTime()
        tThisFlip = win.getFutureFlipTime(clock=Learning_trialsClock)
        tThisFlipGlobal = win.getFutureFlipTime(clock=None)
        frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
        # update/draw components on each frame
        # *mouse2* updates
        if mouse2.status == NOT_STARTED and t >= 0.0-frameTolerance:
            # keep track of start time/frame for later
            mouse2.frameNStart = frameN  # exact frame index
            mouse2.tStart = t  # local t and not account for scr refresh
            mouse2.tStartRefresh = tThisFlipGlobal  # on global time
            win.timeOnFlip(mouse2, 'tStartRefresh')  # time at next scr refresh
            mouse2.status = STARTED
            mouse2.mouseClock.reset()
            prevButtonState = mouse2.getPressed()  # if button is down already this ISN'T a new click
        if mouse2.status == STARTED:
            # is it time to stop? (based on global clock, using actual start)
            if tThisFlipGlobal > mouse2.tStartRefresh + duration-frameTolerance:
                # keep track of stop time/frame for later
                mouse2.tStop = t  # not accounting for scr refresh
                mouse2.frameNStop = frameN  # exact frame index
                win.timeOnFlip(mouse2, 'tStopRefresh')  # time at next scr refresh
                mouse2.status = FINISHED
        if mouse2.status == STARTED:  # only update if started and not finished!
            buttons = mouse2.getPressed()
            if buttons != prevButtonState:  # button state changed?
                prevButtonState = buttons
                if sum(buttons) > 0:  # state changed to a new click
                    # check if the mouse was inside our 'clickable' objects
                    gotValidClick = False
                    for obj in [Star,background2]:
                        if obj.contains(mouse2):
                            gotValidClick = True
                            mouse2.clicked_name.append(obj.name)
                    x, y = mouse2.getPos()
                    mouse2.x.append(x)
                    mouse2.y.append(y)
                    buttons = mouse2.getPressed()
                    mouse2.leftButton.append(buttons[0])
                    mouse2.midButton.append(buttons[1])
                    mouse2.rightButton.append(buttons[2])
                    mouse2.time.append(mouse2.mouseClock.getTime())
        
        # *background2* updates
        if background2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
            # keep track of start time/frame for later
            background2.frameNStart = frameN  # exact frame index
            background2.tStart = t  # local t and not account for scr refresh
            background2.tStartRefresh = tThisFlipGlobal  # on global time
            win.timeOnFlip(background2, 'tStartRefresh')  # time at next scr refresh
            background2.setAutoDraw(True)
        if background2.status == STARTED:
            # is it time to stop? (based on global clock, using actual start)
            if tThisFlipGlobal > background2.tStartRefresh + duration-frameTolerance:
                # keep track of stop time/frame for later
                background2.tStop = t  # not accounting for scr refresh
                background2.frameNStop = frameN  # exact frame index
                win.timeOnFlip(background2, 'tStopRefresh')  # time at next scr refresh
                background2.setAutoDraw(False)
        
        # *Star* updates
        if Star.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
            # keep track of start time/frame for later
            Star.frameNStart = frameN  # exact frame index
            Star.tStart = t  # local t and not account for scr refresh
            Star.tStartRefresh = tThisFlipGlobal  # on global time
            win.timeOnFlip(Star, 'tStartRefresh')  # time at next scr refresh
            Star.setAutoDraw(True)
        if Star.status == STARTED:
            # is it time to stop? (based on global clock, using actual start)
            if tThisFlipGlobal > Star.tStartRefresh + duration-frameTolerance:
                # keep track of stop time/frame for later
                Star.tStop = t  # not accounting for scr refresh
                Star.frameNStop = frameN  # exact frame index
                win.timeOnFlip(Star, 'tStopRefresh')  # time at next scr refresh
                Star.setAutoDraw(False)
        
        # *gaze_Cursor* updates
        if gaze_Cursor.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
            # keep track of start time/frame for later
            gaze_Cursor.frameNStart = frameN  # exact frame index
            gaze_Cursor.tStart = t  # local t and not account for scr refresh
            gaze_Cursor.tStartRefresh = tThisFlipGlobal  # on global time
            win.timeOnFlip(gaze_Cursor, 'tStartRefresh')  # time at next scr refresh
            gaze_Cursor.setAutoDraw(True)
        if gaze_Cursor.status == STARTED:
            # is it time to stop? (based on global clock, using actual start)
            if tThisFlipGlobal > gaze_Cursor.tStartRefresh + duration-frameTolerance:
                # keep track of stop time/frame for later
                gaze_Cursor.tStop = t  # not accounting for scr refresh
                gaze_Cursor.frameNStop = frameN  # exact frame index
                win.timeOnFlip(gaze_Cursor, 'tStopRefresh')  # time at next scr refresh
                gaze_Cursor.setAutoDraw(False)
        if gaze_Cursor.status == STARTED:  # only update if drawing
            gaze_Cursor.setOpacity(display_gaze, log=False)
            gaze_Cursor.setPos([x,y], log=False)
        if eyetracker:
            if event.getKeys(keyList=['g',]):
                display_gaze=not display_gaze
            gpos=eyetracker.sample()
            if type(gpos) in [list,tuple]:
                x,y=gpos[0],gpos[1]
                d=np.sqrt(abs(x-StarX)**2+abs(y-StarY)**2)
                rounded_d=np.round(d,0)
                if rounded_d<= fixation_boundary and mouse2.clicked_name==["Star","background2"]:
                    continueRoutine=False
                elif mouse2.clicked_name==["background2"]:
                    continueRoutine=False
                else:
                    continueRoutine=True 
        
        # check for quit (typically the Esc key)
        if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
            core.quit()
        
        # check if all components have finished
        if not continueRoutine:  # a component has requested a forced-end of Routine
            break
        continueRoutine = False  # will revert to True if at least one component still running
        for thisComponent in Learning_trialsComponents:
            if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
                continueRoutine = True
                break  # at least one component has not yet finished
        
        # refresh the screen
        if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
            win.flip()
    
    # -------Ending Routine "Learning_trials"-------
    for thisComponent in Learning_trialsComponents:
        if hasattr(thisComponent, "setAutoDraw"):
            thisComponent.setAutoDraw(False)
    # store data for Learning_loop (TrialHandler)
    Learning_loop.addData('mouse2.x', mouse2.x)
    Learning_loop.addData('mouse2.y', mouse2.y)
    Learning_loop.addData('mouse2.leftButton', mouse2.leftButton)
    Learning_loop.addData('mouse2.midButton', mouse2.midButton)
    Learning_loop.addData('mouse2.rightButton', mouse2.rightButton)
    Learning_loop.addData('mouse2.time', mouse2.time)
    Learning_loop.addData('mouse2.clicked_name', mouse2.clicked_name)
    Learning_loop.addData('mouse2.started', mouse2.tStart)
    Learning_loop.addData('mouse2.stopped', mouse2.tStop)
    Learning_loop.addData('background2.started', background2.tStartRefresh)
    Learning_loop.addData('background2.stopped', background2.tStopRefresh)
    Learning_loop.addData('Star.started', Star.tStartRefresh)
    Learning_loop.addData('Star.stopped', Star.tStopRefresh)
    Learning_loop.addData('gaze_Cursor.started', gaze_Cursor.tStartRefresh)
    Learning_loop.addData('gaze_Cursor.stopped', gaze_Cursor.tStopRefresh)
    eyetracker.user_data("%s_%s_%s_END" % (Images,Clutter_Level,Learning_loop.thisRepN))
    #time.sleep(0.0066)
    eyetracker.user_data("0")
    # the Routine "Learning_trials" was not non-slip safe, so reset the non-slip timer
    routineTimer.reset()
    
    # ------Prepare to start Routine "Learning_feedback"-------
    continueRoutine = True
    routineTimer.add(0.700000)
    # update component parameters for each repeat
    my_trial+=1
    if mouse2.clicked_name==["Star","background2"]:
        sound='Sounds/correct3.wav'
        Learning_loop.addData('Practise_acc', 1)
        Learning_loop.addData('Mouse_click_X', mouse2.x[-1])
        Learning_loop.addData('Mouse_click_Y', mouse2.y[-1])
        Learning_loop.addData('Reaction_time', mouse2.time[-1])
        Acc_trials+=1
        Acc_blocks+=1
    elif mouse2.clicked_name==["background2"]:
        sound='Sounds/wrong2.wav'
        Learning_loop.addData('Practise_acc', 0)
        Learning_loop.addData('Mouse_click_X', mouse2.x[-1])
        Learning_loop.addData('Mouse_click_Y', mouse2.y[-1])
        Learning_loop.addData('Reaction_time', mouse2.time[-1])
    else:
        sound='Sounds/cuckoo.wav'
        Learning_loop.addData('Practise_acc', -9)
    sound_2.setSound(sound, secs=0.7, hamming=False)
    sound_2.setVolume(1, log=False)
    # keep track of which components have finished
    Learning_feedbackComponents = [sound_2]
    for thisComponent in Learning_feedbackComponents:
        thisComponent.tStart = None
        thisComponent.tStop = None
        thisComponent.tStartRefresh = None
        thisComponent.tStopRefresh = None
        if hasattr(thisComponent, 'status'):
            thisComponent.status = NOT_STARTED
    # reset timers
    t = 0
    _timeToFirstFrame = win.getFutureFlipTime(clock="now")
    Learning_feedbackClock.reset(-_timeToFirstFrame)  # t0 is time of first possible flip
    frameN = -1
    
    # -------Run Routine "Learning_feedback"-------
    while continueRoutine and routineTimer.getTime() > 0:
        # get current time
        t = Learning_feedbackClock.getTime()
        tThisFlip = win.getFutureFlipTime(clock=Learning_feedbackClock)
        tThisFlipGlobal = win.getFutureFlipTime(clock=None)
        frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
        # update/draw components on each frame
        if mouse2.clicked_name==["Star","background2"]:
            v=visual.ImageStim(win=win, image='Stimuli/v.png', pos=(0, 0), size=(150,150))
            v.draw()
        elif mouse2.clicked_name==["background2"]:
            x=visual.ImageStim(win=win, image='Stimuli/x.png', pos=(0, 0), size=(150,150))
            x.draw()
        else:
            clock=visual.ImageStim(win=win, image='Stimuli/clock_.png', pos=(0, 0))
            clock.draw()
        # start/stop sound_2
        if sound_2.status == NOT_STARTED and t >= 0.0-frameTolerance:
            # keep track of start time/frame for later
            sound_2.frameNStart = frameN  # exact frame index
            sound_2.tStart = t  # local t and not account for scr refresh
            sound_2.tStartRefresh = tThisFlipGlobal  # on global time
            sound_2.play()  # start the sound (it finishes automatically)
        if sound_2.status == STARTED:
            # is it time to stop? (based on global clock, using actual start)
            if tThisFlipGlobal > sound_2.tStartRefresh + 0.7-frameTolerance:
                # keep track of stop time/frame for later
                sound_2.tStop = t  # not accounting for scr refresh
                sound_2.frameNStop = frameN  # exact frame index
                win.timeOnFlip(sound_2, 'tStopRefresh')  # time at next scr refresh
                sound_2.stop()
        
        # check for quit (typically the Esc key)
        if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
            core.quit()
        
        # check if all components have finished
        if not continueRoutine:  # a component has requested a forced-end of Routine
            break
        continueRoutine = False  # will revert to True if at least one component still running
        for thisComponent in Learning_feedbackComponents:
            if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
                continueRoutine = True
                break  # at least one component has not yet finished
        
        # refresh the screen
        if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
            win.flip()
    
    # -------Ending Routine "Learning_feedback"-------
    for thisComponent in Learning_feedbackComponents:
        if hasattr(thisComponent, "setAutoDraw"):
            thisComponent.setAutoDraw(False)
    sound_2.stop()  # ensure sound has stopped at end of routine
    
    # ------Prepare to start Routine "Trial_Break"-------
    continueRoutine = True
    # update component parameters for each repeat
    msg_3=f"{Acc_trials}/14"
    if Learning_loop.thisTrialN not in [13,27,41,69,83,97,125,139,153,181,195,209]:
        continueRoutine=False
    
    
    
    break_text.setText(msg_3)
    # keep track of which components have finished
    Trial_BreakComponents = [break_text, next3]
    for thisComponent in Trial_BreakComponents:
        thisComponent.tStart = None
        thisComponent.tStop = None
        thisComponent.tStartRefresh = None
        thisComponent.tStopRefresh = None
        if hasattr(thisComponent, 'status'):
            thisComponent.status = NOT_STARTED
    # reset timers
    t = 0
    _timeToFirstFrame = win.getFutureFlipTime(clock="now")
    Trial_BreakClock.reset(-_timeToFirstFrame)  # t0 is time of first possible flip
    frameN = -1
    
    # -------Run Routine "Trial_Break"-------
    while continueRoutine:
        # get current time
        t = Trial_BreakClock.getTime()
        tThisFlip = win.getFutureFlipTime(clock=Trial_BreakClock)
        tThisFlipGlobal = win.getFutureFlipTime(clock=None)
        frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
        # update/draw components on each frame
        feedback=visual.ImageStim(win=win, image='Stimuli/trial_feedback.png', pos=(0, 0))
        feedback.draw()
        if mouse2.isPressedIn(next3,buttons=[0]):
            continueRoutine=False 
        
        # *break_text* updates
        if break_text.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
            # keep track of start time/frame for later
            break_text.frameNStart = frameN  # exact frame index
            break_text.tStart = t  # local t and not account for scr refresh
            break_text.tStartRefresh = tThisFlipGlobal  # on global time
            win.timeOnFlip(break_text, 'tStartRefresh')  # time at next scr refresh
            break_text.setAutoDraw(True)
        
        # *next3* updates
        if next3.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
            # keep track of start time/frame for later
            next3.frameNStart = frameN  # exact frame index
            next3.tStart = t  # local t and not account for scr refresh
            next3.tStartRefresh = tThisFlipGlobal  # on global time
            win.timeOnFlip(next3, 'tStartRefresh')  # time at next scr refresh
            next3.setAutoDraw(True)
        
        # check for quit (typically the Esc key)
        if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
            core.quit()
        
        # check if all components have finished
        if not continueRoutine:  # a component has requested a forced-end of Routine
            break
        continueRoutine = False  # will revert to True if at least one component still running
        for thisComponent in Trial_BreakComponents:
            if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
                continueRoutine = True
                break  # at least one component has not yet finished
        
        # refresh the screen
        if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
            win.flip()
    
    # -------Ending Routine "Trial_Break"-------
    for thisComponent in Trial_BreakComponents:
        if hasattr(thisComponent, "setAutoDraw"):
            thisComponent.setAutoDraw(False)
    Learning_loop.addData('break_text.started', break_text.tStartRefresh)
    Learning_loop.addData('break_text.stopped', break_text.tStopRefresh)
    Learning_loop.addData('next3.started', next3.tStartRefresh)
    Learning_loop.addData('next3.stopped', next3.tStopRefresh)
    # the Routine "Trial_Break" was not non-slip safe, so reset the non-slip timer
    routineTimer.reset()
    
    # ------Prepare to start Routine "Block_Break"-------
    continueRoutine = True
    # update component parameters for each repeat
    eyetracker.stop_recording()
    # keep track of which components have finished
    Block_BreakComponents = [block_break_text, next_5]
    for thisComponent in Block_BreakComponents:
        thisComponent.tStart = None
        thisComponent.tStop = None
        thisComponent.tStartRefresh = None
        thisComponent.tStopRefresh = None
        if hasattr(thisComponent, 'status'):
            thisComponent.status = NOT_STARTED
    # reset timers
    t = 0
    _timeToFirstFrame = win.getFutureFlipTime(clock="now")
    Block_BreakClock.reset(-_timeToFirstFrame)  # t0 is time of first possible flip
    frameN = -1
    
    # -------Run Routine "Block_Break"-------
    while continueRoutine:
        # get current time
        t = Block_BreakClock.getTime()
        tThisFlip = win.getFutureFlipTime(clock=Block_BreakClock)
        tThisFlipGlobal = win.getFutureFlipTime(clock=None)
        frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
        # update/draw components on each frame
        if Learning_loop.thisN==55 or Learning_loop.thisN==111 or Learning_loop.thisN==167 or Learning_loop.thisN==223:
            continueRoutine=True
            if mouse.isPressedIn(next_5, buttons=[0]):
                continueRoutine=False
        else:
            continueRoutine=False
        
        if Learning_loop.thisN==55:
            map=visual.ImageStim(win=win, image='Stimuli/block1_feedback.png', pos=(0, 0))
            map.draw()
            msg_4=f"{Acc_blocks}/56"
        
        elif Learning_loop.thisN==111:
            map=visual.ImageStim(win=win, image='Stimuli/block2_feedback.png', pos=(0, 0))
            map.draw()
            msg_4=f"{Acc_blocks}/56"
        
        elif Learning_loop.thisN==167:
            map=visual.ImageStim(win=win, image='Stimuli/block3_feedback.png', pos=(0, 0))
            map.draw()
            msg_4=f"{Acc_blocks}/56"
        
        elif Learning_loop.thisN==223:
            map=visual.ImageStim(win=win, image='Stimuli/block4_feedback.png', pos=(0, 0))
            map.draw()
            msg_4=f"{Acc_blocks}/56"
        
        
        
        # *block_break_text* updates
        if block_break_text.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
            # keep track of start time/frame for later
            block_break_text.frameNStart = frameN  # exact frame index
            block_break_text.tStart = t  # local t and not account for scr refresh
            block_break_text.tStartRefresh = tThisFlipGlobal  # on global time
            win.timeOnFlip(block_break_text, 'tStartRefresh')  # time at next scr refresh
            block_break_text.setAutoDraw(True)
        if block_break_text.status == STARTED:  # only update if drawing
            block_break_text.setText(msg_4, log=False)
        
        # *next_5* updates
        if next_5.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
            # keep track of start time/frame for later
            next_5.frameNStart = frameN  # exact frame index
            next_5.tStart = t  # local t and not account for scr refresh
            next_5.tStartRefresh = tThisFlipGlobal  # on global time
            win.timeOnFlip(next_5, 'tStartRefresh')  # time at next scr refresh
            next_5.setAutoDraw(True)
        
        # check for quit (typically the Esc key)
        if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
            core.quit()
        
        # check if all components have finished
        if not continueRoutine:  # a component has requested a forced-end of Routine
            break
        continueRoutine = False  # will revert to True if at least one component still running
        for thisComponent in Block_BreakComponents:
            if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
                continueRoutine = True
                break  # at least one component has not yet finished
        
        # refresh the screen
        if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
            win.flip()
    
    # -------Ending Routine "Block_Break"-------
    for thisComponent in Block_BreakComponents:
        if hasattr(thisComponent, "setAutoDraw"):
            thisComponent.setAutoDraw(False)
    map=None
    msg=''
    eyetracker.start_recording()
    Learning_loop.addData('block_break_text.started', block_break_text.tStartRefresh)
    Learning_loop.addData('block_break_text.stopped', block_break_text.tStopRefresh)
    Learning_loop.addData('next_5.started', next_5.tStartRefresh)
    Learning_loop.addData('next_5.stopped', next_5.tStopRefresh)
    # the Routine "Block_Break" was not non-slip safe, so reset the non-slip timer
    routineTimer.reset()
    
    # ------Prepare to start Routine "gap"-------
    continueRoutine = True
    # update component parameters for each repeat
    # keep track of which components have finished
    gapComponents = []
    for thisComponent in gapComponents:
        thisComponent.tStart = None
        thisComponent.tStop = None
        thisComponent.tStartRefresh = None
        thisComponent.tStopRefresh = None
        if hasattr(thisComponent, 'status'):
            thisComponent.status = NOT_STARTED
    # reset timers
    t = 0
    _timeToFirstFrame = win.getFutureFlipTime(clock="now")
    gapClock.reset(-_timeToFirstFrame)  # t0 is time of first possible flip
    frameN = -1
    
    # -------Run Routine "gap"-------
    while continueRoutine:
        # get current time
        t = gapClock.getTime()
        tThisFlip = win.getFutureFlipTime(clock=gapClock)
        tThisFlipGlobal = win.getFutureFlipTime(clock=None)
        frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
        # update/draw components on each frame
        
        # check for quit (typically the Esc key)
        if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
            core.quit()
        
        # check if all components have finished
        if not continueRoutine:  # a component has requested a forced-end of Routine
            break
        continueRoutine = False  # will revert to True if at least one component still running
        for thisComponent in gapComponents:
            if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
                continueRoutine = True
                break  # at least one component has not yet finished
        
        # refresh the screen
        if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
            win.flip()
    
    # -------Ending Routine "gap"-------
    for thisComponent in gapComponents:
        if hasattr(thisComponent, "setAutoDraw"):
            thisComponent.setAutoDraw(False)
    if my_trial in [14,28,42,56,70,84,98,112,126,140,154,168,182,196,210,224]:
        Acc_trials=0
    
    if my_trial in [56,112,168,224]:
        Acc_blocks=0
    
    # the Routine "gap" was not non-slip safe, so reset the non-slip timer
    routineTimer.reset()
    thisExp.nextEntry()
    
# completed 4 repeats of 'Learning_loop'


# ------Prepare to start Routine "End"-------
continueRoutine = True
routineTimer.add(6.500000)
# update component parameters for each repeat
# keep track of which components have finished
EndComponents = [cloud, family]
for thisComponent in EndComponents:
    thisComponent.tStart = None
    thisComponent.tStop = None
    thisComponent.tStartRefresh = None
    thisComponent.tStopRefresh = None
    if hasattr(thisComponent, 'status'):
        thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
EndClock.reset(-_timeToFirstFrame)  # t0 is time of first possible flip
frameN = -1

# -------Run Routine "End"-------
while continueRoutine and routineTimer.getTime() > 0:
    # get current time
    t = EndClock.getTime()
    tThisFlip = win.getFutureFlipTime(clock=EndClock)
    tThisFlipGlobal = win.getFutureFlipTime(clock=None)
    frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
    # update/draw components on each frame
    
    # *cloud* updates
    if cloud.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
        # keep track of start time/frame for later
        cloud.frameNStart = frameN  # exact frame index
        cloud.tStart = t  # local t and not account for scr refresh
        cloud.tStartRefresh = tThisFlipGlobal  # on global time
        win.timeOnFlip(cloud, 'tStartRefresh')  # time at next scr refresh
        cloud.setAutoDraw(True)
    if cloud.status == STARTED:
        # is it time to stop? (based on global clock, using actual start)
        if tThisFlipGlobal > cloud.tStartRefresh + 3-frameTolerance:
            # keep track of stop time/frame for later
            cloud.tStop = t  # not accounting for scr refresh
            cloud.frameNStop = frameN  # exact frame index
            win.timeOnFlip(cloud, 'tStopRefresh')  # time at next scr refresh
            cloud.setAutoDraw(False)
    
    # *family* updates
    if family.status == NOT_STARTED and tThisFlip >= 3-frameTolerance:
        # keep track of start time/frame for later
        family.frameNStart = frameN  # exact frame index
        family.tStart = t  # local t and not account for scr refresh
        family.tStartRefresh = tThisFlipGlobal  # on global time
        win.timeOnFlip(family, 'tStartRefresh')  # time at next scr refresh
        family.setAutoDraw(True)
    if family.status == STARTED:
        # is it time to stop? (based on global clock, using actual start)
        if tThisFlipGlobal > family.tStartRefresh + 3.5-frameTolerance:
            # keep track of stop time/frame for later
            family.tStop = t  # not accounting for scr refresh
            family.frameNStop = frameN  # exact frame index
            win.timeOnFlip(family, 'tStopRefresh')  # time at next scr refresh
            family.setAutoDraw(False)
    
    # check for quit (typically the Esc key)
    if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
        core.quit()
    
    # check if all components have finished
    if not continueRoutine:  # a component has requested a forced-end of Routine
        break
    continueRoutine = False  # will revert to True if at least one component still running
    for thisComponent in EndComponents:
        if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
            continueRoutine = True
            break  # at least one component has not yet finished
    
    # refresh the screen
    if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
        win.flip()

# -------Ending Routine "End"-------
for thisComponent in EndComponents:
    if hasattr(thisComponent, "setAutoDraw"):
        thisComponent.setAutoDraw(False)
thisExp.addData('cloud.started', cloud.tStartRefresh)
thisExp.addData('cloud.stopped', cloud.tStopRefresh)
thisExp.addData('family.started', family.tStartRefresh)
thisExp.addData('family.stopped', family.tStopRefresh)
thisExp.addData("condition_file",condition)
eyetracker.stop_recording()
eyetracker.close()

# Flip one final time so any remaining win.callOnFlip() 
# and win.timeOnFlip() tasks get executed before quitting
win.flip()

# these shouldn't be strictly necessary (should auto-save)
thisExp.saveAsWideText(filename+'.csv')
thisExp.saveAsPickle(filename)
logging.flush()
# make sure everything is closed down
thisExp.abort()  # or data files will save again on exit
win.close()
core.quit()
