本文整理汇总了Python中psychopy.event.clearEvents函数的典型用法代码示例。如果您正苦于以下问题:Python clearEvents函数的具体用法?Python clearEvents怎么用?Python clearEvents使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了clearEvents函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: 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
示例2: 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
示例3: flush
def flush(self):
"""See openexp._mouse.legacy"""
event.mouseButtons = [0,0,0]
event.clearEvents()
return False
开发者ID:fragtalg,项目名称:OpenSesame,代码行数:7,代码来源:psycho.py
示例4: GetResponse
def GetResponse():
global currentRule, currentTgt, ruleCount, rightAnswers, gameScore
event.clearEvents()
retVal = 0 #if not modified, breaks the task
answerPressed = -1 # which card was selected?
keylist = { 'down': ['down', '2'], 'left': ['left', '4'], 'up': ['up', '8'], 'right': ['right', '6']}
keys = event.waitKeys(keyList=['f10', 'escape', 'up', 'right', 'down', 'left', '2', '4', '6', '8'])
if keys[0] == 'f10':
triggerAndLog(portCodes['stop'], "STP", 0, 0, "STOP: aborted by F10")
win.close()
core.quit()
if keys[0] == 'escape':
retVal = 0
#elif keys[0] == 'up':
elif keys[0] in keylist['up']:
if CheckCard( 0, currentRule, currentTgt ):
rightAnswers += 1
retVal = 1
else:
retVal = -1
#elif keys[0] == 'right':
elif keys[0] in keylist['right']:
if CheckCard( 1, currentRule, currentTgt ):
rightAnswers += 1
retVal = 2
else:
retVal = -2
#elif keys[0] == 'down':
elif keys[0] in keylist['down']:
if CheckCard( 2, currentRule, currentTgt ):
rightAnswers += 1
retVal = 3
else:
retVal = -3
#elif keys[0] == 'left':
elif keys[0] in keylist['left']:
if CheckCard( 3, currentRule, currentTgt ):
rightAnswers += 1
retVal = 4
else:
retVal = -4
idx=str(rules.index(currentRule)+1)
if retVal > 0:
gameScore += 1
triggerAndLog( portCodes['respRight'] + portCodes['rule'+idx],\
"RSP", currentBlock, currentTrial, 'RESPONSE 1 ' + currentRule + ' ANSWER ' + str(retVal) )
elif retVal < 0:
gameScore -= 1
triggerAndLog( portCodes['respWrong'] + portCodes['rule'+idx],\
"RSP", currentBlock, currentTrial, 'RESPONSE 0 ' + currentRule + ' ANSWER ' + str(retVal) )
return retVal
开发者ID:bwrc,项目名称:WishGLD,代码行数:60,代码来源:WCST_faces_tasktypes_matchingstim_configfile_xpltfrm.py
示例5: practicerounds
def practicerounds(r):
already = True#why is this here again?
bet = 999
#load words
words = ["one","two","three"]
#show words
event.clearEvents()
if r == 0:
while event.getKeys(keyList=['return'])==[]:#wait till ready
instructions2[3].draw()
mywin.flip()
questions.draw()#draw blank
w = visual.TextStim(mywin, height=55,text= words[rq],color="white",pos=(0,0))
if already == True:
w.draw()
mywin.flip()#show word
core.wait(2)#wait 2 seconds
#THIS IS WHERE THE TIMING STUFF WILL GO
while bet > 10:
print type(bet)
print bet
betAsk.draw()#ask how much they want to bet
mywin.flip()
trialtime = core.Clock()
trialtime.reset()
bet = WaitForKeyInput() #recieve bet input
try:
bet = int(bet)
except ValueError:
bet = 999
continue
RT = trialtime.getTime()
开发者ID:WMPLab,项目名称:MetaMemory,代码行数:32,代码来源:mm.py
示例6: showResponseOptions
def showResponseOptions(self):
self.responseObj.updateVariants()
self.win.setColor(self.responseBgnd)
self.win.flip()
t=self.clock.getTime()
self.responseDur=-1
resp=None
while resp==None:
pos=self.mouse.getPos()
choice=self.responseObj.variantForPoint(pos)
self.mouse.setVisible(1)
self.responseObj.draw()
self.win.flip()
btn=self.mouse.getPressed()
if btn[0]==True and choice != -1:
resp=True
self.responseDur=self.clock.getTime()-t
self.responseObj.blinkSelected()
self.win.flip()
event.clearEvents()
return choice
开发者ID:yvs,项目名称:Percexp,代码行数:31,代码来源:DLSession.py
示例7: run_preferential_gaze
def run_preferential_gaze(self):
cont=True
for i in range(self.preferential_gaze_trials):
self.distractor_set.show_video()
# clear any keystrokes before starting
event.clearEvents()
self.preferential_gaze.run(self.ns, self.eye_tracker, self.mouse, self.gaze_debug, self.debug_sq)
# Check user input
all_keys = event.getKeys()
if len(all_keys):
# Quit experiment
if all_keys[0].upper() in ['Q', 'ESCAPE']:
cont = False
break
# Pause block
elif all_keys[0].upper() == 'P':
self.pause()
# End block
elif all_keys[0].upper() == 'E':
break
event.clearEvents()
return cont
开发者ID:jbonaiuto,项目名称:infant_eeg,代码行数:26,代码来源:gaze_following_exp.py
示例8: 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
示例9: wait_get_response
def wait_get_response(p, clock, oddball, wait_time):
"""Get response info specific to this experiment."""
check_clock = core.Clock()
good_resp = False
corr, response, resp_rt = 0, 0, -1
while not good_resp:
keys = event.getKeys(timeStamped=clock)
for key, stamp in keys:
if key in p.quit_keys:
print "Subject quit execution"
core.quit()
elif key in p.match_keys:
corr = 0 if oddball else 1
response = 1
resp_rt = stamp
good_resp = True
break
elif key in p.nonmatch_keys:
corr = 1 if oddball else 0
response = 2
resp_rt = stamp
good_resp = True
break
event.clearEvents()
# Possibly exit with nothing
if check_clock.getTime() >= wait_time:
return corr, response, resp_rt
# Wait the rest of the time
core.wait(wait_time - resp_rt)
return corr, response, resp_rt
开发者ID:mwaskom,项目名称:GAPE_Experiment,代码行数:30,代码来源:gape.py
示例10: fScore
def fScore():
global score
wordsToScore = wordsTheyRecalled
wordList = './words/words%i.txt' %(round-1)
throwAwayWords = list(cor for cor in open(wordList).read().split("\n") if cor)
print "WORDS THEY RECALLED"
print wordsTheyRecalled
print "ORIGINAL"
print throwAwayWords
for w in wordsToScore:
instructions2[2].draw()
mywin.flip()
core.wait(0.1)
if w in throwAwayWords:
risk = int(findBet(w))
throwAwayWords.remove(w)
score += risk
writeToDataFile(scorefileName,w,risk,score)
print score
correctedWord = correct(w)
if correctedWord != w:
while event.getKeys(keyList=['return'])==[]:
global corrects
misspelled = visual.TextStim(mywin, height=30,text=w,color="white",pos=(-300,0))
didYouMean = visual.TextStim(mywin, height=30,text=correctedWord,color="white",pos=(300, 0))
ask = visual.TextStim(mywin, height=45,text='Did you mean:',color="white",pos=(0, 0))
how = visual.TextStim(mywin, height=30,text='press y for Yes or n for No',color="white",pos=(0, -200))
instructions[2].draw()
misspelled.draw()
didYouMean.draw()
ask.draw()
how.draw()
mywin.flip()
event.clearEvents()
corrects = WaitForMouseInput()
print "DID THEY CHANGE?"
print corrects + "in loop"
if corrects == "yes":
if correctedWord in throwAwayWords:
risk = int(findBet(correctedWord))
throwAwayWords.remove(correctedWord)
score += risk
writeToDataFile(scorefileName,correctedWord,risk,score)
print score
else:
continue
for w in throwAwayWords:
risk = int(findBet(w))
score -= risk
writeToDataFile(scorefileName,w,risk,score)
print score
questions.draw()
#THIS IS WHERE THE FEEDBACK GOES
t = visual.TextStim(mywin, height=36,text="Your current score: ",color="white",pos=(-150,-100))
doing = visual.TextStim(mywin, height=36,text=score,color="white",pos=(150,-100))
t.draw()
doing.draw()
mywin.flip()
core.wait(4)
return score
开发者ID:WMPLab,项目名称:MetaMemory,代码行数:60,代码来源:totest.py
示例11: display_practice
def display_practice(graphics):
"""
Display the practice phase
:param graphics: graphics object which holds all visuals.
"""
# num of trials in left must be equal to num of trials in right.
if len(Constants.PRACTICE_LEFT_STIMS) != len(Constants.RIGHT_STIM_KEYS):
return
num_of_practice_trials = 2
practice_stim_val = [Constants.VIS_PRACTICE_LEFT_STIM, Constants.VIS_PRACTICE_RIGHT_STIM]
practice_stim = [Constants.PRACTICE_LEFT_STIMS, Constants.PRACTICE_RIGHT_STIMS]
routine_timer = core.CountdownTimer()
for trial in range(num_of_practice_trials): # 2 practice trials
for i in range(2): # Left stim then right stim
for stim in range(3): # Go through each triplet
# Set timer for each stim
routine_timer.reset()
routine_timer.add(Constants.DISPLAY_VISUAL_TIME)
# Set and display current stim.
graphics.set_text(practice_stim_val[i], practice_stim[i][trial][stim])
graphics.draw(practice_stim_val[i])
graphics.refresh()
# Display for the given length
while routine_timer.getTime() > 0:
if event.getKeys(keyList=Constants.ESCAPE_KEYS):
core.quit()
elif event.getKeys(keyList=Constants.SKIP_KEYS):
return
graphics.refresh()
routine_timer.add(Constants.NO_VISUAL_TIME)
# Remove visuals for the given length (transition from one stim to another)
while routine_timer.getTime() > 0:
if event.getKeys(keyList=Constants.ESCAPE_KEYS):
core.quit()
elif event.getKeys(keyList=Constants.SKIP_KEYS):
return
# After stims have been displayed, draw a question mark and wait for response.
graphics.draw(Constants.VIS_QUESTION_MARK)
graphics.refresh()
event.clearEvents()
# Wait until response given or escape key is pressed.
while True:
if event.getKeys(keyList=Constants.ESCAPE_KEYS):
core.quit()
elif event.getKeys(keyList=Constants.PRACTICE_RESP_KEYS):
break
# Clear screen and wait for the given length before starting next trial.
graphics.refresh()
time.sleep(Constants.NO_VISUAL_TIME)
开发者ID:FinnLandLab,项目名称:olives,代码行数:60,代码来源:Practice.py
示例12: 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
示例13: new_block
def new_block(input):
im = Image.new("RGB", (2048, 500), bg)
font = ImageFont.truetype("arial.ttf", 50)
draw = ImageDraw.Draw(im)
draw.text((580, 100), input, fill=(0,0,0), font=font)
# Attention: input can only be one line!
draw.text((580, 200), 'Weiter mit linker Maustaste.', fill=(0,0,0), font=font)
im.save("instructions/new_block.png")
eizoGS320.convert_to_eizo_picture("instructions/new_block.png", "instructions/block_eizo.png")
im_draw = visual.SimpleImageStim(mywin, "instructions/block_eizo.png", units="pix")
event.clearEvents()
run = True
while run:
for key in event.getKeys():
if key in ['escape','q']:
core.quit()
mouse1, mouse2, mouse3 = mymouse.getPressed()
if (mouse1):
run = False
event.clearEvents()
im_draw.draw()
mywin.flip()
mywin.flip()
core.wait(0.1)
开发者ID:jamesmcm,项目名称:StimScripts,代码行数:33,代码来源:myexp.py
示例14: pause
def pause(self):
"""
Pause block
"""
event.clearEvents()
self.win.flip()
event.waitKeys()
开发者ID:jbonaiuto,项目名称:infant_eeg,代码行数:7,代码来源:facial_movement_exp.py
示例15: run_calibration
def run_calibration():
# display instructions
set_msg('SET SOUND LEVEL','TITLE')
set_msg('press up and down to increase/decrease sound level and press enter when level is confortable','MAIN')
set_msg('Press return to continue','KEY')
win.flip()
# prepare calibration sound
s = sound_build.make_lp_noise(100000,3000,Exp.rate)
vol = 0.5
playsound(s,vol,200)
pressEnter = False
while pressEnter==False:
allKeys=event.waitKeys()
for thisKey in allKeys:
if thisKey=='up':
pygame.mixer.music.set_volume(pygame.mixer.music.get_volume()+0.03)
print(pygame.mixer.music.get_volume())
elif thisKey=='down':
pygame.mixer.music.set_volume(pygame.mixer.music.get_volume()-0.03)
print(pygame.mixer.music.get_volume())
elif thisKey in ['return']:
pressEnter = True
elif thisKey in ['q', 'escape']:
core.quit() #abort experiment
event.clearEvents() #must clear other (eg mouse) events - they clog the buffer
vol = pygame.mixer.music.get_volume()
pygame.mixer.music.stop()
return vol
开发者ID:vincentadam87,项目名称:pitch_experiment,代码行数:30,代码来源:run_experimentAXB.py
示例16: RunAttentionTrial
def RunAttentionTrial(cue,stim,cueDur,preStimDur,stimDur):
# --- SET UP
#Flush the key buffer and mouse movements
event.clearEvents()
#Reset our clock to zero - I think this call should take less time than window.flip, so resetting after the flip should be slightly more accurate.
clock.reset()
# --- DISPLAY
# display cue
textStim.setText(cue)
textStim.draw()
win.flip() #Put the image on the screen
core.wait(cueDur,cueDur) # tie up the CPU for cueDur seconds.
# display blank
textStim.setText('')
textStim.draw()
win.flip()
core.wait(preStimDur,preStimDur) # tie up the CPU for preStimDur seconds.
# display stimulus
textStim.setText(stim)
textStim.draw()
win.flip() #Put the image on the screen
#Wait stimDur seconds. Tie up the CPU the entire time (this is more accurate than letting other processes go)
core.wait(stimDur,stimDur)
# --- CLEAN UP
#Get a list of all keys that were pressed during our wait. Tell it to give also give us the amount of time since our clock was reset when the key was pressed (reaction time).
keypresses = event.getKeys(None,clock)
return keypresses
开发者ID:djangraw,项目名称:PsychoPyParadigms,代码行数:29,代码来源:LocalGlobalAttention.py
示例17: RunTrial
def RunTrial(goForward, nKeys):
# get trial start time
tTrial = globalClock.getTime() * 1000
# reset trial clock
trialClock.reset()
# clear event buffer
event.clearEvents()
# display response direction
line.draw()
if goForward:
rightArrow.draw()
win.logOnFlip(level=logging.EXP, msg="Right Arrow")
else:
leftArrow.draw()
win.logOnFlip(level=logging.EXP, msg="Left Arrow")
win.flip()
# wait for responses
# core.wait(respDur)
# get responses
allKeys = []
while len(allKeys) < nKeys and trialClock.getTime() < respDur:
newKeys = event.getKeys(timeStamped=trialClock)
for thisKey in newKeys:
allKeys.append(thisKey) # ,keyList=['1','2','3','4','q','Escape']
# allKeys = event.getKeys(timeStamped=trialClock)
return (tTrial, allKeys)
开发者ID:djangraw,项目名称:PsychoPyParadigms,代码行数:30,代码来源:SequenceLearningTask.py
示例18: 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
示例19: GetResponse
def GetResponse():
global currentRule, currentTgt, ruleCount, rightAnswers, gameScore
event.clearEvents()
retVal = 0 #if not modified, breaks the task
answerPressed = -1 # which card was selected?
keys = event.waitKeys()
if keys[0]=='escape':
retVal = 0
elif keys[0] == 'up':
if CheckCard( 0, currentRule, currentTgt ):
rightAnswers += 1
retVal = 1
else:
retVal = -1
elif keys[0] == 'right':
if CheckCard( 1, currentRule, currentTgt ):
rightAnswers += 1
retVal = 2
else:
retVal = -2
elif keys[0] == 'down':
if CheckCard( 2, currentRule, currentTgt ):
rightAnswers += 1
retVal = 3
else:
retVal = -3
elif keys[0] == 'left':
if CheckCard( 3, currentRule, currentTgt ):
rightAnswers += 1
retVal = 4
else:
retVal = -4
if retVal > 0:
gameScore += 1
if currentRule == 'G1':
triggerAndLog( portCodes['respRight'] | portCodes['rule1'], 'RESP 1 ' + currentRule + ' ANSWER ' + str(retVal) )
if currentRule == 'G2':
triggerAndLog( portCodes['respRight'] | portCodes['rule2'], 'RESP 1 ' + currentRule + ' ANSWER ' + str(retVal) )
if currentRule == 'L1':
triggerAndLog( portCodes['respRight'] | portCodes['rule3'], 'RESP 1 ' + currentRule + ' ANSWER ' + str(retVal) )
if currentRule == 'L2':
triggerAndLog( portCodes['respRight'] | portCodes['rule4'], 'RESP 1 ' + currentRule + ' ANSWER ' + str(retVal) )
elif retVal < 0:
gameScore -= 1
if currentRule == 'G1':
triggerAndLog( portCodes['respWrong'] | portCodes['rule1'], 'RESP 0 ' + currentRule + ' ANSWER ' + str(retVal) )
if currentRule == 'G2':
triggerAndLog( portCodes['respWrong'] | portCodes['rule2'], 'RESP 0 ' + currentRule + ' ANSWER ' + str(retVal) )
if currentRule == 'L1':
triggerAndLog( portCodes['respWrong'] | portCodes['rule3'], 'RESP 0 ' + currentRule + ' ANSWER ' + str(retVal) )
if currentRule == 'L2':
triggerAndLog( portCodes['respWrong'] | portCodes['rule4'], 'RESP 0 ' + currentRule + ' ANSWER ' + str(retVal) )
return retVal
开发者ID:bwrc,项目名称:WishGLD,代码行数:59,代码来源:testi.py
示例20: RunTrial
def RunTrial(sequence):
# check for going over session time
if globalClock.getTime()-tStartSession > tSessionMax:
CoolDown() #exit experiment gracefully
# get deadline for response
respDur = tRespPerItem*(len(sequence))
respDur = int(tRespRoundOff * np.ceil(float(respDur)/tRespRoundOff)) # round up to next tRespRoundOff multiple
# print("length = %d, respDur = %1.1f"%(len(sequence), respDur))
logging.log(level=logging.EXP, msg='Start Sequence %d'%len(sequence))
# play sequence
for iStim in sequence:
DisplayButtons([iStim],stimDur)
beeps[iStim].play()
core.wait(stimDur,stimDur) # wait so sound plays properly
DisplayButtons([],pauseDur)
# core.wait(pauseDur,pauseDur)
logging.log(level=logging.EXP, msg='End Sequence %d'%len(sequence))
#draw fixation dot and wait for response
event.clearEvents() # ignore any keypresses before now
# win.logOnFlip(level=logging.EXP, msg='Display Fixation')
# fixation.draw()
DisplayButtons([],0,True)
# tResp = trialClock.getTime() # IMPORTANT REFERENCE POINT
tResp = tNextFlip[0] # IMPORTANT REFERENCE POINT
iSeq = 0
# Response loop
while globalClock.getTime() < (tResp + respDur) and iSeq < len(sequence):
iStim = sequence[iSeq]
thisKey = event.getKeys(timeStamped=globalClock)
if len(thisKey)>0 and thisKey[0][0] == respKeys[iStim]:
#tResp = trialClock.getTime(); # reset the shot clock
# fixation.draw()
DisplayButtons([iStim],0,True) # DON'T INCREMENT CLOCK
beepsShort[iStim].play()
core.wait(shortDur,shortDur) # USE CORE.WAIT HERE SO CLOCK DOESN'T INCREMENT
# fixation.draw()
DisplayButtons([],0,True)
iSeq += 1
elif len(thisKey)>0 and thisKey[0][0] in ['q','escape']:
core.quit()
elif len(thisKey)>0:
print('this: %s'%str(thisKey[0][0]))
print('correct: %s'%str(respKeys[iStim]))
buzz.play()
core.wait(buzzDur,buzzDur) # USE CORE.WAIT HERE SO CLOCK DOESN'T INCREMENT
return (WRONG)
#get response
if iSeq == len(sequence): # finished sequence
DisplayButtons([],respDur,False) # increment next-frame clock
return(RIGHT)
else: # ran out of time
buzz.play()
core.wait(buzzDur,buzzDur) # USE CORE.WAIT HERE SO CLOCK DOESN'T INCREMENT
DisplayButtons([],respDur,False) # increment next-frame clock
return (TOOSLOW)
开发者ID:djangraw,项目名称:PsychoPyParadigms,代码行数:59,代码来源:SimonTask.py
注:本文中的psychopy.event.clearEvents函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论