psychopy.org | Reference | Downloads | Github

Conditionally end a trial and proceed to the next upon keystroke detection

Hello,

I’m preparing a decision paradigm in Python 3.8.3/macOS Big Sur 11.2.3, and I need to implement a keypress feature that allows volunteers to end a given trial.

I’m able to record all keystrokes and detect specific keystrokes. However, I could use some help in figuring out the right approach to conditionally ending the trial and moving on to the next trial if a specific key—say, for instance, the ‘space’ key—is pressed.

Here’s a simplified version of the code:

Thanks in advance for any help! :slight_smile:

So a couple questions. Is the idea that they can press one of several keys and one of them will end the trial while others will do other things, or just that you want the trial to run until they pre are ss a key?

In the latter case there is an extremely simple solution: any loop, and event.waitKeys(['valid keys']). WaitKeys does exactly what it sounds like: just holds the entire program until a keypress is detected, and you can restrict which keys are accepted with the argument.

If you need your experiment to be doing literally anything while you’re waiting for that keypress, it’s a little bit but not much more complicated. You just need a loop and a condition, which might look like this;

done = False
while not done:
   stim.draw()
   win.flip()
  
  keys = event.getKeys()
  if 'space' in keys:
      done = True

This is assuming you’re doing everything in the coder, of course. The builder has options for ending a trial on key-press using the keyboard response object.

1 Like

Hi Jonathan,

Thanks so much for your reply! The issue I’m running into is that I do have operations running while the keylogger runs, and I need trials to run for specific amounts of time if the subject does not press anything.

In my above code, core.wait() is meant to achieve that. But the problem I’m having is that I cannot seem to conditionally interrupt core.wait() to end the trial in the event that the subject does press the specified “escape” key (e.g., ‘space’).

Do you know how to interrupt core.wait()? Or can you see another workaround? Many thanks,
Dan

ps. I’m coding all of this in Python without use of the PsychoPy GUI.

You just need to use a different kind of timer then. Something like a frame counter. So, slight revision:

done = False
frameCount = 0
while not done:
   stim.draw()
   win.flip()
   frameCount = frameCount + 1
  
  keys = event.getKeys()
  if 'space' in keys:
      done = True
  if frameCount > 300: # 5 seconds at 60fps
      done = True

This code simultaneously checks for a key-press and ends if nothing happens for some amount of time.

EDIT: I should mention, this works because while loops that call win.flip() cycle once per frame, so this is essentially executing this code at 60Hz

1 Like

This works like a charm! Getting away from core.wait() was indeed the fix. Thank you again, Jonathan.