本文整理汇总了Python中psychopy.event.clearEvents函数的典型用法代码示例。如果您正苦于以下问题:Python clearEvents函数的具体用法?Python clearEvents怎么用?Python clearEvents使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了clearEvents函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
示例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.
示例3: flush
def flush(self):
"""See openexp._mouse.legacy"""
event.mouseButtons = [0,0,0]
event.clearEvents()
return False
示例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
示例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()
示例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
示例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
示例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
示例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
示例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
示例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)
示例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]
示例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)
示例14: pause
def pause(self):
"""
Pause block
"""
event.clearEvents()
self.win.flip()
event.waitKeys()
示例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