• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python event.getKeys函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中psychopy.event.getKeys函数的典型用法代码示例。如果您正苦于以下问题:Python getKeys函数的具体用法?Python getKeys怎么用?Python getKeys使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了getKeys函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: runRT

def runRT(window,ask,test,language,preferred_hand,exp):
    try:
        while True:
            ask(lookup[test][language][preferred_hand])
            response = ask(practiceLookup[language])
            if event.getKeys(keyList=['escape', 'q']):
                core.quit()
            if 'r' in response:
                print 'r pressed'
                continue
            if 'space' in response:
                break
            if event.getKeys(keyList=['s']):
                print "Skipped experiment"
                return
            
        getReady = lookupGetReady[language]
        error = lookupError[language]
        wrongkey = lookupwrongKey[language]

        score=1
        while score != 0:
            score = run(window,clock, ask, error,getReady,wrongkey,language, exp,practice=True)
            print score
        #Run experiment
        run(window,clock, ask, error,getReady,wrongkey,language,exp)
    except KeyboardInterrupt:
        raise
        core.quit()
开发者ID:MaisonLogicielLibre,项目名称:CogSciProject-master,代码行数:29,代码来源:RT_experiment.py


示例2: show_probe

def show_probe():
    stats={'type':'probe'}

    # clear keybuffer
    event.getKeys()

    # set probe to either on- or off-task
    probe.init_random()

    fclock.reset()
    for i in range(fprobe):
        probe.draw()
        win.flip()
        keys=event.getKeys()
        if  key1 in keys:
          probe.arrow_move(int(key1))
        elif key2 in keys:
            probe.arrow_move(int(key2))
        elif key3 in keys:
            probe.arrow_move(int(key3))
        elif key4 in keys:
            probe.arrow_move(int(key4))
    stats['time_probe']=fclock.getTime()
    stats['response']=probe.current_pos+1
    return stats
开发者ID:ihrke,项目名称:2016-sart-mw-tdcs-registered-report,代码行数:25,代码来源:sart.py


示例3: wait_check_pause_quit

def wait_check_pause_quit(win, wait_time, quit_keys=["q", "escape"],
                          pause_keys=["space"], check_every=1):
    """Wait while checking for pause or quit input."""
    raise NotImplementedError("This isn't quite finished yet")
    checks = int(floor(wait_time / check_every))
    for _ in range(checks):

        core.wait(check_every)

        if event.getKeys(keyList=quit_keys):
            print "Subject quit execution"
            core.quit()

        if event.getKeys(keyList=pause_keys):

            pause_start = time.time()
            visual.TextStim(win, text="Experiment paused").draw()
            win.flip()
            paused = True
            while paused:
                if event.getKeys(keyList=pause_keys):
                    paused = False
                core.sleep(check_every)
            pause_end = time.time()

    pause_duration = pause_end - pause_start
    remaining = wait_time - checks * check_every
    if remaining:
        core.wait(remaining)

    return pause_duration
开发者ID:mwaskom,项目名称:cregg,代码行数:31,代码来源:main.py


示例4: show_trial

def show_trial(num):
    stats={'type':'go' if num!=3 else 'stop', 'number':num, 'nresponses':0}
    fclock.reset()
    num=int(num)
    number.setText("%i"%num)
    fclock.reset()
    for i in range(fnumber):
        number.draw()
        win.flip()
        keys=event.getKeys()
        if set(valid_keys) & set(keys): #intersection on sets
            if stats['nresponses']==0:
                stats['response']=1
                stats['RT']=fclock.getTime()
            stats['nresponses']+=1
    stats['time_number']=fclock.getTime()

    fclock.reset()
    for i in range(fblank):
        win.flip()
        keys=event.getKeys()
        if set(valid_keys) & set(keys):
            if stats['nresponses']==0:
                stats['response']=1
                stats['RT']=fclock.getTime()+stats['time_number']
            stats['nresponses']+=1

    stats['time_blank']=fclock.getTime()
    return stats
开发者ID:ihrke,项目名称:2016-sart-mw-tdcs-registered-report,代码行数:29,代码来源:sart.py


示例5: WaitForKeyInput

def WaitForKeyInput():
    text='...'
    #until return pressed, listen for letter keys & add to text string
    while event.getKeys(keyList=['return'])==[]:
        letterlist=event.getKeys(keyList=['0', '1', '2', '3', '4',  '5' , '6', '7', '8', '9','backspace','q'])
        for l in letterlist:
            if l == 'q':
                core.quit()
            #if key isn't backspace, add key pressed to the string
            if l !='backspace':
                if text =="...":
                    text=l
                    pressedkeys=l
                else:
                    text+=l
                    pressedkeys+=(";" + l)
            #otherwise, take the last letter off the string
            elif len(text)>0:
                text=text[:-1]
                pressedkeys+=(";backspace")
            #continually redraw text onscreen until return pressed
            text = unicode(text)
            print "UNICODE"
            print text
            response = visual.TextStim(mywin, height=36,text=text,color="white",pos=(0,-100))
            betAsk.draw()
            response.draw()
            mywin.flip()
            core.wait(0.1)
    RT = trialClock.getTime()
    event.clearEvents()
    return text,RT
开发者ID:WMPLab,项目名称:MetaMemory,代码行数:32,代码来源:metamemory.py


示例6: ask

def ask(text='', keyList=[]):
    """
    Ask subject something. Shows question and returns answer (keypress)
    and reaction time. Defaults to no text and all keys.
    """
    # Draw the TextStims to visual buffer, then show it and reset timing immediately (at stimulus onset)
    stimText.setText(codecs.decode(text,"utf-8"))
    spaceText.setText(codecs.decode(spaceLookup[language],"utf-8"))
    # Set the text height
    stimText.setHeight(1)
    spaceText.setHeight(1)
    # set the text color
    stimText.setColor('white')
    spaceText.setColor('white')
    stimText.draw()
    spaceText.draw()
    win.flip()
    event.clearEvents('keyboard')

    # Halt everything and wait for (first) responses matching the keys given in the Q object.
    response = event.waitKeys(keyList=['space','q','r'])
    if response[0] in keysQuit:  # Look at first reponse [0]. Quit everything if quit-key was pressed
        core.quit()
    if response[0] in keysBreak:
        event.clearEvents('keyboard')
        win.flip()
    if event.getKeys(keyList=['escape', 'q']):
        core.quit()
    if event.getKeys(keyList=['s']):
        print "Skipped experiment"
        quit()
    return response # When answer given, return it.
开发者ID:MaisonLogicielLibre,项目名称:CogSciProject-master,代码行数:32,代码来源:welcomescript.py


示例7: showUntilKeyPressed

 def showUntilKeyPressed(self, text, keyList=[]):
     """
     Show text until a key is pressed.
     If keyList is empty, it will listen for all keys.
     """
     
     self._display(text)
     
     
     instructionClock = core.Clock()
     instructionClock.reset()
     
     keyPressed = False
     eventCheckStarted = False
     while not keyPressed:
         t = instructionClock.getTime()
         
         if t >= 0.5:
             # Do not check for events immediatelly, such that people do not accidentally
             # skip the message.
             
             if eventCheckStarted == False:
                 # Remove keyboard events that were sent before the "grace" period had elapsed
                 event.clearEvents(eventType='keyboard')
                 eventCheckStarted = True
                 
             # Check for keys
             if keyList == []:
                 theseKeys = event.getKeys()
             else:
                 theseKeys = event.getKeys(keyList=keyList)
             
             if len(theseKeys) > 0:
                 # A key was pressed, return it
                 return theseKeys[0]
开发者ID:Beskhue,项目名称:SequenceRetentionExperiment,代码行数:35,代码来源:showText.py


示例8: textInput

def textInput():
    #until return pressed, listen for letter keys & add to text string
    text = ''
    while event.getKeys(keyList=['escape'])==[]:
        letterlist=event.getKeys()
        letterDict = {'space': ' '}
#        letterlist=event.getKeys(keyList=['0','1','2','3','4','5','6','7','8','9','backspace'])

        for l in letterlist:
            if l == 'space':
                text += ' '
            elif l == 'return':
                text += '\n'
            #if key isn't backspace, add key pressed to the string
            elif l != 'backspace':
                text += l
            #otherwise, take the last letter off the string
            elif len(text)>0:
                text = text[:-1]
        #continually redraw text onscreen until return pressed

        textObject = visual.TextStim(win=win, ori=0, name='pause', text=text, font=u'Arial', pos=[0, 0],
                                     height=1.0, wrapWidth=None, color=u'white', colorSpace=u'rgb', opacity=1, depth=-1.0)

        # textReport.draw()
        textObject.draw()
        win.flip()
    text = str(text)
    event.clearEvents()
    print text
    return text
开发者ID:mkaillersmith,项目名称:Intro-to-Python,代码行数:31,代码来源:Text+Input.py


示例9: get_rating

def get_rating(input_method, resp_device, timeStamped,trig_collector,win):
    #if participants don't respond we will set up a null value so we don't get an error
    thisResp = None
    thisRT = np.nan
    if input_method == 'keyboard':
        for key, RT in event.getKeys(keyList = ['escape', 'q', '1', '2', '3', '4'], timeStamped = timeStamped):
            if key in ['escape','q']:
                print 'User Cancelled'

                if trig_collector:
                    trig_collector.endCollection()
                quitEXP(True)
            else:
                thisResp = key
                thisRT = timeStamped.getTime()
    else:
        thisResp = resp_device.read(1)
        thisRT = timeStamped.getTime()
        if len(thisResp) == 0:
            thisResp = None
            thisRT = np.nan
        else:
            pass
        # Quickly check for a 'escape' response on the keyboard to quit
        for key, RT in event.getKeys(keyList = ['escape'], timeStamped = timeStamped):
            if key in ['escape']:
                print 'User cancelled'
                trials.saveAsText(datalog_fn + '_data.csv')
                if trig_collector:
                    trig_collector.endCollection()
                quitEXP(True)
    return thisResp, thisRT
开发者ID:htwangtw,项目名称:mindwanderinglabYork,代码行数:32,代码来源:baseDef.py


示例10: waitForKeypress

def waitForKeypress():
    allKeys = event.getKeys()
    while len(allKeys)==0:
        allKeys = event.getKeys()
    if 'escape' in allKeys[0]:
        mywin.close() # quit
        core.quit()
开发者ID:jadref,项目名称:buffer_bci,代码行数:7,代码来源:runSentences_psychopy_soln.py


示例11: doUserInteraction

def doUserInteraction(stim, expectedKeys, timeout, soundFile):
    global paused
    if timeout == None or timeout == 0:
        timeout = sys.maxint
    startTime = trialClock.getTime()
    endTime = startTime + timeout

    response = {
        "keys": [],
        "firstKey": None,
        "lastKey": None,
        "startTime": startTime,
        "endTime": endTime,
        "duration": 0,
        "timedOut": False,
        }

    if soundFile != None:
        soundFile.play()

    while(True):
        stim.setAutoDraw(True) #continuously draws the stimulus to the buffer
        win.flip() # exposes the stimulus to the screen
        keys = [] # initializes an empty array to hold the keys that were pressed.

        # this IF checks 2 things in order to determine which keys are allowed to be pressed:

        if expectedKeys != None: # Have I specified a list of allowed keys?
            if len(expectedKeys) != 0: # Have I specified any particular keys (rather than just [] which means All keys?
                keys = event.getKeys(expectedKeys) # Listen for key presses from a particular subset
            else:
                keys = event.getKeys() # Listen for Any key presses.
        if len(keys) > 0: # If a key was pressed store some values in the object "response" defined above.
            response["keys"] = keys # put all the responses in here.
            response["firstKey"] = keys[0] # put the first keypress here
            response["lastKey"] = keys[len(keys)-1] # put the last keypress here.
            break #break out of this function

        elif trialClock.getTime() > endTime: # If the response time window has run out
            response["timedOut"] = True # indicate that we timed out
            response["firstKey"] = 'NA' # put 'NA' as the first key pressed
            break

        if event.getKeys(['f5']): # This is a "pause" button for the experiment
            textStim.text = 'Press any key to continue'
            textStim.pos = (0,-10)
            paused = 1
            stimUntilAnyKey(textStim)
            textStim.pos = (0,0)

        #check for quit (the [Esc] key)
        if event.getKeys(["escape"]):
            core.quit() #quits the entire experiment - will dump you to the desktop or whatever.

    stim.setAutoDraw(False) # stop drawing the stimulus to the buffer
    win.flip() # expose the now blank buffer to the screen
    response["duration"] = trialClock.getTime() - startTime # keeps track of how long since the stim was drawn to the screen
    event.clearEvents(eventType=None) # clear the key buffer.
    return response # ends the function and returns the object "response". Without this return - we would not be able to access any of this data.
开发者ID:mkaillersmith,项目名称:Intro-to-Python,代码行数:59,代码来源:Stroop+Demo+Complete.py


示例12: do_break

def do_break():
    breaktext = visual.TextStim(mywin, text="Break\n\nPress <space> to continue...",color=(1,1,1),height = 50) 
    breaktext.draw()
    mywin.flip()
    # wait for key-press
    allKeys = event.getKeys()
    while len(allKeys)==0:
        allKeys = event.getKeys()
开发者ID:jadref,项目名称:buffer_bci,代码行数:8,代码来源:simple_imagined_movement.py


示例13: show_instr

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()
开发者ID:jadref,项目名称:buffer_bci,代码行数:8,代码来源:simple_imagined_movement.py


示例14: Letters3Back

def Letters3Back(win, ask, language, letters):
    
    event.clearEvents()
    win.setRecordFrameIntervals(True)
    mouse = event.Mouse(visible=False)
    list =[random.randint(0,10) for r in xrange(numTrials)]
    #list = [2,3,2,3,2,3,2,3,4,5,6,7,8,9,8]
    keyList=[]
    responses = ['none'] * len(letters)
    demoDisp = visual.TextStim(win, text = letters[0], height = 4, pos=(0.0, 0.0)) #textstim object that will be displayed
    counter = 0  # Counter is unused?
    for x in range(len(letters)):
        # PREPARE STIMULUS
        demoDisp.setText(letters[x])

        # PRESENT STIMULUS
        for frameN in range(stimFrames):
            # Display stimulus
            demoDisp.draw()
            win.flip()
            RT.reset()
            # Reset timer on onset
            if frameN == 0:
                RT.reset()
            if event.getKeys(['q','escape']):
                core.quit()
            # RECORD RESPONSES
            keyList=event.getKeys(timeStamped=RT)
            if keyList:
                # keyList[N][Y], N is response number if multiple keys were pressed. Y=0 is key-name. Y=1 is time
                if 'space' in keyList[0][0]:
                    #Play sound when key pressed
                    #filesound = sound.Sound(audioPath)
                    #filesound.setVolume(1.0)
                    #filesound.play()
                    #Save responses
                    responses[x]= keyList[0][0]
                    print responses
                elif keyList == 'q':
                    core.quit()
            else:
                #responses.append('none')
                #No key was pressed
                continue
        #if not keyList:
        #    responses.append('none')

        # PRESENT BLANK
        for frameN in range(blankFrames):
            # Blank screen with no response recording
            RT.reset()
            win.flip()
        if event.getKeys(['q']):
            core.quit()
    
    print 'Letters 3-Back task finished...' 
    return responses
开发者ID:MaisonLogicielLibre,项目名称:CogSciProject-master,代码行数:57,代码来源:letters3back.py


示例15: show

def show(win, to_show = [], mouse_btns = [0,1,2], exit_keys = None, buttons = [], delay = 100000, clickReset = True):
    if mouse_btns == None: 
        mouse_btns = [0,1,2]
    
    use_mouse = False
    use_keybd = True # this is always true to capture the ESC key
    
    if len(mouse_btns):
        use_mouse = True
        mouse = event.Mouse(win=win)
        rects = [ button.rect() for r in buttons ]
        if len(rects): 
            mouse.setVisible(True)
     
    rt,b,k,re = -1,None,None,None
    event.clearEvents()
    
    if use_keybd:
        event.getKeys()
    if use_mouse:
        mouse_release(mouse)

    clock_show=core.Clock()
    
    if use_mouse and clickReset:
        mouse.clickReset()
    
    t=0; clock_show.reset()
    
    while True:
        rt = t= clock_show.getTime()

        if t >= delay:
            break
            
        if (0.0 <= t):
            for t in to_show:
                t.draw()
            for b in buttons:
                b.draw()
       
        if use_mouse:
            rt, bt, re, ts = mouse_pressed(mouse, mouse_btns, rects = rects)
            if len(bt) and (len(rects) == 0 or len(re)): 
                break
        
        if use_keybd:
            rt, k = key_pressed(clock_show, exit_keys)
            if len(k): 
                break
                 
        win.flip()
        
    if use_mouse and len(rects): 
        mouse.setVisible(False)
        
    return rt,b,k,re
开发者ID:languageguide,项目名称:__irony-comprehension,代码行数:57,代码来源:IronyComprehensionAllInOne.py


示例16: draw_fixation

def draw_fixation(color):
    while 'space' not in event.getKeys():
        [s.setFillColor(color) for s in fixations]
        [s.draw() for s in fixations]
        win.flip()
        if event.getKeys(["escape"]):
            core.quit()
    event.clearEvents()
    win.flip()
    core.wait(0.5)
开发者ID:awellis,项目名称:SVV,代码行数:10,代码来源:run_calibration.py


示例17: waitBeforeTrial

def waitBeforeTrial(nDone,respDeadline,expStop,stuffToDrawOnRespScreen):
    #displayDraw is a function instance to call to draw what want to between trials
    if dirOrLocalize:
        betweenTrialsText.setText('CLICK in blue area to continue')
        clickContinueArea.draw()
    else:
        betweenTrialsText.setText('Press SPACE to continue')
    progressMsg = 'Completed ' + str(nDone) + ' of ' + str(trials.nTotal) + ' trials'
    nextRemindCountText.setText(progressMsg)
    event.clearEvents() #clear keypresses and mouse clicks
    myClock.reset();
    if dirOrLocalize:
        betweenTrialsText.setText('CLICK in blue area to continue')
        waitingForClick = True
        while waitingForClick and respClock.getTime() < respDeadline:
            m_x, m_y = myMouse.getPos()  # in the same units as the Window 
            mouseLocationMarker.setPos((m_x, m_y)) #Because mouseLocationMarker is in same units as windowAndMouseUnits, and mouse returns windowAndMouseUnits, this has to work
            mouse1, mouse2, mouse3 = myMouse.getPressed()
            if myMouse.isPressedIn(clickContinueArea):
                waitingForClick = False
                event.clearEvents() 
            if waitingForClick and (mouse1 or mouse2 or mouse3):
               myWin.flip(); myWin.flip() #flicker everything to tell user registered your click but it's in wrong place
            keysPressed = event.getKeys()
            if 'escape' in keysPressed:
                expStop = True
            for x in stuffToDrawOnRespScreen:
                x.draw()
            betweenTrialsText.setText('CLICK in blue area to continue')
            if nDone==0:
                beforeFirstTrialText.draw()
            clickContinueArea.draw()
            mouseLocationMarker.draw()
            betweenTrialsText.draw()
            nextRemindCountText.draw()
            myWin.flip()
    if not expStop and not waitingForClick: #person never responded, but timed out. Presumably because of autopilot or hit escape
        waitingForPressBetweenTrials = True
        betweenTrialsText.setText('While looking at the green dot, press SPACE to continue')
        while waitingForPressBetweenTrials and myClock.getTime() < respDeadline:
            if nDone==0:
                beforeFirstTrialText.draw()
            respPromptText.draw()
            betweenTrialsText.draw()
            for x in stuffToDrawOnRespScreen:
                x.draw()
            myWin.flip()
            for key in event.getKeys():       #check if pressed abort-type key
                  if key in ['escape']:
                      expStop = True; waitingForPressBetweenTrials=False
                  if key in ['space']:
                      waitingForPressBetweenTrials=False
    return expStop
开发者ID:alexholcombe,项目名称:spatiotopic-motion,代码行数:53,代码来源:dotLocalize.py


示例18: waitForExitPress

def waitForExitPress(time = 0):
  logging.debug("Waiting for exit key to be pressed")
  if time == 0:
    while True:
      if event.getKeys(["escape"]):
            logging.debug("User pressed escape")
            exit()
  else:
    waitTimer = core.CountdownTimer(time) 
    while (waitTimer.getTime() > 0):
      if event.getKeys(["escape"]):
            logging.debug("User pressed escape")
            exit()
开发者ID:SpetchLab,项目名称:SubOptimalChoiceWithCommitment,代码行数:13,代码来源:SubOptimalChoiceWithCommitment.py


示例19: show_instruction

def show_instruction(screen):
    """screen is a list of strings that is displayed on one screen"""
    event.getKeys() # clear buffer
    r=None
    if not debug:
        for i,inst in enumerate(screen):
            ypos=1-(pad+(i+1)*(2.0-2*pad)/len(screen))
            msg=visual.TextStim(win, pos=[0,ypos],text=unicode(inst,"utf-8"), units='norm', height=0.075, #size=(2.0,1.0),
                                alignHoriz='center', alignVert='center', color=stimcolor ,wrapWidth=1.8)
            msg.draw()
        win.flip()
        r=event.waitKeys()[0]
    return r
开发者ID:ihrke,项目名称:2016-sart-mw-tdcs-registered-report,代码行数:13,代码来源:sart.py


示例20: draw_fixation

def draw_fixation(color):
    """args: color should be a string
    """
    print_message("Color", color)
    print("Press 'space' to continue")
    while 'space' not in event.getKeys():
        [s.setFillColor(COLOR[color]) for s in fixations]
        [s.draw() for s in fixations]
        win.flip()
        if event.getKeys(["escape"]):
            core.quit()
    event.clearEvents()
    win.flip()
    core.wait(0.5)
开发者ID:awellis,项目名称:SVV,代码行数:14,代码来源:run_svv_adaptation.py



注:本文中的psychopy.event.getKeys函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python event.waitKeys函数代码示例发布时间:2022-05-25
下一篇:
Python event.clearEvents函数代码示例发布时间:2022-05-25
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap