How to use the psychopy.event.getKeys function in psychopy

To help you get started, we’ve selected a few psychopy examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github jadref / buffer_bci / python / imaginedMovement_psychoPy / simple_imagined_movement_lastrun.py View on Github external
ISI_2.frameNStart = frameN  # exact frame index
                ISI_2.start(0.5)
            elif ISI_2.status == STARTED: #one frame should pass before updating params and completing
                ISI_2.complete() #finish the static period
            
            # 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 stimulusComponents:
                if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
                    continueRoutine = True
                    break  # at least one component has not yet finished
            
            # check for quit (the Esc key)
            if endExpNow or event.getKeys(keyList=["escape"]):
                core.quit()
            
            # refresh the screen
            if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
                win.flip()
        
        #-------Ending Routine "stimulus"-------
        for thisComponent in stimulusComponents:
            if hasattr(thisComponent, "setAutoDraw"):
                thisComponent.setAutoDraw(False)
        
        thisExp.nextEntry()
        
    # completed 1 repeats of 'stimuli'
github ingo-m / pyprf / pyprf / stimulus_presentation / code / stimulus.py View on Github external
def func_exit():
    """
    Check whether exit-keys have been pressed.

    The exit keys are 'e' and 'x'; they have to be pressed at the same time.
    This is supposed to make it less likely that the experiment is aborted
    by accident.
    """
    # Check keyboard, save output to temporary string:
    lstExit = event.getKeys(keyList=['e', 'x'], timeStamped=False)

    # Whether the list has the correct length (if nothing has happened lstExit
    # will have length zero):
    if len(lstExit) != 0:

        if ('e' in lstExit) and ('x' in lstExit):

            # Log end of experiment:
            logging.data('------Experiment aborted by user.------')

            # Make the mouse cursor visible again:
            event.Mouse(visible=True)

            # Close everyting:
            # objWin.close()
            core.quit()
github psychopy / psychopy / psychopy / demos / coder / timing / timeByFramesEx.py View on Github external
size=[0, 0.05], color='red', pos=[0, -0.9], autoLog=False)
myStim = visual.GratingStim(win, tex='sin', mask='gauss',
    size=300, sf=0.05, units='pix', autoLog=False)

# logging.console.setLevel(logging.INFO)  # uncomment to print log every frame

fliptimes = numpy.zeros(nIntervals + 1)

win.recordFrameIntervals = True
for frameN in range(nIntervals + 1):
    progBar.setSize([2.0 * frameN / nIntervals, 0.05])
    progBar.draw()
    myStim.setPhase(0.1, '+')
    myStim.setOri(1, '+')
    myStim.draw()
    if event.getKeys():
        print('stopped early')
        break
    win.logOnFlip(msg='frame=%i' % frameN, level=logging.EXP)
    fliptimes[frameN] = win.flip()

if disable_gc:
    gc.enable()
core.rush(False)

win.close()

# calculate some values
intervalsMS = pylab.array(win.frameIntervals) * 1000
m = pylab.mean(intervalsMS)
sd = pylab.std(intervalsMS)
# se=sd/pylab.sqrt(len(intervalsMS)) # for CI of the mean
github psychopy / psychopy / psychopy / demos / coder / stimuli / starField.py View on Github external
from psychopy.tools.coordinatetools import pol2cart
import numpy

nDots = 500
maxSpeed = 0.02
dotSize = .0075

dotsTheta = numpy.random.rand(nDots) * 360
dotsRadius = (numpy.random.rand(nDots) ** 0.5) * 2
speed = numpy.random.rand(nDots) * maxSpeed

win = visual.Window([800, 600], color=[-1, -1, -1])
dots = visual.ElementArrayStim(win, elementTex=None, elementMask='circle',
    nElements=nDots, sizes=dotSize)

while not event.getKeys():
    # update radius
    dotsRadius = (dotsRadius + speed)
    # random radius where radius too large
    outFieldDots = (dotsRadius >= 2.0)
    dotsRadius[outFieldDots] = numpy.random.rand(sum(outFieldDots)) * 2.0

    dotsX, dotsY = pol2cart(dotsTheta, dotsRadius)
    dotsX *=  0.75  # to account for wider aspect ratio
    dots.xys = numpy.array([dotsX, dotsY]).transpose()
    dots.draw()

    win.flip()

win.close()
core.quit()
github psychopy / psychopy / psychopy / demos / coder / stimuli / gabor.py View on Github external
# create a window to draw in
win = visual.Window([400, 400.0], allowGUI=False)

# INITIALISE SOME STIMULI
gabor = visual.GratingStim(win, tex="sin", mask="gauss", texRes=256, 
           size=[1.0, 1.0], sf=[4, 0], ori = 0, name='gabor1')
gabor.autoDraw = True
message = visual.TextStim(win, pos=(0.0, -0.9), text='Hit Q to quit')
trialClock = core.Clock()

# repeat drawing for each frame
while trialClock.getTime() < 20: 
    gabor.phase += 0.01
    message.draw()
    # handle key presses each frame
    if event.getKeys(keyList=['escape', 'q']):
        win.close()
        core.quit()

    win.flip()

win.close()
core.quit()
github psychopy / psychopy / psychopy / tools / wizard.py View on Github external
bestDots = starting  # this might over-estimate the actual best
        dotCount = starting
        count = visual.TextStim(win, text=str(dotCount), autoLog=False)
        count.draw()
        win.flip()
        dots = visual.DotStim(win, color=(1.0, 1.0, 1.0), nDots=dotCount,
                              fieldShape=fieldShape, autoLog=False)
        win.fps()  # reset
        frameCount = 0
        while True:
            dots.draw()
            win.flip()
            frameCount += 1
            if frameCount > maxFrame:
                fps = win.fps()  # get frames per sec
                if len(event.getKeys(['escape'])):
                    sys.exit()
                if (fps < baseline * 0.6) or (dotCount > 5000):
                    # only break when start dropping a LOT of frames (80% or
                    # more) or exceeded 5,000 dots
                    dotsInfo.append(
                        ('dots_' + fieldShape, str(bestDots), '', False))
                    break
                frames_dropped = round(baseline - fps)  # can be negative
                if frames_dropped < 1:  # can be negative
                    # only set best if no dropped frames:
                    bestDots = dotCount
                # but do allow to continue in case do better with more dots:
                dotCount += 100
                # show the dot count:
                count.setText(str(dotCount), log=False)
                count.draw()
github jadref / buffer_bci / python / imaginedMovement_psychoPy / simple_imagined_movement.py View on Github external
def show_instr(instructionText):
    instruction = visual.TextStim(mywin, text=instructionText,color=(1,1,1),height = 25) 
    instruction.draw()
    mywin.flip()
    # wait for key-press
    allKeys = event.getKeys()
    while len(allKeys)==0:
        allKeys = event.getKeys()
github psychopy / psychopy / psychopy / demos / coder / stimuli / stim3d.py View on Github external
specularColor=(0, 0, 0), shininess=125.0)

# load a diffuse texture
boxStim.material.diffuseTexture = createTexImage2dFromFile('face.jpg')

# set the box 3 meters away from the observer by editing the stimuli's rigid
# body class
boxStim.thePose.pos = (0, 0, -3)

# text to overlay
message = visual.TextStim(
    win, text='Any key to quit', pos=(0, -0.8), units='norm')

angle = 0.0

while not event.getKeys():
    win.setPerspectiveView()  # set the projection, must be done every frame

    win.useLights = True  # enable lighting

    # spin the stimulus by angle
    boxStim.thePose.setOriAxisAngle((0, 1, 1), angle)

    # draw the stimulus
    boxStim.draw()

    win.resetEyeTransform()  # reset the transformation to draw 2D stimuli
    # disable lights for 2D stimuli, or else colors will be modulated
    win.useLights = False
    message.draw()

    win.flip()
github hsogo / psychopy_tobii_controller / psychopy_tobii_controller / __init__.py View on Github external
"""
        
        clock = psychopy.core.Clock()
        for point_index in range(len(self.calibration_points)):
            x, y = self.get_tobii_pos(self.calibration_points[point_index])
            self.calibration_target_dot.setPos(self.calibration_points[point_index])
            self.calibration_target_disc.setPos(self.calibration_points[point_index])
            
            clock.reset()
            current_time = clock.getTime()
            while current_time < self.move_duration:
                self.calibration_target_disc.setRadius(
                    (self.calibration_target_dot_size*2.0-self.calibration_target_disc_size)/ \
                     self.move_duration*current_time+self.calibration_target_disc_size
                    )
                psychopy.event.getKeys()
                self.calibration_target_disc.draw()
                self.calibration_target_dot.draw()
                self.win.flip()
                current_time = clock.getTime()
            self.calibration.collect_data(x, y)
github psychopy / psychopy / psychopy / monitors / getLumSeries.py View on Github external
units='norm')

    # stay like this until key press (or 30secs has passed)
    waitClock = core.Clock()
    tRemain = 30
    msg = ("Point the photometer at the central white bar. "
           "Hit a key when ready (or wait %iss)")
    while tRemain > 0:
        tRemain = 30 - waitClock.getTime()
        instructions = msg % tRemain
        backPatch.draw()
        testPatch.draw()
        message.setText(instructions)
        message.draw()
        myWin.flip()
        if len(psychopy.event.getKeys()):
            break  # we got a keypress so move on

    if autoMode != 'semi':
        message.setText('Q to quit at any time')
    else:
        message.setText('Spacebar for next patch')

    # LS100 likes to take at least one bright measurement
    if havePhotom and photometer.type == 'LS100':
        junk = photometer.getLum()

    # what are the test values of luminance
    if (type(lumLevels) is int) or (type(lumLevels) is float):
        toTest = DACrange(lumLevels)
    else:
        toTest = numpy.asarray(lumLevels)