本文整理汇总了Python中psychopy.event.getKeys函数的典型用法代码示例。如果您正苦于以下问题:Python getKeys函数的具体用法?Python getKeys怎么用?Python getKeys使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了getKeys函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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()
示例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
示例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
示例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
示例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
示例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.
示例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]
示例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
示例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
示例10: waitForKeypress
def waitForKeypress():
allKeys = event.getKeys()
while len(allKeys)==0:
allKeys = event.getKeys()
if 'escape' in allKeys[0]:
mywin.close() # quit
core.quit()
示例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.
示例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()
示例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()
示例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
示例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