Search code examples
pythonpsychopy

How do I check accuracy within the loop?


I am trying to code a function for my experiment which shows 2 labels above a a coloured rectangle in the middle. Subjects has to press either left or right to categorise the colour with one of the labels above.

I would like to code within in the loop that if accuracy = 1, then the experiment should show an info-text saying their choice was correct, and vice versa if accuracy = 0. After they press enter to continue, it should go back to the original loop and then repeat itself.

How do I do that?

# make a function for one trial of colour practice
def con1_trial(self):
    global trial
    global key
    trial += 1
    target_colour = random.choice(colours) 

    # show one square with gouloboy colour in top right corner of screen
    col3rec.setFillColor(target_colour)
    col3rec.draw()
    sinij_text.draw()
    boy_text.draw()

    # draw and flip
    win.flip()

    key, test_answer = event.waitKeys(keyList=['right', 'left', 'escape'], timeStamped = True)[0]
    for colour_pair in colour_pairs:
        if test_colour == colours[0] and key == "left":
            accuracy = 1
        elif test_colour == colours[1] and key == "right":
            accuracy = 1
        elif key == 'escape':
            core.quit() 
        else: accuracy = 0

    # records time in ms
    rt = (test_answer - test_start)*1000
    return accuracy, rt

Solution

  • To make the code neat, first define a feedback function somewhere earlier in your script:

    feedback_text = visual.TextStim(win)
    def show_feedback(feedback):
        # Show feedback on screen
        feedback_text.text = feedback
        feedback_text.draw()
        win.flip()
    
        # Wait for key
        event.waitKeys()
    

    Following your code add something this:

    # Show feedback
    if accuracy == 1:
        show_feedback('Correct! Well done. Press a key to continue...')
    elif accuracy == 0:
        show_feedback('Wrong! Press a key to continue...')
    

    ... with the correct level of indentation. I always end up having some sort of function to show a message. In show_feedback you could also add something to quit the experiment:

    key = event.waitKeys()[0]  # get first key pressed
    if key == 'escape':
        core.quit()