#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This experiment was created using PsychoPy3 Experiment Builder (v2020.2.8),
    on fevereiro 09, 2021, at 23:06
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
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
from datetime import datetime


# 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.2.8'
expName = 'SaccadicMovement'  # from the Builder filename that created this script
expInfo = {'participant': '', 'session': '001'}
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
expInfo['time'] = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")
expInfo['epoch_time_start'] = core.getAbsTime()


# 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\\Mariana\\Desktop\\STIMULUS\\AntiSaccadicMovement.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 after the window creation

# Setup the Window
win = visual.Window(
    size=(1024, 768), fullscr=True, screen=0, 
    winType='pyglet', allowGUI=False, allowStencil=False,
    monitor='testMonitor', color=[0,0,0], colorSpace='rgb',
    blendMode='avg', useFBO=True, 
    units='height')
# 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"
WelcomeClock = core.Clock()
polyWelcome = visual.Rect(
    win=win, name='polyWelcome',
    width=(2, 2)[0], height=(2, 2)[1],
    ori=0, pos=(0, 0),
    lineWidth=1, 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)
textWelcome = visual.TextStim(win=win, name='textWelcome',
    text=None,
    font='Arial',
    pos=(0, 0), height=0.07, wrapWidth=None, ori=0, 
    color='white', colorSpace='rgb', opacity=1, 
    languageStyle='LTR',
    depth=-1.0);
keyWelcome = keyboard.Keyboard()

# Initialize components for Routine "blank500"
blank500Clock = core.Clock()
polyBlank = visual.Rect(
    win=win, name='polyBlank',
    width=(2, 2)[0], height=(2, 2)[1],
    ori=0, pos=(0, 0),
    lineWidth=1, 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 "Instructions_AntiSaccadic"
Instructions_AntiSaccadicClock = core.Clock()
polyAntiSacc = visual.Rect(
    win=win, name='polyAntiSacc',
    width=(2, 2)[0], height=(2, 2)[1],
    ori=0, pos=(0, 0),
    lineWidth=1, lineColor=[1,1,1], lineColorSpace='rgb',
    fillColor=[-1.000,-1.000,-1.000], fillColorSpace='rgb',
    opacity=1, depth=0.0, interpolate=True)
Instrucctions_AntiSaccadic = visual.TextStim(win=win, name='Instrucctions_AntiSaccadic',
    text='Anti Saccadic test',
    font='Arial',
    pos=(0, 0), height=0.08, wrapWidth=None, ori=0, 
    color='white', colorSpace='rgb', opacity=1, 
    languageStyle='LTR',
    depth=-1.0);
key_InstructionsAntisaccadic = keyboard.Keyboard()

# Initialize components for Routine "blank500"
blank500Clock = core.Clock()
polyBlank = visual.Rect(
    win=win, name='polyBlank',
    width=(2, 2)[0], height=(2, 2)[1],
    ori=0, pos=(0, 0),
    lineWidth=1, 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 "SaccadicMovement"
SaccadicMovementClock = core.Clock()
polyBallBlank = visual.Rect(
    win=win, name='polyBallBlank',
    width=(2, 2)[0], height=(2, 2)[1],
    ori=0, pos=(0, 0),
    lineWidth=1, 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)
polyBall = visual.Polygon(
    win=win, name='polyBall',
    edges=50, size=(0.05, 0.05),
    ori=0, pos=[0,0],
    lineWidth=1, lineColor=[-1.000,0.004,1.000], lineColorSpace='rgb',
    fillColor=[-1.000,0.004,1.000], fillColorSpace='rgb',
    opacity=1, depth=-1.0, interpolate=True)

# Initialize components for Routine "blank500"
blank500Clock = core.Clock()
polyBlank = visual.Rect(
    win=win, name='polyBlank',
    width=(2, 2)[0], height=(2, 2)[1],
    ori=0, pos=(0, 0),
    lineWidth=1, 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 "EndScreen"
EndScreenClock = core.Clock()
polyEndBlank = visual.Rect(
    win=win, name='polyEndBlank',
    width=(2, 2)[0], height=(2, 2)[1],
    ori=0, pos=(0, 0),
    lineWidth=1, 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)
textEndScreen = visual.TextStim(win=win, name='textEndScreen',
    text='¡Fin de la prueba!\n\n¡Muchas gracias por su participación!',
    font='Arial',
    pos=(0, 0), height=0.1, wrapWidth=None, ori=0, 
    color='white', colorSpace='rgb', opacity=1, 
    languageStyle='LTR',
    depth=-1.0);
key_END = keyboard.Keyboard()

# 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"-------
continueRoutine = True
# update component parameters for each repeat
keyWelcome.keys = []
keyWelcome.rt = []
_keyWelcome_allKeys = []
# keep track of which components have finished
WelcomeComponents = [polyWelcome, textWelcome, keyWelcome]
for thisComponent in WelcomeComponents:
    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")
WelcomeClock.reset(-_timeToFirstFrame)  # t0 is time of first possible flip
frameN = -1

# -------Run Routine "Welcome"-------
while continueRoutine:
    # get current time
    t = WelcomeClock.getTime()
    tThisFlip = win.getFutureFlipTime(clock=WelcomeClock)
    tThisFlipGlobal = win.getFutureFlipTime(clock=None)
    frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
    # update/draw components on each frame
    
    # *polyWelcome* updates
    if polyWelcome.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
        # keep track of start time/frame for later
        polyWelcome.frameNStart = frameN  # exact frame index
        polyWelcome.tStart = t  # local t and not account for scr refresh
        polyWelcome.tStartRefresh = tThisFlipGlobal  # on global time
        win.timeOnFlip(polyWelcome, 'tStartRefresh')  # time at next scr refresh
        polyWelcome.setAutoDraw(True)
    
    # *textWelcome* updates
    if textWelcome.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
        # keep track of start time/frame for later
        textWelcome.frameNStart = frameN  # exact frame index
        textWelcome.tStart = t  # local t and not account for scr refresh
        textWelcome.tStartRefresh = tThisFlipGlobal  # on global time
        win.timeOnFlip(textWelcome, 'tStartRefresh')  # time at next scr refresh
        textWelcome.setAutoDraw(True)
    
    # *keyWelcome* updates
    waitOnFlip = False
    if keyWelcome.status == NOT_STARTED and tThisFlip >= 1.0-frameTolerance:
        # keep track of start time/frame for later
        keyWelcome.frameNStart = frameN  # exact frame index
        keyWelcome.tStart = t  # local t and not account for scr refresh
        keyWelcome.tStartRefresh = tThisFlipGlobal  # on global time
        win.timeOnFlip(keyWelcome, 'tStartRefresh')  # time at next scr refresh
        keyWelcome.status = STARTED
        # keyboard checking is just starting
        waitOnFlip = True
        win.callOnFlip(keyWelcome.clock.reset)  # t=0 on next screen flip
        win.callOnFlip(keyWelcome.clearEvents, eventType='keyboard')  # clear events on next screen flip
    if keyWelcome.status == STARTED and not waitOnFlip:
        theseKeys = keyWelcome.getKeys(keyList=['left', 'right', 'space'], waitRelease=False)
        _keyWelcome_allKeys.extend(theseKeys)
        if len(_keyWelcome_allKeys):
            keyWelcome.keys = _keyWelcome_allKeys[-1].name  # just the last key pressed
            keyWelcome.rt = _keyWelcome_allKeys[-1].rt
            # a response ends the routine
            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 WelcomeComponents:
        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"-------
for thisComponent in WelcomeComponents:
    if hasattr(thisComponent, "setAutoDraw"):
        thisComponent.setAutoDraw(False)
thisExp.addData('polyWelcome.started', polyWelcome.tStartRefresh)
thisExp.addData('polyWelcome.stopped', polyWelcome.tStopRefresh)
thisExp.addData('textWelcome.started', textWelcome.tStartRefresh)
thisExp.addData('textWelcome.stopped', textWelcome.tStopRefresh)
# check responses
if keyWelcome.keys in ['', [], None]:  # No response was made
    keyWelcome.keys = None
thisExp.addData('keyWelcome.keys',keyWelcome.keys)
if keyWelcome.keys != None:  # we had a response
    thisExp.addData('keyWelcome.rt', keyWelcome.rt)
thisExp.addData('keyWelcome.started', keyWelcome.tStartRefresh)
thisExp.addData('keyWelcome.stopped', keyWelcome.tStopRefresh)
thisExp.nextEntry()
# the Routine "Welcome" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()

# ------Prepare to start Routine "blank500"-------
continueRoutine = True
routineTimer.add(0.500000)
# update component parameters for each repeat
# keep track of which components have finished
blank500Components = [polyBlank]
for thisComponent in blank500Components:
    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")
blank500Clock.reset(-_timeToFirstFrame)  # t0 is time of first possible flip
frameN = -1

# -------Run Routine "blank500"-------
while continueRoutine and routineTimer.getTime() > 0:
    # get current time
    t = blank500Clock.getTime()
    tThisFlip = win.getFutureFlipTime(clock=blank500Clock)
    tThisFlipGlobal = win.getFutureFlipTime(clock=None)
    frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
    # update/draw components on each frame
    
    # *polyBlank* updates
    if polyBlank.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
        # keep track of start time/frame for later
        polyBlank.frameNStart = frameN  # exact frame index
        polyBlank.tStart = t  # local t and not account for scr refresh
        polyBlank.tStartRefresh = tThisFlipGlobal  # on global time
        win.timeOnFlip(polyBlank, 'tStartRefresh')  # time at next scr refresh
        polyBlank.setAutoDraw(True)
    if polyBlank.status == STARTED:
        # is it time to stop? (based on global clock, using actual start)
        if tThisFlipGlobal > polyBlank.tStartRefresh + 0.5-frameTolerance:
            # keep track of stop time/frame for later
            polyBlank.tStop = t  # not accounting for scr refresh
            polyBlank.frameNStop = frameN  # exact frame index
            win.timeOnFlip(polyBlank, 'tStopRefresh')  # time at next scr refresh
            polyBlank.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 blank500Components:
        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 "blank500"-------
for thisComponent in blank500Components:
    if hasattr(thisComponent, "setAutoDraw"):
        thisComponent.setAutoDraw(False)
thisExp.addData('polyBlank.started', polyBlank.tStartRefresh)
thisExp.addData('polyBlank.stopped', polyBlank.tStopRefresh)

# ------Prepare to start Routine "Instructions_AntiSaccadic"-------
continueRoutine = True
# update component parameters for each repeat
key_InstructionsAntisaccadic.keys = []
key_InstructionsAntisaccadic.rt = []
_key_InstructionsAntisaccadic_allKeys = []
# keep track of which components have finished
Instructions_AntiSaccadicComponents = [polyAntiSacc, Instrucctions_AntiSaccadic, key_InstructionsAntisaccadic]
for thisComponent in Instructions_AntiSaccadicComponents:
    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")
Instructions_AntiSaccadicClock.reset(-_timeToFirstFrame)  # t0 is time of first possible flip
frameN = -1

# -------Run Routine "Instructions_AntiSaccadic"-------
while continueRoutine:
    # get current time
    t = Instructions_AntiSaccadicClock.getTime()
    tThisFlip = win.getFutureFlipTime(clock=Instructions_AntiSaccadicClock)
    tThisFlipGlobal = win.getFutureFlipTime(clock=None)
    frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
    # update/draw components on each frame
    
    # *polyAntiSacc* updates
    if polyAntiSacc.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
        # keep track of start time/frame for later
        polyAntiSacc.frameNStart = frameN  # exact frame index
        polyAntiSacc.tStart = t  # local t and not account for scr refresh
        polyAntiSacc.tStartRefresh = tThisFlipGlobal  # on global time
        win.timeOnFlip(polyAntiSacc, 'tStartRefresh')  # time at next scr refresh
        polyAntiSacc.setAutoDraw(True)
    
    # *Instrucctions_AntiSaccadic* updates
    if Instrucctions_AntiSaccadic.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
        # keep track of start time/frame for later
        Instrucctions_AntiSaccadic.frameNStart = frameN  # exact frame index
        Instrucctions_AntiSaccadic.tStart = t  # local t and not account for scr refresh
        Instrucctions_AntiSaccadic.tStartRefresh = tThisFlipGlobal  # on global time
        win.timeOnFlip(Instrucctions_AntiSaccadic, 'tStartRefresh')  # time at next scr refresh
        Instrucctions_AntiSaccadic.setAutoDraw(True)
    
    # *key_InstructionsAntisaccadic* updates
    waitOnFlip = False
    if key_InstructionsAntisaccadic.status == NOT_STARTED and tThisFlip >= 1.0-frameTolerance:
        # keep track of start time/frame for later
        key_InstructionsAntisaccadic.frameNStart = frameN  # exact frame index
        key_InstructionsAntisaccadic.tStart = t  # local t and not account for scr refresh
        key_InstructionsAntisaccadic.tStartRefresh = tThisFlipGlobal  # on global time
        win.timeOnFlip(key_InstructionsAntisaccadic, 'tStartRefresh')  # time at next scr refresh
        key_InstructionsAntisaccadic.status = STARTED
        # keyboard checking is just starting
        waitOnFlip = True
        win.callOnFlip(key_InstructionsAntisaccadic.clock.reset)  # t=0 on next screen flip
        win.callOnFlip(key_InstructionsAntisaccadic.clearEvents, eventType='keyboard')  # clear events on next screen flip
    if key_InstructionsAntisaccadic.status == STARTED and not waitOnFlip:
        theseKeys = key_InstructionsAntisaccadic.getKeys(keyList=['left', 'right', 'space'], waitRelease=False)
        _key_InstructionsAntisaccadic_allKeys.extend(theseKeys)
        if len(_key_InstructionsAntisaccadic_allKeys):
            key_InstructionsAntisaccadic.keys = _key_InstructionsAntisaccadic_allKeys[-1].name  # just the last key pressed
            key_InstructionsAntisaccadic.rt = _key_InstructionsAntisaccadic_allKeys[-1].rt
            # a response ends the routine
            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 Instructions_AntiSaccadicComponents:
        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 "Instructions_AntiSaccadic"-------
for thisComponent in Instructions_AntiSaccadicComponents:
    if hasattr(thisComponent, "setAutoDraw"):
        thisComponent.setAutoDraw(False)
thisExp.addData('polyAntiSacc.started', polyAntiSacc.tStartRefresh)
thisExp.addData('polyAntiSacc.stopped', polyAntiSacc.tStopRefresh)
thisExp.addData('Instrucctions_AntiSaccadic.started', Instrucctions_AntiSaccadic.tStartRefresh)
thisExp.addData('Instrucctions_AntiSaccadic.stopped', Instrucctions_AntiSaccadic.tStopRefresh)
# check responses
if key_InstructionsAntisaccadic.keys in ['', [], None]:  # No response was made
    key_InstructionsAntisaccadic.keys = None
thisExp.addData('key_InstructionsAntisaccadic.keys',key_InstructionsAntisaccadic.keys)
if key_InstructionsAntisaccadic.keys != None:  # we had a response
    thisExp.addData('key_InstructionsAntisaccadic.rt', key_InstructionsAntisaccadic.rt)
thisExp.addData('key_InstructionsAntisaccadic.started', key_InstructionsAntisaccadic.tStartRefresh)
thisExp.addData('key_InstructionsAntisaccadic.stopped', key_InstructionsAntisaccadic.tStopRefresh)
thisExp.nextEntry()
# the Routine "Instructions_AntiSaccadic" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()

# ------Prepare to start Routine "blank500"-------
continueRoutine = True
routineTimer.add(0.500000)
# update component parameters for each repeat
# keep track of which components have finished
blank500Components = [polyBlank]
for thisComponent in blank500Components:
    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")
blank500Clock.reset(-_timeToFirstFrame)  # t0 is time of first possible flip
frameN = -1

# -------Run Routine "blank500"-------
while continueRoutine and routineTimer.getTime() > 0:
    # get current time
    t = blank500Clock.getTime()
    tThisFlip = win.getFutureFlipTime(clock=blank500Clock)
    tThisFlipGlobal = win.getFutureFlipTime(clock=None)
    frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
    # update/draw components on each frame
    
    # *polyBlank* updates
    if polyBlank.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
        # keep track of start time/frame for later
        polyBlank.frameNStart = frameN  # exact frame index
        polyBlank.tStart = t  # local t and not account for scr refresh
        polyBlank.tStartRefresh = tThisFlipGlobal  # on global time
        win.timeOnFlip(polyBlank, 'tStartRefresh')  # time at next scr refresh
        polyBlank.setAutoDraw(True)
    if polyBlank.status == STARTED:
        # is it time to stop? (based on global clock, using actual start)
        if tThisFlipGlobal > polyBlank.tStartRefresh + 0.5-frameTolerance:
            # keep track of stop time/frame for later
            polyBlank.tStop = t  # not accounting for scr refresh
            polyBlank.frameNStop = frameN  # exact frame index
            win.timeOnFlip(polyBlank, 'tStopRefresh')  # time at next scr refresh
            polyBlank.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 blank500Components:
        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 "blank500"-------
for thisComponent in blank500Components:
    if hasattr(thisComponent, "setAutoDraw"):
        thisComponent.setAutoDraw(False)
thisExp.addData('polyBlank.started', polyBlank.tStartRefresh)
thisExp.addData('polyBlank.stopped', polyBlank.tStopRefresh)

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

for thisTrialsSaccadic in trialsSaccadic:
    currentLoop = trialsSaccadic
    # abbreviate parameter names if possible (e.g. rgb = thisTrialsSaccadic.rgb)
    if thisTrialsSaccadic != None:
        for paramName in thisTrialsSaccadic:
            exec('{} = thisTrialsSaccadic[paramName]'.format(paramName))
    
    # ------Prepare to start Routine "SaccadicMovement"-------
    continueRoutine = True
    routineTimer.add(3.000000)
    # update component parameters for each repeat
    polyBall.setPos(BallPosition)
    # keep track of which components have finished
    SaccadicMovementComponents = [polyBallBlank, polyBall]
    for thisComponent in SaccadicMovementComponents:
        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")
    SaccadicMovementClock.reset(-_timeToFirstFrame)  # t0 is time of first possible flip
    frameN = -1
    
    # -------Run Routine "SaccadicMovement"-------
    while continueRoutine and routineTimer.getTime() > 0:
        # get current time
        t = SaccadicMovementClock.getTime()
        tThisFlip = win.getFutureFlipTime(clock=SaccadicMovementClock)
        tThisFlipGlobal = win.getFutureFlipTime(clock=None)
        frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
        # update/draw components on each frame
        
        # *polyBallBlank* updates
        if polyBallBlank.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
            # keep track of start time/frame for later
            polyBallBlank.frameNStart = frameN  # exact frame index
            polyBallBlank.tStart = t  # local t and not account for scr refresh
            polyBallBlank.tStartRefresh = tThisFlipGlobal  # on global time
            win.timeOnFlip(polyBallBlank, 'tStartRefresh')  # time at next scr refresh
            polyBallBlank.setAutoDraw(True)
        if polyBallBlank.status == STARTED:
            # is it time to stop? (based on global clock, using actual start)
            if tThisFlipGlobal > polyBallBlank.tStartRefresh + 3-frameTolerance:
                # keep track of stop time/frame for later
                polyBallBlank.tStop = t  # not accounting for scr refresh
                polyBallBlank.frameNStop = frameN  # exact frame index
                win.timeOnFlip(polyBallBlank, 'tStopRefresh')  # time at next scr refresh
                polyBallBlank.setAutoDraw(False)
        
        # *polyBall* updates
        if polyBall.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
            # keep track of start time/frame for later
            polyBall.frameNStart = frameN  # exact frame index
            polyBall.tStart = t  # local t and not account for scr refresh
            polyBall.tStartRefresh = tThisFlipGlobal  # on global time
            win.timeOnFlip(polyBall, 'tStartRefresh')  # time at next scr refresh
            polyBall.setAutoDraw(True)
        if polyBall.status == STARTED:
            # is it time to stop? (based on global clock, using actual start)
            if tThisFlipGlobal > polyBall.tStartRefresh + 3-frameTolerance:
                # keep track of stop time/frame for later
                polyBall.tStop = t  # not accounting for scr refresh
                polyBall.frameNStop = frameN  # exact frame index
                win.timeOnFlip(polyBall, 'tStopRefresh')  # time at next scr refresh
                polyBall.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 SaccadicMovementComponents:
            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 "SaccadicMovement"-------
    for thisComponent in SaccadicMovementComponents:
        if hasattr(thisComponent, "setAutoDraw"):
            thisComponent.setAutoDraw(False)
    trialsSaccadic.addData('polyBallBlank.started', polyBallBlank.tStartRefresh)
    trialsSaccadic.addData('polyBallBlank.stopped', polyBallBlank.tStopRefresh)
    trialsSaccadic.addData('polyBall.started', polyBall.tStartRefresh)
    trialsSaccadic.addData('polyBall.stopped', polyBall.tStopRefresh)
    thisExp.nextEntry()
    
# completed 1 repeats of 'trialsSaccadic'


# ------Prepare to start Routine "blank500"-------
continueRoutine = True
routineTimer.add(0.500000)
# update component parameters for each repeat
# keep track of which components have finished
blank500Components = [polyBlank]
for thisComponent in blank500Components:
    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")
blank500Clock.reset(-_timeToFirstFrame)  # t0 is time of first possible flip
frameN = -1

# -------Run Routine "blank500"-------
while continueRoutine and routineTimer.getTime() > 0:
    # get current time
    t = blank500Clock.getTime()
    tThisFlip = win.getFutureFlipTime(clock=blank500Clock)
    tThisFlipGlobal = win.getFutureFlipTime(clock=None)
    frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
    # update/draw components on each frame
    
    # *polyBlank* updates
    if polyBlank.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
        # keep track of start time/frame for later
        polyBlank.frameNStart = frameN  # exact frame index
        polyBlank.tStart = t  # local t and not account for scr refresh
        polyBlank.tStartRefresh = tThisFlipGlobal  # on global time
        win.timeOnFlip(polyBlank, 'tStartRefresh')  # time at next scr refresh
        polyBlank.setAutoDraw(True)
    if polyBlank.status == STARTED:
        # is it time to stop? (based on global clock, using actual start)
        if tThisFlipGlobal > polyBlank.tStartRefresh + 0.5-frameTolerance:
            # keep track of stop time/frame for later
            polyBlank.tStop = t  # not accounting for scr refresh
            polyBlank.frameNStop = frameN  # exact frame index
            win.timeOnFlip(polyBlank, 'tStopRefresh')  # time at next scr refresh
            polyBlank.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 blank500Components:
        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 "blank500"-------
for thisComponent in blank500Components:
    if hasattr(thisComponent, "setAutoDraw"):
        thisComponent.setAutoDraw(False)
thisExp.addData('polyBlank.started', polyBlank.tStartRefresh)
thisExp.addData('polyBlank.stopped', polyBlank.tStopRefresh)

# ------Prepare to start Routine "EndScreen"-------
continueRoutine = True
routineTimer.add(20.000000)
# update component parameters for each repeat
key_END.keys = []
key_END.rt = []
_key_END_allKeys = []
# keep track of which components have finished
EndScreenComponents = [polyEndBlank, textEndScreen, key_END]
for thisComponent in EndScreenComponents:
    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")
EndScreenClock.reset(-_timeToFirstFrame)  # t0 is time of first possible flip
frameN = -1

# -------Run Routine "EndScreen"-------
while continueRoutine and routineTimer.getTime() > 0:
    # get current time
    t = EndScreenClock.getTime()
    tThisFlip = win.getFutureFlipTime(clock=EndScreenClock)
    tThisFlipGlobal = win.getFutureFlipTime(clock=None)
    frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
    # update/draw components on each frame
    
    # *polyEndBlank* updates
    if polyEndBlank.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
        # keep track of start time/frame for later
        polyEndBlank.frameNStart = frameN  # exact frame index
        polyEndBlank.tStart = t  # local t and not account for scr refresh
        polyEndBlank.tStartRefresh = tThisFlipGlobal  # on global time
        win.timeOnFlip(polyEndBlank, 'tStartRefresh')  # time at next scr refresh
        polyEndBlank.setAutoDraw(True)
    if polyEndBlank.status == STARTED:
        # is it time to stop? (based on global clock, using actual start)
        if tThisFlipGlobal > polyEndBlank.tStartRefresh + 20-frameTolerance:
            # keep track of stop time/frame for later
            polyEndBlank.tStop = t  # not accounting for scr refresh
            polyEndBlank.frameNStop = frameN  # exact frame index
            win.timeOnFlip(polyEndBlank, 'tStopRefresh')  # time at next scr refresh
            polyEndBlank.setAutoDraw(False)
    
    # *textEndScreen* updates
    if textEndScreen.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
        # keep track of start time/frame for later
        textEndScreen.frameNStart = frameN  # exact frame index
        textEndScreen.tStart = t  # local t and not account for scr refresh
        textEndScreen.tStartRefresh = tThisFlipGlobal  # on global time
        win.timeOnFlip(textEndScreen, 'tStartRefresh')  # time at next scr refresh
        textEndScreen.setAutoDraw(True)
    if textEndScreen.status == STARTED:
        # is it time to stop? (based on global clock, using actual start)
        if tThisFlipGlobal > textEndScreen.tStartRefresh + 20-frameTolerance:
            # keep track of stop time/frame for later
            textEndScreen.tStop = t  # not accounting for scr refresh
            textEndScreen.frameNStop = frameN  # exact frame index
            win.timeOnFlip(textEndScreen, 'tStopRefresh')  # time at next scr refresh
            textEndScreen.setAutoDraw(False)
    
    # *key_END* updates
    waitOnFlip = False
    if key_END.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
        # keep track of start time/frame for later
        key_END.frameNStart = frameN  # exact frame index
        key_END.tStart = t  # local t and not account for scr refresh
        key_END.tStartRefresh = tThisFlipGlobal  # on global time
        win.timeOnFlip(key_END, 'tStartRefresh')  # time at next scr refresh
        key_END.status = STARTED
        # keyboard checking is just starting
        waitOnFlip = True
        win.callOnFlip(key_END.clock.reset)  # t=0 on next screen flip
        win.callOnFlip(key_END.clearEvents, eventType='keyboard')  # clear events on next screen flip
    if key_END.status == STARTED:
        # is it time to stop? (based on global clock, using actual start)
        if tThisFlipGlobal > key_END.tStartRefresh + 20-frameTolerance:
            # keep track of stop time/frame for later
            key_END.tStop = t  # not accounting for scr refresh
            key_END.frameNStop = frameN  # exact frame index
            win.timeOnFlip(key_END, 'tStopRefresh')  # time at next scr refresh
            key_END.status = FINISHED
    if key_END.status == STARTED and not waitOnFlip:
        theseKeys = key_END.getKeys(keyList=['left', 'right', 'space'], waitRelease=False)
        _key_END_allKeys.extend(theseKeys)
        if len(_key_END_allKeys):
            key_END.keys = _key_END_allKeys[-1].name  # just the last key pressed
            key_END.rt = _key_END_allKeys[-1].rt
            # a response ends the routine
            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 EndScreenComponents:
        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 "EndScreen"-------
for thisComponent in EndScreenComponents:
    if hasattr(thisComponent, "setAutoDraw"):
        thisComponent.setAutoDraw(False)
thisExp.addData('polyEndBlank.started', polyEndBlank.tStartRefresh)
thisExp.addData('polyEndBlank.stopped', polyEndBlank.tStopRefresh)
thisExp.addData('textEndScreen.started', textEndScreen.tStartRefresh)
thisExp.addData('textEndScreen.stopped', textEndScreen.tStopRefresh)
# check responses
if key_END.keys in ['', [], None]:  # No response was made
    key_END.keys = None
thisExp.addData('key_END.keys',key_END.keys)
if key_END.keys != None:  # we had a response
    thisExp.addData('key_END.rt', key_END.rt)
thisExp.addData('key_END.started', key_END.tStartRefresh)
thisExp.addData('key_END.stopped', key_END.tStopRefresh)
thisExp.nextEntry()

# 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', delim='auto')
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()
