Exemplo n.º 1
0
    def RunTrial(self, image):
        """Runs a particular trial, which includes displaying the image to the
        screen, and gathering the keypresses and their respective response times. 

        image: the image (filename) to display
        returns: [keyPress, reaction time]
        """
        theImage = ImageStim(self.window)
        imagePath = os.path.normpath(self.imgDir + "/%s" % (image))

        theImage.setImage(imagePath)
        imageSize = self.ScaleImage(imagePath, self.imageWidth)
        theImage.setSize(imageSize)
        theImage.draw(self.window)
        self.window.flip()
        clearEvents()
        self.clock.reset()
        keyPresses = []
        if (self.selfPaced == False):
            wait(self.trialDuration, self.trialDuration)
            keyPresses = getKeys(keyList=[
                self.leftButton, self.rightButton, self.pauseButton, 'escape'
            ],
                                 timeStamped=self.clock)
        elif (self.selfPaced == True):
            keyPresses = waitKeys(keyList=[
                self.leftButton, self.rightButton, self.pauseButton, 'escape'
            ],
                                  timeStamped=self.clock)
        self.window.flip()
        wait(self.ISI)
        if (not keyPresses):
            return '', 0
        return keyPresses[0][0], keyPresses[0][1]
Exemplo n.º 2
0
    def RunTrial(self, image, pos):
        """Runs a particular trial, which includes displaying the image to the
        screen, and gathering the keypresses and their respective response times. 

        image: The filename of the image to display
        pos: Coordinates (on 6x4 grid) where image will be displayed
        return: tuple of first keypress info: (keyPress, reactionTime)
        """
        ShownImage = ImageStim(self.window)
        ShownImage.setPos(pos)
        ShownImage.setSize((self.imageWidth, self.imageWidth))
        ShownImage.setImage(self.imgDir + '/%s' % (image))
        ShownImage.draw(self.window)
        self.window.flip()
        clearEvents()
        self.clock.reset()
        keypresses = []
        if (self.selfPaced == False):
            wait(self.trialDuration, self.trialDuration)
            keypresses = getKeys(keyList=[
                self.leftButton, self.rightButton, self.pauseButton, "escape"
            ],
                                 timeStamped=self.clock)
        elif (self.selfPaced == True):
            keypresses = waitKeys(keyList=[
                self.leftButton, self.rightButton, self.pauseButton, "escape"
            ],
                                  timeStamped=self.clock)
        self.window.flip()
        wait(self.ISI)
        if len(keypresses) < 1:
            return '', 0
        return keypresses[0][0], keypresses[0][1]
Exemplo n.º 3
0
def whoAmI(response, done, qpos, image):
    """
    Function that will be called to enter the user identification data
    - **Input**:
        :response: the user resonse (empty string at beginning)
        :done: boolean (True / False) -> False at beginning
        :qpos: text position for user response
        :image: the stimulus image
        
    - **outpu**:
        :response: the user response
    """

    # --------------------------------------- #
    # WHILE THE WELCOME MESSAGE IS NOT PASSED #
    # --------------------------------------- #
    while len(response) == 0:  # while the user has not taped anything yet
        response = ''  # the response written by the user - On commence avec une chaîne vide
        respstim = TextStim(disp, text='', pos=qpos, height=size,
                            color=color)  # stimulus texte
        qstim = ImageStim(disp, image=image)
        qstim.draw()  # dessiner la question
        disp.flip(
        )  # passer au screen au suivant -> on met la question par-dessus
        core.wait(loadTime
                  )  # delay of 10 seconds before passing to the learning phase
        done = False

        # ----------------------------------- #
        # WHILE THE USER'S ANSWER IS NOT DONE #
        # Check for keypresses                #
        # ----------------------------------- #
        while not done:  # loop until done == True
            resplist = waitKeys(maxWait=float('inf'),
                                keyList=None,
                                timeStamped=True)
            key, presstime = resplist[
                0]  # use only the first in the returned list of keypresses -> resplist[0] is the first element in the resplist list
            if len(key) == 1:  # Check si la longeur de la réponse (len) = 1
                response += key  #Ajouter la lettre tapée à la réponse => on ne tient pas compte des touches pour les majuscules ni de la touche escape
            elif key == 'space':  # Check if key is the space bar
                response += ' '  # ajoute un espace
            elif key == 'backspace' and len(
                    response
            ) > 0:  # Check if the key's name was backspace AND si la réponse a au moins une lettre
                response = response[0:
                                    -1]  #remove last character of the response
            if key == 'return':  # if the key was non of the above, check si c'est enter
                done = True  # set done to True
            respstim.setText(response.capitalize(
            ))  # actualiser la user response => 1ère lettre en majuscule
            qstim.draw()  # réafficher la question stimulus (image)
            respstim.draw()  # réafficher la réponse au stimulus
            disp.flip()  # update the monitor
            core.wait(
                loadTime)  # add a little lag to avoid little freez and/or bug

    return response.capitalize()  # 1ère lettre en majuscule
Exemplo n.º 4
0
class ImageScreen(Screen):
    
    
    def __init__(self,
                 disp,
                 text,
                 text_width,
                 image,
                 image_size,
                 text_pos=None,
                 image_pos=None,
                 wait_time=1,
                 extra_image_stims=[]
                 ):
        super(ImageScreen, self).__init__(disp, wait_time=wait_time)
        self.extra_image_stims = extra_image_stims
        self.wait_time = wait_time
        if self.wait_time == 0:
            self.continue_button.clickable = True
        if text_pos is None:
            _text_pos = self.coords(self.width/4, self.height/2)
        else:
            _text_pos = text_pos
        if image_pos is None:
            _image_pos = self.coords(3*self.width/4, self.height/2)
        else:
            _image_pos = image_pos
        self.text_stim = TextStim(
                win=self.window,
                text=text,
                pos=_text_pos,
                height=Screen.default_font_size,
                wrapWidth=text_width
                )
        self.img_stim = ImageStim(
                win=self.window,
                image=image,
                pos=_image_pos,
                size=(image_size[0], image_size[1])
                )
        
    def draw(self, debug_mode=False):
        for img_stim in self.extra_image_stims:
            img_stim.draw()
        self.continue_button.draw()
        self.text_stim.draw()
        self.img_stim.draw()
        
        if not self.continue_button.clickable:
            if getAbsTime() - self.t0 > self.wait_time:
                self.continue_button.clickable = True
        
    def cleanup(self):
        for extra in self.extra_image_stims:
            del extra
        self.window.flip()
        self.window.flip()
        self.window.flip()
Exemplo n.º 5
0
class ShowAndConfirm():
    def __init__(self, win, image, button_text):
        self.win = win
        self.show = ImageStim(win, image=image, units='norm')
        self.confirm_button = Button(win, (0, -0.5), width=0.1, height=0.05, name='confirm_button', text=button_text)

    def run(self):
        while self.confirm_button.state != self.confirm_button.END:
            self.show.draw()
            self.confirm_button.process()
            self.confirm_button.draw()
            self.win.flip()
Exemplo n.º 6
0
def userResponse(response, done, qpos, image, multi):
    """
    Function that will be called every time the user needs to press a key to pass to the next display
    - **Input**:
        :response: the user resonse (empty string at beginning)
        :done: boolean (True / False) -> False at beginning
        :qpos: text position for user response
        :image: the stimulus image
        :multi: multiple display ? integer (1, 2 or 3)
    """

    # --------------------------------------- #
    # WHILE THE WELCOME MESSAGE IS NOT PASSED #
    # --------------------------------------- #
    while len(response) == 0:  # while the user has not taped anything yet
        response = ''  # the response written by the user - On commence avec une chaîne vide
        respstim = TextStim(disp, text='', pos=qpos,
                            height=size)  # stimulus texte
        qstim = ImageStim(disp, image=image)
        qstim.draw()  # dessiner la question
        if multi >= 2:  # at least 2 diferent stimuli
            qstim2.draw()
        if multi == 3:  # 3 diferent stimuli
            qstim3.draw()
        disp.flip(
        )  # passer au screen au suivant -> on met la question par-dessus
        core.wait(loadTime
                  )  # delay of 10 seconds before passing to the learning phase
        done = False

        # ----------------------------------- #
        # WHILE THE USER'S ANSWER IS NOT DONE #
        # Check for keypresses                #
        # ----------------------------------- #
        while not done:  # loop until done == True
            resplist = waitKeys(maxWait=float('inf'),
                                keyList=None,
                                timeStamped=True)
            key, presstime = resplist[
                0]  # use only the first in the returned list of keypresses -> resplist[0] is the first element in the resplist list
            response += key  #Ajouter la lettre tapée à la réponse
            done = True  # set done to True
            qstim.draw()  # réafficher la question stimulus
            respstim.draw()  # réafficher la réponse au stimulus
            disp.flip()  # update the monitor
            core.wait(
                loadTime)  # add a little lag to avoid little freez and/or bug
def draw_overview_target(win, level, target_pos, text_pos,
                         mouse_clicks_all_levels):
    target = ImageStim(win, 'target.png', size=420, pos=target_pos)
    level_text = TextStim(win,
                          text=f'Level {level}',
                          height=35,
                          color=(0.2, 0.2, 0.8),
                          pos=text_pos)

    target.draw()
    level_text.draw()

    target_x, target_y = target_pos
    curr_level_mouse_clicks = mouse_clicks_all_levels[level - 1]

    for target_hit_pos in curr_level_mouse_clicks:
        if target_hit_pos['mouse_in_target']:
            circle = Circle(win,
                            radius=5,
                            fillColor='yellow',
                            lineColor='yellow')
            circle.setPos((target_hit_pos['mouse_x'] + target_x,
                           target_hit_pos['mouse_y'] + target_y))
            circle.draw()
def show_intro(win):
    start = TextStim(
        win,
        text="Hi there, player! This is you! Let's play!",
        height=35,
        color=(0.2, 0.2, 0.8),
        pos=(250, 230),
    )

    player = ImageStim(
        win,
        'creature.jpg',
        pos=(0, -100),
        size=(420, 420),
    )

    intro_text = (
        'In this game you should shoot at the target with your mouse. ' +
        'The target moves rapidly to a new position each time you shoot at it.'
        + 'There are 3 levels each faster than the previous one. Good luck!')

    instructions = TextStim(
        win,
        text=intro_text,
        height=35,
        color=(1, 0.2, 0.6),
        pos=(250, 0),
    )

    start.draw()
    player.draw()
    win.flip()
    wait(3)
    instructions.draw()
    win.flip()
    wait(8)
Exemplo n.º 9
0
			example_target.setPos(right)
			example_foil.setPos(right)
	else: #else they're showen in the center
		example_mask.setPos(center) #which is true for trials with indices of >= 5
		example_target.setPos(center)
		example_foil.setPos(center)

	if fixation_cross == True: #implement a fixation cross, if requested
		fix.draw()
		win.flip()
		wait(0.1) #fixation cross is shown for 100ms before trial onset
		wait(0.008) #wait for half a frame to counteract refresh rate imprecisions

	#forward masking / (first half of the sandwich masking)
	if mask_forw == True:
		example_mask.draw()
		win.flip()
		wait((mask_forw_durat-0.008)) #display the mask for the requested duration (minus half a frame)

	#show stimulus
	wait(0.008) #Note to reviewer: I'm not quite sure I remember this half-frame adjustment correctly, feel free to correct me
	if	N_types[trial_number] == 9: #if no stimulus is supposed to be shown
		wait(0) #do nothing
	elif N_types[trial_number] in [1, 2, 5]: #if a target stimulus is shown (i.e., if it has index number 1, 2, or 5)
		example_target.draw()
	else: #if a foil stimulus is shown
		example_foil.draw()
	win.flip()
	wait((target_durat-0.008))

	#backward masking / (second half of the sandwich masking)
Exemplo n.º 10
0
sample_aid_long = ImageStim(
    win,
    image=
    "C:\Users\lasch\OneDrive\Documents\Wright State\Research\Cara_experiment_code\intLong.png",
    pos=[7, 0])
aid = TextStim(
    win,
    text=
    """Examples of long and short bars with automated aid \n \nPress any key to continue""",
    wrapWidth=40,
    units='deg',
    pos=[0, 10],
    height=1,
    color='White')

sample_aid_long.draw()
sample_aid_short.draw()
aid.draw()
win.flip()
waitKeys()

questions = TextStim(
    win,
    text=
    """If you have any questions, please ask the researcher now.\n\nPress any key to start""",
    wrapWidth=20,
    units='deg',
    pos=[0, 0],
    height=1,
    color='White')
questions.draw()
Exemplo n.º 11
0
        win,
        curr_smil + '.png',
    )
    stim_img.size *= 0.5  # make a bit smaller

    # Initially, onset is undefined
    cond_df.loc[idx, 'onset'] = -1

    trial_clock.reset()
    kb.clock.reset()
    while trial_clock.getTime() < 2:
        # Draw stuff

        if trial_clock.getTime() < 0.5:
            stim_txt.draw()
            stim_img.draw()
        else:
            fix_target.draw()

        win.flip()
        if cond_df.loc[idx, 'onset'] == -1:
            cond_df.loc[idx, 'onset'] = clock.getTime()

        # Get responses
        resp = kb.getKeys()
        if resp:
            # Stop the experiment when 'q' is pressed
            if 'q' in resp:
                quit()

            # Log reaction time and response
Exemplo n.º 12
0
intro1.run()

# introduction 2
intro2 = ShowAndConfirm(win, 'imgs/intro2.png', '确认')
intro2.run()

# practice
practice_title = TextStim(win, text='练习', height=0.1, pos=(0, 0.5), units='norm', color=(0, 0, 0), colorSpace='rgb255')
practice = ImageStim(win, image='imgs/practice.png', pos=(0, 0.2), units='norm')
practice_hint = TextStim(win, text='价格', height=0.05, pos=(-0.15, 0), units='norm', color=(0, 0, 0), colorSpace='rgb255')
practice_text = TextStim(win, text='¥9999', height=0.05, pos=(0, 0), units='norm', color=(0, 0, 0), colorSpace='rgb255')
practice_cover = SimpleCover(win, pos=(0, 0), name='价格')
button_practice = Button(win, (0, -0.5), width=0.1, height=0.05, name='button_practice', text='正式开始')
while button_practice.state != button_practice.END:
    practice_title.draw()
    practice.draw()
    practice_hint.draw()
    practice_text.draw()
    practice_cover.process()
    practice_cover.draw()
    button_practice.process()
    button_practice.draw()
    win.flip()

# tests
tests = sorted(os.listdir('tests'))
for test_file in tests:
    trial = Trial(win=win, test_file=test_file, sum_file=sum_file, detail_file=detail_file, sub_id=sub_id, big_support=big_support)
    trial.run()
    trial.save()
DISPSIZE = (1400,800)
BGC = (-1,-1,-1)
score = 0

win = Window(size=DISPSIZE, units='pix', fullscr=False, color=BGC)
target = ImageStim(win, 'target.png', size = (420, 420)) # i created this target in photoshop
mouse = Mouse(win)

mouse_click_clock = Clock()

# The game starts now by drawing the target at a random location:

move_target_at_random_pos(target)

while True:
    target.draw()  
    win.flip()
    
    # since I am still to develop the game, I give myself the option to stop it
    # at any time by pressing 'q' (avoiding the otherwise infinite loop)
    
    keys_pressed = getKeys()
    if 'q' in keys_pressed:
        break
  
    mouse_is_pressed = mouse.getPressed()[0] == True
    
    # Check for a mouse click every 0.2s, so that we don't accept more than 1
    # press on mouse hold
    if mouse_is_pressed and mouse_click_clock.getTime() > 0.2:
        mouse_click_clock.reset()
def run():

    from psychopy.visual import Window, TextStim, ImageStim
    from psychopy.core import wait
    from psychopy.event import getKeys, waitKeys, clearEvents
    from numpy.random import shuffle
    from psychopy import gui
    import numpy as np
    import random
    '''
	Next, we want to create the window in which the experiment takes place and open up a log file.
	'''
    #create window
    DISPSIZE = (1000, 700)
    #in case that doesn't work, use DISPSIZE = (1000,700)
    #for windows only DISPSIZE = (GetSystemMetrics(0),GetSystemMetrics(1))
    BGC = 'white'

    #log file
    log = open('logfileprisonersdilemma.txt', 'w')
    log.write('trial round\topponent strategy\participant strategy\n'
              )  #insert headers of what should be logged
    '''
	Now we create the objects we will use. 
	The code here is in the same order as it will be used once we start the game. 
	We'll start with the objects for introduction and instruction.
	
	'''
    win = Window(size=DISPSIZE, units='pix', color=BGC, fullscr=False)
    backgroundimage = ImageStim(win, 'prisonwall.png', size=(1000, 1000))
    #objects for introduction and instruction
    #introduction text
    subject_name = 'Kathi'

    introstr = f'''
	Welcome to the prisoner's dilemma game, {subject_name}!
	This game will take about 10 minutes. 
	Please wait for further instructions after you've finished.
	Press 'space' to continue. 
	'''

    introtxt = TextStim(win,
                        text=introstr,
                        font='Arial',
                        height=30,
                        color='white',
                        wrapWidth=400)

    #instruction text
    inststr = '''
	Imagine you are one of two people being questioned about the same crime. They are each talking to the interrogator separately. The interrogator gives each person the same deal: 
	they can choose to vouch for the other person’s innocence (COOPERATING) or rat them out (DEFECTING). 
	And of course, there’s a twist. If both people cooperate with each other, they’ll each get 3 months off their sentence, 
	but if the first person vouches for the second person, and the second person rats them out, 
	the first person will get no time off their sentence and the second person will get 5 months off their time. 
	Lastly, if they both rat each other out, they each get 1 month off their time.
	
	Press 'space' to start the game.
	'''

    insttxt = TextStim(win,
                       text=inststr,
                       font='Arial',
                       height=25,
                       color='white',
                       wrapWidth=900,
                       pos=(000, -70))
    '''
	Participants as well as their opponent are represented in the game by avatars. These objects are used for explaining this and defining the image objects. 
	These are avatars you can use created with www.hexatar.com, however you are free to use your own. 
	
	This is redunant since I coulnd't figure it out, but I wanted to keep it for the future.
	'''
    #objects for representing participants, images
    #telling people to choose avatar
    avatstr = '''
	Please choose one of these avatars to represent you in the game.
	Just press the key that responds to the letter next to the image.
	'''
    avattxt = TextStim(win,
                       text=avatstr,
                       font='Arial',
                       height=20,
                       color='black',
                       wrapWidth=900,
                       pos=(000, -300))

    #avatars: created with http://www.hexatar.com
    partoverview = ImageStim(
        win, image='partchoice.png', size=(500, 500)
    )  #start screen from which participant chooses an avatar to represent them in the game
    '''
	Here we define objects during the actual game: instructions about controls, a 
	connecting screen, text to be displayed after every round and a goodbye screen.
	'''
    #objects for during the game, in the loop
    sentcountp = 35
    sentcounto = 35

    #info about controls/gameplay, should be displayed on the bottom left during the game
    controlinfo = TextStim(
        win,
        text=
        '''Press the left arrow to defect and the right arrow to cooperate''',
        font='Arial',
        height=20,
        color='white',
        wrapWidth=900,
        pos=(000, -300))

    # txt within game
    connectstr = f'Your prison sentence is {sentcountp} months.\n'
    'Your partner`s sentence is {sentcounto} months.\n'
    'The authorities are still not sure what to do with the two of you. Therefore, you and your partner\n'
    'will be interrogated again by a different police officer. Again you have the choice to cooperate or defect.'

    connecttxt = TextStim(win,
                          text=connectstr,
                          font='Arial',
                          height=20,
                          color='black',
                          wrapWidth=400)
    cooptxt = TextStim(win,
                       text='Your opponent chose to cooperate.',
                       font='Arial',
                       height=20,
                       color='black',
                       wrapWidth=400)
    deftxt = TextStim(win,
                      text='Your opponent chose to defect.',
                      font='Arial',
                      height=20,
                      color='black',
                      wrapWidth=400)

    #goodbye screen
    goodbyestr = ('The game is now over.\n' + 'Thank you for playing!\n')
    goodbye = TextStim(win,
                       text=goodbyestr,
                       font='Arial',
                       height=40,
                       color='black',
                       wrapWidth=500)

    strategy = [1, 2, 3, 4, 5]  #random assignment of opponents strategy
    shuffle(strategy)
    randostrategy = [1, 2]  #for strategy 3
    condlist = [1, 2, 3]  #1 is in-group, 2 is outgroup, 3 is anon
    ntrials = 7
    oppstrategy = '...'  #for updating the sentence counter

    #function that determines participants sentence and adds it to the sentence counter
    #add unitest here
    '''
	During the experiment, we need to update how many months the participant has
	to spend in prison now, depending on the choice they made and the choice their
	opponent made. For doing this during the trial loop, we write the function
	sentencetracker, that checks the participants choice (either cooperating or
	defecting) as well as the opponents strategy and updates the sentence based on this.
	As a reminder: left arrow to defect and the right arrow to cooperate.
	'''
    def sentencetracker(sentcounto, sentcountp, response, oppstrategy):
        if response == 'right' and oppstrategy == 'cooperation':  #both cooperate
            sentcounto -= 3
            sentcountp -= 3
        elif response == 'right' and oppstrategy == 'defect':  #participant wants to cooperate,  but opponent rats them out
            sentcountp -= 5
        elif response == 'left' and oppstrategy == 'cooperation':  #participant rats opponent out, but opponent cooperates
            sentcounto -= 5
        else:  #response == 'left' & oppstrategy == 'defect': #both defect
            sentcountp -= 1
            sentcounto -= 1
        return sentcounto, sentcountp

    '''
	Time to start the experiment!
	Let's start with the introduction. After that, we explain how it works. 
	We also define the image stimuli for displaying the avatars.
	'''
    backgroundimage.draw()  #background prisonwall
    introtxt.draw()
    win.flip()
    waitKeys(keyList=['space'
                      ])  #wait until participant pressed space to continue
    clearEvents()
    ''' that part worked but couldn't figure out avatar assignment :()
	#choosing avatar that represents participant 
	avattxt.draw()
	partoverview.draw()
	win.flip()
	aresponse = waitKeys(keyList = ['a','b','c','d'])
	
	shuffle(condlist) #randomly assigning condition (in group, out group, anonymous opponent)
	#condition = condlist[1]
	'''
    opponent = ImageStim(win, image="opponent1.png", pos=(300, 000))
    participant = ImageStim(win, image='partA.png', pos=(-300, 000))
    ''' was supposed to assign condition and set the right avatars, but doesn't work
	condition = np.random.randint(1,3)
	if condition == 1: #playing with an in-group member
		print('in-group condition')
		if aresponse == 'a': #participant is female caucasian
			opponent = ImageStim(win, image="opponent2.png", pos=(300,000))
			participant = ImageStim(win, image='partA.png', pos=(-300, 000))
		elif aresponse == 'c': #participant is male caucasian 
			opponent = ImageStim(win, image="opponent2.png", pos=(300,000))
			participant = ImageStim(win, image='partC.png', pos=(-300, 000))
		elif aresponse == 'b': #participant is female non-caucasian
			opponent = ImageStim(win, image="opponent1.png", pos=(300,000))
			participant = ImageStim(win, image='partB.png', pos=(-300, 000))
		elif aresponse == 'd': #option d, participant is male non-caucasian
			opponent = ImageStim(win, image="opponent1.png", pos=(300,000))
			participant = ImageStim(win, image='partD.png', pos=(-300, 000))
		
		
		
		
	elif condition == 2: #playing with an out-group member
		print('out-group condition')
		if aresponse == 'a': #participant is female caucasian
			opponent = ImageStim(win, image="opponent1.png", pos=(300,000))
			participant = ImageStim(win, image='partA.png', pos=(-300, 000))
			
		elif aresponse == 'c': #participant is male caucasian 
			opponent = ImageStim(win, image="opponent1.png", pos=(300,000))
			participant = ImageStim(win, image='partC.png', pos=(-300, 000))
			
		elif aresponse == 'b': #participant is female non-caucasian
			opponent = ImageStim(win, image="opponent2.png", pos=(300,000))
			participant = ImageStim(win, image='partB.png', pos=(-300, 000))
			
		elif aresponse == 'd': #option d, participant is male non-caucasian
			opponent = ImageStim(win, image="opponent2.png", pos=(300,000))
			participant = ImageStim(win, image='partD.png', pos=(-300, 000))
			
		
		
	
	elif condition == 3: #playing with no information about opponent
		print('anonymous condition')
		opponent = ImageStim(win, image="anonymous.jpg", pos=(300,000))
		if aresponse == 'a': #participant is female caucasian
			participant = ImageStim(win, image='partA.png', pos=(-300, 000))
			 
		elif aresponse == 'c': #participant is male caucasian 
			participant = ImageStim(win, image='partC.png', pos=(-300, 000))
			
		elif aresponse == 'b': #participant is female non-caucasian
			participant = ImageStim(win, image='partB.png', pos=(-300, 000))
			
		elif aresponse == 'd': #option d, participant is male non-caucasian
			participant = ImageStim(win, image='partD.png', pos=(-300, 000))
			
		
	
	clearEvents()
	'''

    #explaining the game
    backgroundimage.draw()
    insttxt.draw()
    win.flip()
    waitKeys(
        keyList=['space']
    )  #wait until participant read instructions and pressed space to start the trial loop
    strategy = np.random.randint(1, 5)
    '''
	Sentence count for the participant and the opponent. You can change this according to your needs, 
	however please note that it's 35 because we defined 7 trial rounds and the maximum the 
	sentence can change during each round is 5. 7 x 5 is 35, so this is set to prevent the sentence count
	from going below 0.
	'''
    sentcounto = 35
    sentcountp = 35
    '''
	This is the trial loop, it's now set to 7 rounds (see object ntrials = 7 above to change it).
	Opponents stick to the same strategy through all 7 rounds. 
	Sentence count as well as strategies are printed in the console as well as logged in the log file.
	'''

    i = 0
    for i in range(ntrials):
        backgroundimage.draw()
        i += 1
        log.write(str(i))
        log.write('\t')

        #opponent always cooperates
        if strategy == 1:
            opponent.draw()
            participant.draw()
            controlinfo.draw()
            win.flip()
            log.write('strategy cooperation\t')
            response = waitKeys(keyList=['left', 'right'])
            if response == 'left':
                log.write('defect\n')
            elif response == 'right':
                log.write('cooperate\n')
            cooptxt.draw()
            win.flip()
            wait(4)  #seconds
            oppstrategy = 'cooperation'
            print('strategy cooperation')
            sentcounto, sentcountp = sentencetracker(sentcounto, sentcountp,
                                                     response, oppstrategy)
            print(sentcounto, sentcountp)
            connectstr = f'''Your prison sentence is {sentcountp} months.
	Your partner`s sentence is {sentcounto} months.
	The authorities are still not sure what to do with the two of you. 
	Therefore, you and your partner will be interrogated again by a different police officer. 
	Again you have the choice to cooperate or defect.'''
            connecttxt = TextStim(win,
                                  text=connectstr,
                                  font='Arial',
                                  height=20,
                                  color='black',
                                  wrapWidth=400)
            connecttxt.draw()
            win.flip()
            wait(7)

        #opponent always defects
        elif strategy == 2:
            opponent.draw()
            participant.draw()
            controlinfo.draw()
            win.flip()
            log.write('strategy defect\t')
            response = waitKeys(keyList=['left', 'right'])
            if response == 'left':
                log.write('defect\n')
            elif response == 'right':
                log.write('cooperate\n')
            deftxt.draw()
            win.flip()
            wait(4)  #seconds
            oppstrategy = 'defect'
            print('strategy defect')
            sentcounto, sentcountp = sentencetracker(sentcounto, sentcountp,
                                                     response, oppstrategy)
            print(sentcounto, sentcountp)
            connectstr = f'''Your prison sentence is {sentcountp} months.
	Your partner`s sentence is {sentcounto} months.
	The authorities are still not sure what to do with the two of you. 
	Therefore, you and your partner will be interrogated again by a different police officer. 
	Again you have the choice to cooperate or defect.'''
            connecttxt = TextStim(win,
                                  text=connectstr,
                                  font='Arial',
                                  height=20,
                                  color='black',
                                  wrapWidth=400)
            connecttxt.draw()
            win.flip()
            wait(7)

        #opponent cooperates or defects on a random basis
        elif strategy == 3:
            rando = np.random.randint(1, 3)
            print('rando')
            if rando == 1:
                opponent.draw()
                participant.draw()
                controlinfo.draw()
                win.flip()
                log.write('strategy random cooperation\t')
                response = waitKeys(keyList=['left', 'right'])
                if response == 'left':
                    log.write('defect\n')
                elif response == 'right':
                    log.write('cooperate\n')
                cooptxt.draw()
                win.flip()
                wait(4)
                oppstrategy = 'cooperation'
                print('rando coop')
                sentcounto, sentcountp = sentencetracker(
                    sentcounto, sentcountp, response, oppstrategy)
                print(sentcounto, sentcountp)
                connectstr = f'''Your prison sentence is {sentcountp} months.
	Your partner`s sentence is {sentcounto} months.
	The authorities are still not sure what to do with the two of you. 
	Therefore, you and your partner will be interrogated again by a different police officer. 
	Again you have the choice to cooperate or defect.'''
                connecttxt = TextStim(win,
                                      text=connectstr,
                                      font='Arial',
                                      height=20,
                                      color='black',
                                      wrapWidth=400)
                connecttxt.draw()
                win.flip()
                wait(7)
            else:
                opponent.draw()
                participant.draw()
                controlinfo.draw()
                win.flip()
                log.write('strategy random defect\t')
                wait(4)
                response = waitKeys(keyList=['left', 'right'])
                if response == 'left':
                    log.write('defect\n')
                elif response == 'right':
                    log.write('cooperate\n')
                deftxt.draw()
                win.flip()
                wait(4)  #seconds
                oppstrategy = 'defect'
                print('rando defect')
                sentcounto, sentcountp = sentencetracker(
                    sentcounto, sentcountp, response, oppstrategy)
                print(sentcounto, sentcountp)
                connectstr = f'''Your prison sentence is {sentcountp} months.
	Your partner`s sentence is {sentcounto} months.
	The authorities are still not sure what to do with the two of you. 
	Therefore, you and your partner will be interrogated again by a different police officer. 
	Again you have the choice to cooperate or defect.'''
                connecttxt = TextStim(win,
                                      text=connectstr,
                                      font='Arial',
                                      height=20,
                                      color='black',
                                      wrapWidth=400)
                connecttxt.draw()
                win.flip()
                wait(7)

        elif strategy == 4:
            print('nice tit for tat')
            log.write('strategy nice tit for tat\t')
            if i == 1:
                opponent.draw()
                participant.draw()
                controlinfo.draw()
                win.flip()
                response = waitKeys(keyList=['left', 'right'])
                if response == 'left':
                    log.write('defect\n')
                elif response == 'right':
                    log.write('cooperate\n')
                cooptxt.draw()
                win.flip()
                wait(4)
                oppstrategy = 'cooperation'
                print('cooperation')
                sentcounto, sentcountp = sentencetracker(
                    sentcounto, sentcountp, response, oppstrategy)
                print(sentcounto, sentcountp)
                connectstr = f'''Your prison sentence is {sentcountp} months.
	Your partner`s sentence is {sentcounto} months.
	The authorities are still not sure what to do with the two of you. 
	Therefore, you and your partner will be interrogated again by a different police officer. 
	Again you have the choice to cooperate or defect.'''
                connecttxt = TextStim(win,
                                      text=connectstr,
                                      font='Arial',
                                      height=20,
                                      color='black',
                                      wrapWidth=400)
                connecttxt.draw()
                win.flip()
                wait(7)  #seconds

            elif i > 1:
                if response == 'right':
                    opponent.draw()
                    participant.draw()
                    controlinfo.draw()
                    win.flip()
                    response = waitKeys(keyList=['left', 'right'])
                    if response == 'left':
                        log.write('defect\n')
                    elif response == 'right':
                        log.write('cooperate\n')
                    cooptxt.draw()
                    win.flip()
                    wait(4)
                    oppstrategy = 'cooperation'
                    print('cooperation')
                    sentcounto, sentcountp = sentencetracker(
                        sentcounto, sentcountp, response, oppstrategy)
                    print(sentcounto, sentcountp)
                    connectstr = f'''Your prison sentence is {sentcountp} months.
	Your partner`s sentence is {sentcounto} months.
	The authorities are still not sure what to do with the two of you. 
	Therefore, you and your partner will be interrogated again by a different police officer. 
	Again you have the choice to cooperate or defect.'''
                    connecttxt = TextStim(win,
                                          text=connectstr,
                                          font='Arial',
                                          height=20,
                                          color='black',
                                          wrapWidth=400)
                    connecttxt.draw()
                    win.flip()
                    wait(7)  #seconds

                elif response == 'left':
                    opponent.draw()
                    participant.draw()
                    controlinfo.draw()
                    win.flip()
                    response = waitKeys(keyList=['left', 'right'])
                    if response == 'left':
                        log.write('defect\n')
                    elif response == 'right':
                        log.write('cooperate\n')
                    deftxt.draw()
                    win.flip()
                    wait(4)
                    oppstrategy = 'defect'
                    print('defect')
                    sentcounto, sentcountp = sentencetracker(
                        sentcounto, sentcountp, response, oppstrategy)
                    print(sentcounto, sentcountp)
                    connectstr = f'''Your prison sentence is {sentcountp} months.
	Your partner`s sentence is {sentcounto} months.
	The authorities are still not sure what to do with the two of you. 
	Therefore, you and your partner will be interrogated again by a different police officer. 
	Again you have the choice to cooperate or defect.'''
                    connecttxt = TextStim(win,
                                          text=connectstr,
                                          font='Arial',
                                          height=20,
                                          color='black',
                                          wrapWidth=400)
                    connecttxt.draw()
                    win.flip()
                    wait(7)  #seconds

        elif strategy == 5:
            print('suspicious tit for tat')
            log.write('strategy suspicious tit for tat\t')
            if i == 1:
                opponent.draw()
                participant.draw()
                controlinfo.draw()
                win.flip()
                response = waitKeys(keyList=['left', 'right'])
                if response == 'left':
                    log.write('defect\n')
                elif response == 'right':
                    log.write('cooperate\n')
                deftxt.draw()
                win.flip()
                wait(4)
                oppstrategy = 'defect'
                print('defect')
                sentcounto, sentcountp = sentencetracker(
                    sentcounto, sentcountp, response, oppstrategy)
                print(sentcounto, sentcountp)
                connectstr = f'''Your prison sentence is {sentcountp} months.
		Your partner`s sentence is {sentcounto} months.
		The authorities are still not sure what to do with the two of you. 
		Therefore, you and your partner will be interrogated again by a different police officer. 
		Again you have the choice to cooperate or defect.'''
                connecttxt = TextStim(win,
                                      text=connectstr,
                                      font='Arial',
                                      height=20,
                                      color='black',
                                      wrapWidth=400)
                connecttxt.draw()
                win.flip()
                wait(7)  #seconds

            elif i > 1:
                if response == 'right':
                    opponent.draw()
                    participant.draw()
                    controlinfo.draw()
                    win.flip()
                    response = waitKeys(keyList=['left', 'right'])
                    if response == 'left':
                        log.write('defect\n')
                    elif response == 'right':
                        log.write('cooperate\n')
                    cooptxt.draw()
                    win.flip()
                    wait(4)
                    oppstrategy = 'cooperation'
                    print('cooperation')
                    sentcounto, sentcountp = sentencetracker(
                        sentcounto, sentcountp, response, oppstrategy)
                    print(sentcounto, sentcountp)
                    connectstr = f'''Your prison sentence is {sentcountp} months.
		Your partner`s sentence is {sentcounto} months.
		The authorities are still not sure what to do with the two of you. 
		Therefore, you and your partner will be interrogated again by a different police officer. 
		Again you have the choice to cooperate or defect.'''
                    connecttxt = TextStim(win,
                                          text=connectstr,
                                          font='Arial',
                                          height=20,
                                          color='black',
                                          wrapWidth=400)
                    connecttxt.draw()
                    win.flip()
                    wait(7)  #seconds

                elif response == 'left':
                    opponent.draw()
                    participant.draw()
                    controlinfo.draw()
                    win.flip()
                    response = waitKeys(keyList=['left', 'right'])
                    if response == 'left':
                        log.write('defect\n')
                    elif response == 'right':
                        log.write('cooperate\n')
                    deftxt.draw()
                    win.flip()
                    wait(4)
                    oppstrategy = 'defect'
                    print('defect')
                    sentcounto, sentcountp = sentencetracker(
                        sentcounto, sentcountp, response, oppstrategy)
                    print(sentcounto, sentcountp)
                    connectstr = f'''Your prison sentence is {sentcountp} months.
		Your partner`s sentence is {sentcounto} months.
		The authorities are still not sure what to do with the two of you. 
		Therefore, you and your partner will be interrogated again by a different police officer. 
		Again you have the choice to cooperate or defect.'''
                    connecttxt = TextStim(win,
                                          text=connectstr,
                                          font='Arial',
                                          height=20,
                                          color='black',
                                          wrapWidth=400)
                    connecttxt.draw()
                    win.flip()
                    wait(7)  #seconds

        #exit early:
        quitt = getKeys(keyList='q')
        if len(quitt) > 0:
            break

    goodbye.draw()
    win.flip()
    wait(3)

    win.close()
    log.close()
Exemplo n.º 15
0
    def RunTrialECog(self, image, phase):
        """Runs a particular trial for an ECog (Electrocorticography) based 
        task. An ECog trial runs as follows: display the image along with
        the black box for <trial duration> amount of time, clear the screen
        for <ISI> amount of time, then asking for and getting subject input
        for <ITI> amount of time.

        image: the stimuli to display on screen
        phase: 0 (Study Phase) - prompts user "Indoor / Outdoor"
               1 (Test Phase) - prompts user "Old / New"
        return: [keyPress, reactionTime]
        """
        theImage = ImageStim(self.window)
        #Set the full path of the image, based on the image's lure type
        if (image[0][5] == "3"):
            image = (self.imgSnglDir + '%s' % (image[0]))
        elif ((image[0][5] == "1") or (image[0][5] == "2")):
            image = (self.lureHighDir + '%s' % (image[0]))
        elif ((image[0][5] == "4") or (image[0][5] == "5")):
            image = (self.lureLowDir + '%s' % (image[0]))

        theImage.setImage(image)
        imageSize = self.ScaleImage(image, self.imageWidth)
        theImage.setSize(imageSize)

        ecogISI = 0.5
        posLeftText = (-(self.window.size[0] / 8), 0)
        posRightText = ((self.window.size[0] / 8), 0)
        if (phase == 0):
            ecogTrialDur = 2.0
            leftMsg = "Indoor\n\n    1"
            rightMsg = "Outdoor\n\n     2"
        else:
            ecogTrialDur = 1.0
            leftMsg = "Old\n\n  1"
            rightMsg = "New\n\n  2"

        theImage.draw(self.window)
        self.blackBox.draw(self.window)
        self.window.flip()
        wait(ecogTrialDur, ecogTrialDur)
        self.window.flip()
        wait(ecogISI, ecogISI)
        textLeft = TextStim(self.window,
                            text=leftMsg,
                            pos=posLeftText,
                            color='Black',
                            height=50)
        textRight = TextStim(self.window,
                             text=rightMsg,
                             pos=posRightText,
                             color='Black',
                             height=50)
        textLeft.draw(self.window)
        textRight.draw(self.window)
        self.window.flip()
        clearEvents()
        self.clock.reset()
        keyPresses = waitKeys(keyList=['1', '2', 'space', 'escape'],
                              timeStamped=self.clock,
                              maxWait=1.5)
        self.window.flip()
        random.shuffle(self.rangeITI)
        wait(self.rangeITI[0], self.rangeITI[0])

        if (not keyPresses):
            return '', 0
        return keyPresses[0][0], keyPresses[0][1]
Exemplo n.º 16
0
class Display:

    def __init__(self, pars):
        self.win = initializers.setup_window()
        self.pars = pars
        self.geom = initializers.setup_geometry(self.win, self.pars)
        self.rotation_clocks = [None] * self.geom['numtargs']
        self.type = ['default'] * self.geom['numtargs']

        self.setup_sounds()
        self.setup_images()
        self.setup_text()

    def setup_sounds(self):
        self.cashsnd = Sound('resources/cash.wav')
        self.firesnd = Sound('resources/bbhit.wav')
        self.buzzsnd = Sound('resources/buzz.wav')

    def setup_images(self):
        self.notargs = []
        self.gotargs = []
        self.deftargs = []
        self.bkimg = ImageStim(self.win, image='resources/pond.jpg',
                               units='norm', size=(2.0, 2.0))

        for targ in range(self.geom['numtargs']):
            self.notargs.append(ImageStim(self.win,
                                          image='resources/rfrog2.jpg',
                                          size=self.geom['target_size'],
                                          pos=self.geom['target_centers'][targ]))
            self.gotargs.append(ImageStim(self.win,
                                          image='resources/gfrog2.jpg',
                                          size=self.geom['target_size'],
                                          pos=self.geom['target_centers'][targ]))
            self.deftargs.append(ImageStim(self.win,
                                           image='resources/lilypad.jpg',
                                           size=self.geom['target_size'],
                                           pos=self.geom['target_centers'][targ]))

        # set initial target stims to be the defaults
        self.targets = []
        for targ in self.deftargs:
            self.targets.append(targ)

    def setup_text(self):
        self.scoretxt = TextStim(self.win, text="Total Points: ",
                                 font='Helvetica', alignHoriz='left', alignVert='top', units='norm',
                                 pos=(-1, 1), height=0.2, color=[178, 34, 34], colorSpace='rgb255',
                                 wrapWidth=2)

        self.targtxt = []
        for targ in range(self.geom['numtargs']):
            self.targtxt.append(TextStim(self.win,
                                         pos=self.geom['target_centers'][targ],
                                         color='White', units='height', height=0.05, text=''))

    def set_target_image(self, index, value='default'):
        if value == 'go':
            self.targets[index] = self.gotargs[index]
        elif value == 'no':
            self.targets[index] = self.notargs[index]
        elif value == 'default':
            self.targets[index] = self.deftargs[index]

    def set_target_text(self, index, value):
        self.targtxt[index].setText(value)

    def set_score(self, pts):
        self.scoretxt.setText('Total Points: ' + str(pts))

    def onset(self, index, value):
        self.rotation_clocks[index] = Clock()
        self.type[index] = value

    def offset(self, index):
        self.rotation_clocks[index] = Clock()
        self.type[index] = 'default'

    def update(self):
        # for each target with clock running (i.e., rotating) ...
        for idx, clk in enumerate(self.rotation_clocks):
            if clk:
                rot_time = clk.getTime()
                rot_dur = self.pars['rot_dur']

                if rot_time > rot_dur:
                    rotfrac = -1  # rotation completed
                else:
                    rotfrac = cos(pi * rot_time / self.pars['rot_dur'])

                # adjust target size to give illusion of rotation
                base_size = self.geom['target_size']
                self.targets[idx].size = (abs(rotfrac) * base_size[0],
                                          base_size[1])

                # set correct image on target based on rotation angle
                if rotfrac < 0:
                    self.set_target_image(idx, self.type[idx])

    def draw(self):
        self.update()
        self.bkimg.draw()
        self.scoretxt.draw()
        for stim in self.targets:
            stim.draw()
        for stim in self.targtxt:
            stim.draw()
        self.win.flip()

    def close(self):
        self.win.close()
Exemplo n.º 17
0
class StimulusResource(Resource):
    should_stop = False

    def __enter__(self):
        from psychopy.visual import ImageStim  # eats some time
        from psychopy.visual import TextStim
        event.clearEvents()
        win = self.window.instance
        self.textstim = TextStim(win, text='')
        # image texture index order is iamge[y, x]
        self.instance = ImageStim(
            win=win,
            units='deg',  #, filpVert=True,
            pos=self.component.position,
            size=self.component.size)  #misc.pix2deg(win.size, win.monitor)*2)
        try:
            self.interval = self.window.get_isi()
        except Exception as e:
            raise ServiceRuntimeException(
                'Could not acquire window object. Please try again')
        return self

    @memoized_property
    def trials(self):
        from psychopy.data import TrialHandler  # eats some time
        sqf = self.component.square_factor
        self.image = np.zeros((sqf, sqf))
        conditions = [
            Condition(x, y, v)
            for x, y, v in product(range(sqf), range(sqf), [-1, 1])
        ]
        ts = [
            Trial(self, cond, self.component.on_duration, self.interval)
            for cond in conditions
        ]
        return TrialHandler(
            ts,
            nReps=self.component.repetition,
            method=('random' if self.component.randomize else 'sequential'))

    @property
    def synced(self):
        self.clock.synchronize(self)
        return iter(self)

    def __iter__(self):
        trials = self.trials
        clock = self.clock.instance
        clock.reset()
        for trial in trials:
            self.update_trial(trial)
            logging.msg('Entering trial #%s...' % trials.thisN)
            trials.addData('on_time', clock.getTime())
            yield trial.start()
            trials.addData('off_time', clock.getTime())
            self.flip_blank()
            core.wait(self.component.off_duration)
            self.instance.opacity = 1.0
            if self.should_stop:
                logging.msg('UserAbortException raised!')
                raise UserAbortException()

    def update_trial(self, trial):
        cond = trial.condition
        self.image[cond.y, cond.x] = cond.v
        self.instance.image = self.image
        self.instance.draw()
        self.image[cond.y, cond.x] = 0

    # def update_phase(self, trial):
    #     now = trial.tick()
    #     self.instance.phase = np.mod(now * trial.condition.tf, 1)
    #     self.instance.draw()
    #     self.window.flip()
    def flip_text(self, text):
        self.textstim.setText(text)
        self.textstim.draw()
        self.window.flip()

    def flip_blank(self):
        self.instance.opacity = 0.0
        self.instance.draw()
        self.window.flip()
Exemplo n.º 18
0
)  # call the whoAmI -> double while loop to save the user taped response
userResponse(
    '', False, qpos, 'images/Hello.gif'
)  # call the userResponse -> double while loop to save the user taped response

# ----------------------------------- #
# SETTING FOR THE PRE-TEST            #
# WHILE THE PRE-TEST IS NOT SUCCEEDED #
# ----------------------------------- #
response = ''  # the response attempted by the user - On commence avec une réponse vide
while response != pretest:  # while the answer is not correct
    response = ''  # the response written by the user - On commence avec une chaîne vide
    respstim = TextStim(disp, text='', pos=qpos, height=size,
                        color=color)  # stimulus texte
    qstim = ImageStim(disp, image='images/TradVonat.gif')
    qstim.draw()  # dessiner la question
    disp.flip()  # passer au screen au suivant -> on met la question par-dessus
    core.wait(
        loadTime)  # delay of 10 seconds before passing to the learning phase
    response, done = tapeAnswer(
        response, False, False)  # While loop to taping the entire answer

    # ------------------------------------------------------- #
    # CHECK IF THE PRETEST IS SUCCEEDED OR NOT                #
    # DISPLAY A MESSAGE TO THE USER ACCORDING TO THE ANSWER   #
    # ------------------------------------------------------- #
    if response == pretest:  # if the answer is correct
        userResponse(
            '', False, qpos, 'images/BravoVonat.gif'
        )  # call the userResponse -> double while loop to save the user taped response
    else:  # if the answer is NOT correct
def main():
    # I set up my siplay size and background colour
    DISPSIZE = (1400, 800)
    BGC = (-1, -1, -1)

    # for my game I need to create some variables:
    score = 0
    lives = 3
    level = 1
    mouse_x = 0
    mouse_y = 0

    # I create some objects:
    win = Window(size=DISPSIZE, units='pix', fullscr=False, color=BGC)

    mouse = Mouse(win)

    target = ImageStim(win, 'target.png', size=(420, 420))

    # I will display three text stimuli to the player while playing the game:
    lives_count = TextStim(
        win,
        text=f'Lives = {lives}',
        height=35,
        color=(1, 0.2, 0.6),
        pos=(100, 330),
    )

    score_count = TextStim(win,
                           text=f'Score = {score}',
                           height=35,
                           color=(0.2, 0.2, 0.8),
                           pos=(450, 330))

    level_count = TextStim(win,
                           text=f'Level = {level}',
                           height=35,
                           color=(1, -0.5, 1),
                           pos=(850, 330))

    # I define the messages to show the player the outcome of the game:
    you_have_lost = TextStim(
        win,
        text='Boo! Not a great game, pal... Get it together!',
        height=35,
        color=(0.2, 0.2, 0.8),
        pos=(250, 230))

    you_have_won = TextStim(win,
                            text='Yey! Well done, champ! Time to celebrate!',
                            height=35,
                            color=(0.2, 0.2, 0.8),
                            pos=(250, 230))

    # These are the images I use for the winning and loosing scenarios:
    looser = ImageStim(win, 'failed.jpg', pos=(0, -100), size=(420, 420))
    winner = ImageStim(win, 'tiny_trash.jpg', pos=(0, -100), size=(420, 420))

    # I introduce this dialog to save the user's ID:
    user_id_dialog = gui.Dlg(title="Target Game")
    user_id_dialog.addText('Please write your subject ID: a 4-digit code')
    user_id_dialog.addField('Subject ID:')
    ok_data = user_id_dialog.show()  # show dialog and wait for OK or Cancel

    if not user_id_dialog.OK:
        print('user cancelled')

    # NOW THE GAME WILL START:

    # If enabled, intro will play:
    enable_intro = True

    if enable_intro:
        show_intro(win)

    # We create this list to save our results into
    target_hits_per_level = [
        [],
        [],
        [],
        [],
    ]

    move_target_at_random_pos(
        target)  # first the target is shown on the screen

    lives_timer = CountdownTimer(
        5)  # Level 1 starts with 5 sec to hit the target
    mouse_click_clock = Clock()
    reaction_time_clock = Clock()
    change_target = False

    while level < 4 and lives > 0:
        target.draw()
        target_x, target_y = target.pos
        lives_count.draw()
        score_count.draw()
        level_count.draw()

        win.flip()

        keys_pressed = getKeys()
        if 'q' in keys_pressed:
            break
        mouse_is_pressed = mouse.getPressed()[0] == True

        mouse_x, mouse_y = mouse.getPos()
        level_count.setText(f'Level = {level}')

        #if the player does not click, the target moves and the player looses a life
        if lives_timer.getTime() <= 0:
            lives -= 1
            lives_count.setText(f'Lives = {lives}')
            mouse_in_target = None
            mouse_in_target_x = None
            mouse_in_target_y = None
            change_target = True

        # Check for a mouse click every 0.2s, so that we don't accept more than 1
        # press on mouse hold
        if mouse_is_pressed and mouse_click_clock.getTime() > 0.2:
            mouse_click_clock.reset()
            change_target = True

            if mouse_clicked_in_target(mouse, target):
                mouse_in_target = True
                mouse_in_target_x = mouse_x - target_x
                mouse_in_target_y = mouse_y - target_y
                score += 1
                score_count.setText(f'Score = {score}')

            else:
                lives -= 1
                lives_count.setText(f'Lives = {lives}')
                mouse_in_target = False
                mouse_in_target_x = None
                mouse_in_target_y = None

        if change_target:

            mouse_click = {
                'mouse_x': mouse_in_target_x,
                'mouse_y': mouse_in_target_y,
                'reaction_time': reaction_time_clock.getTime(),
                'mouse_in_target': mouse_in_target,
            }

            target_hits_per_level[level - 1].append(
                mouse_click)  # inddexes start from 0 --> level - 1

            if score == 5:
                lives_timer.reset(3)
                level = 2
            elif score == 10:
                lives_timer.reset(1)
                level = 3
            elif score == 15:
                level = 4

            move_target_at_random_pos(target)
            lives_timer.reset()
            reaction_time_clock.reset()
            change_target = False

    # Here we display the outcome of the game:
    if level == 4:
        you_have_won.draw()
        winner.draw()
    else:
        you_have_lost.draw()
        looser.draw()

    win.flip()
    wait(3)

    # Finally, we draw the overwivew for thr player

    draw_overview_target(
        win=win,
        level=1,
        target_pos=(-450, 0),
        text_pos=(50, 300),
        mouse_clicks_all_levels=target_hits_per_level,
    )

    draw_overview_target(
        win=win,
        level=2,
        target_pos=(0, 0),
        text_pos=(450, 300),
        mouse_clicks_all_levels=target_hits_per_level,
    )

    draw_overview_target(
        win=win,
        level=3,
        target_pos=(450, 0),
        text_pos=(850, 300),
        mouse_clicks_all_levels=target_hits_per_level,
    )

    win.flip()
    wait(4)

    # The user has not clicked Cancel on the subject ID window
    if ok_data is not None:
        write_results(target_hits_per_level, 'results-' + ok_data[0] + '.csv')

    win.close()
Exemplo n.º 20
0
tarstim['right']['congr']['H'] = ImageStim(disp, image="Rcongr_h.jpg")
tarstim['right']['congr']['L'] = ImageStim(disp, image="Rcongr_l.jpg")
tarstim['right']['incongr'] = {}
tarstim['right']['incongr']['H'] = ImageStim(disp, image="Rincongr_h.jpg")
tarstim['right']['incongr']['L'] = ImageStim(disp, image="Rincongr_l.jpg")

TARTIME = 1.7

###Feedback screen
fbstim = {}
fbstim[0] = TextStim(disp, text='Incorrect!', height=24, color='red')
fbstim[1] = TextStim(disp, text='Correct!', height=24, color='green')
fbstim[2] = TextStim(disp, text='Too slow!', height=24, color='red')
FEEDBACKTIME = 0.8

inststim.draw()
disp.flip()
waitKeys(maxWait=float('inf'), keyList=["return"], timeStamped=True)

stopwatch = core.Clock()

TRIALREPEATS = 1

alltrials1 = []
for tarside in TARSIDE:
    for congr in CONGR:
        for updown in UPDOWN:
            trial1 = {
                'tarside': tarside,
                'congr': congr,
                'updown': updown,
Exemplo n.º 21
0
class StimulusResource(Resource):
    should_stop = False

    def __enter__(self):
        win = self.window.instance
        proj = self.projection.instance
        try:
            eyepoint_x = proj.eyepoint[0]
        except:
            eyepoint_x = 0.5
        self.textstim = TextStim(win, text='')

        size_overriden = self.component.snp_viewport_override
        view_size = size_overriden if any(size_overriden) else win.size
        win_x, win_y = win.size
        view_x, view_y = view_size
        afr = 30  # int(win.getActualFrameRate() * 0.5)
        logging.msg('Fixed frame rate: ' + str(afr))
        self.flip_text('Generating stimulus...it may take a few minutes.')
        try:
            logging.msg('init movie...')
            print 'init movie...'
            width, height = win.monitor.getSizePix()
            mgen = SweepingNoiseGenerator(
                max_spat_freq=self.component.snp_max_spat_freq,
                max_temp_freq=self.component.snp_max_temp_freq,
                contrast=self.component.snp_contrast,
                rotation=self.component.snp_rotation,
                bandfilter=self.component.snp_filter,
                duration=self.component.snp_duration,
                bandwidth=self.component.snp_bandwidth,
                viewwidth=self.component.snp_view_width,
                imsize=self.component.snp_img_size,
                binary_threshold=self.component.snp_cont_thresh,
                framerate=afr,
                contr_period=self.component.snp_contr_period,
                screenWidthPix=win_x,
                screenHeightPix=win_y,
                viewport_x=view_x,
                viewport_y=view_y,
                screenWidthCm=self.window.monitor.component.width,
                screenHeightCm=self.window.monitor.component.height,
                screenDistanceCm=self.window.monitor.component.dist,
                eyepoint_x=eyepoint_x)
        except Exception as e:
            print 'got exception', type(e)
            print e
        else:
            print 'generating...'
            mgen.generate()
            print 'rotating...'
            mgen.rotate()
            print 'viewmasking...'
            mgen.viewmask()
            # print 'croping...'
            # mgen.crop()
            print 'done!'
            self.movie = mgen.moviedata
            print 'shape is', self.movie.shape

            logging.msg('masking window...')
            print 'masking window...'
            # Setting viewport width
            # screenWidthCm = self.window.monitor.component.width
            # screenDistanceCm = self.window.monitor.component.dist

            self.flip_text('Generating stimulus...done!')

        logging.msg('creating image stim...')
        print 'creating image stim...'
        # imagebuffer to play each frame
        self.instance = ImageStim(
            win=win,
            # size = [1440, 900], # prevent stretch
            # size = [900, 900], # for mbpr with 10cm
            size=view_size,
            units='pix',
            interpolate=True)
        logging.msg('ImageStim size: ' + str(self.instance.size))
        try:
            logging.msg('getting ISI...')
            self.interval = self.window.get_isi()
        except Exception as e:
            raise ServiceRuntimeException(
                'Could not acquire window object. Please try again')
        return self

    @memoized_property
    def trials(self):
        ts = [
            Trial(self, cond, self.component.snp_duration, self.interval)
            for cond in [self.movie]
        ]
        return TrialHandler(ts, nReps=1, method='random')

    @property
    def synced(self):
        self.clock.synchronize(self)
        return iter(self)

    def __iter__(self):
        for trial in self.trials:
            index = self.trials.thisN
            logging.msg('Entering trial #%s...' % index)
            # self.update_trial(trial)
            # self.trials.addData('on_time', self.clock.getTime())
            yield trial.start()
            # self.trials.addData('off_time', self.clock.getTime())
            self.flip_blank()

    def update_trial(self, trial):
        pass

    def update_phase(self, trial):
        pass

    def flip_text(self, text):
        self.textstim.setText(text)
        self.textstim.draw()
        self.window.flip()

    def flip_blank(self):
        self.instance.opacity = 0.0
        self.instance.draw()
        self.window.flip()

    def __exit__(self, type, value, tb):
        self.movie = None
        return super(StimulusResource, self).__exit__(type, value, tb)
Exemplo n.º 22
0
class MDTT(object):
    def __init__(self, logfile, imgDir, subjectNum, screenType, numStim,
                 numBlocks, trialDuration, ISI, selfPaced, runPractice,
                 inputButtons, pauseButton):

        self.logfile = logfile
        self.imgDir = imgDir
        self.subjectNum = subjectNum
        self.numStim = numStim
        self.numBlocks = numBlocks
        self.trialDuration = trialDuration
        self.selfPaced = selfPaced
        self.ISI = ISI
        self.numCats = 4
        self.trialsPer = int((self.numStim / self.numCats) / 2)
        self.runPractice = runPractice
        self.leftButton = inputButtons[0]
        self.rightButton = inputButtons[1]
        self.pauseButton = pauseButton

        #Set up window, center, left and right image sizes + positions

        if (screenType == 'Windowed'):
            screenSelect = False
        elif (screenType == 'Fullscreen'):
            screenSelect = True

        self.window = Window(fullscr=screenSelect,
                             units='pix',
                             color='White',
                             allowGUI=False)
        self.imageWidth = self.window.size[1] / 5.5
        self.centerImage = ImageStim(self.window)
        self.centerImage.setSize((self.imageWidth, self.imageWidth))
        self.leftImage = ImageStim(self.window)
        self.leftImage.setPos((-1.5 * self.imageWidth, 0))
        self.leftImage.setSize((self.imageWidth, self.imageWidth))
        self.rightImage = ImageStim(self.window)
        self.rightImage.setPos((1.5 * self.imageWidth, 0))
        self.rightImage.setSize((self.imageWidth, self.imageWidth))
        self.clock = Clock()

        #Init score list for 4 categories: [correct,incorrect,response]
        self.scoreList = []
        for i in range(0, 4):
            self.scoreList.append([0, 0, 0])

    def SplitRange(self, rangeMin, rangeMax, start=0):
        """Creates a pair of indexes separated by a value. The value itself
        can be between a min-max range. Neither index can be an index that is
        in a list of already used indexes.

        rangeMin: minimum amount that indexes can be separated by
        rangeMax: maximum amount that indexes can be separated by
        start: start index of used list 
        return: a pair of indexes (index1,index2)
                (-1,-1) if range split failed
        """

        #Search through list of used indexes to ensure no duplicates
        #Ignore start/end of list, as it's already used by primacy/recency
        for i in range(0, self.numStim):
            if (i in self.usedList):
                continue
            added = random.randint(rangeMin, rangeMax)
            startPt = added
            searchedRange = False
            #Loop through the min to max range of added values
            while not searchedRange:
                if ((i + added < self.numStim)
                        and (i + added not in self.usedList)):
                    self.usedList.append(i)
                    self.usedList.append(i + added)
                    return (i, i + added)
                if (added > rangeMin):
                    added -= 1
                else:
                    added = rangeMax
                if (added == startPt):
                    searchedRange = True
        return (-1, -1)

    def CreatePairsSpaced(self):
        """Creates a list, each element containing two indexes as well as a
        trial type. The trial type is based upon the spacing of the indexes as
        follows:

        adjacent (1): numbers next to eachother e.g. (3,4) or (8,9)
        eightish (2): numbers separated by between 7-9 e.g. (5,12) or (14,23)
        sixteenish (3): numbers separated by between 15-17 e.g. (3,18) or (8,25)
        primacy/recency: (4): start and end of list numbers e.g. (1,30) or (0,31)

        Occassionally, the list will fail to successfully split into index pairs.
        (SplitRange() returns (-1,-1) when this happens). The function will retry 
        the index splitting until all indexes are used

        return: list containing elements each with: (index1,index2,trialType)
        """

        startList = range(0, self.trialsPer)
        endList = range(self.numStim - self.trialsPer, self.numStim)
        trialOrder = range(0, (self.trialsPer * 3))  #3 categories besides P/R
        random.shuffle(startList)
        random.shuffle(endList)

        #Attempt to split 0-31 range into 4 index categories
        #Split fails if any one of the index pairs is (-1,-1) at end
        def AttemptSplit():

            # 3 categories besides P/R
            trialOrder = range(0, (self.trialsPer * 3))
            random.shuffle(trialOrder)
            self.usedList = []
            attemptList = []
            finalList = []

            #Add edge index pairs (primacy/recency)
            for i in range(0, self.trialsPer):
                finalList.append((startList[i], endList[i], 4))
                self.usedList.append(startList[i])
                self.usedList.append(endList[i])

            #Add spaced (separated) pairs of indexes to list
            for trial in trialOrder:
                if (trial % 3 == 0):  #Adjacent
                    (idxOne, idxTwo) = self.SplitRange(1, 1)
                    attemptList.append((idxOne, idxTwo, 1))
                elif (trial % 3 == 1):  #Eightish
                    (idxOne, idxTwo) = self.SplitRange(7, 9)
                    attemptList.append((idxOne, idxTwo, 2))
                elif (trial % 3 == 2):  #Sixteenish
                    (idxOne, idxTwo) = self.SplitRange(15, 17)
                    attemptList.append((idxOne, idxTwo, 3))

            #Ensures PR trials (type 4) occur first. Randomize successive trials
            random.shuffle(attemptList)
            finalList.extend(attemptList)
            return finalList

        #Try AttemptSplit() until index split is successful
        splitSuccess = False
        while (not splitSuccess):
            splitList = AttemptSplit()
            foundError = False
            for pair in splitList:
                if ((pair[0] == -1) or (pair[1] == -1)):
                    foundError = True
            if (foundError == True):
                continue
            else:
                splitSuccess = True

        return splitList

    def RunTrialSingle(self, img):
        """Displays a single image at the center of the screen for a period of
        time, and captures keypresses and their respective reaction times.

        img: the image to Displays
        return: a list of keypresses and respective reaction times
        """
        self.centerImage.setImage(self.imgDir + "/%s" % (img))
        self.centerImage.draw(self.window)
        clearEvents()
        self.window.flip()
        self.clock.reset()
        keyPresses = []
        if (self.selfPaced == False):
            wait(self.trialDuration, self.trialDuration)
            keyPresses = getKeys(keyList=[
                self.leftButton, self.rightButton, self.pauseButton, "escape"
            ],
                                 timeStamped=self.clock)
        elif (self.selfPaced == True):
            keyPresses = waitKeys(keyList=[
                self.leftButton, self.rightButton, self.pauseButton, "escape"
            ],
                                  timeStamped=self.clock)
        self.window.flip()
        wait(self.ISI)
        return keyPresses

    def RunTrialDual(self, leftImg, rightImg):
        """Displays two images on the screen for a period of time, and captures
        keypresses and their respective reaction times.

        leftimg: the image to display on the left
        rightimg: the image to display on the right
        return: a list of keypresses and respective reaction times
        """
        self.leftImage.setImage(self.imgDir + "/%s" % (leftImg))
        self.rightImage.setImage(self.imgDir + "/%s" % (rightImg))
        self.leftImage.draw(self.window)
        self.rightImage.draw(self.window)
        clearEvents()
        self.window.flip()
        self.clock.reset()
        if (self.selfPaced == False):
            wait(self.trialDuration, self.trialDuration)
            keyPresses = getKeys(keyList=[
                self.leftButton, self.rightButton, self.pauseButton, "escape"
            ],
                                 timeStamped=self.clock)
        elif (self.selfPaced == True):
            keyPresses = waitKeys(keyList=[
                self.leftButton, self.rightButton, self.pauseButton, "escape"
            ],
                                  timeStamped=self.clock)
        self.window.flip()
        wait(self.ISI)
        return keyPresses

    def RunStudy(self, imageBlock, session):
        """Runs the study, i.e. the first half of each experimental block.
        Writes all relevant information about the study to a logfile.

        imageBlock: List of images to display during the study
        session: the number of the session (block number) that is running
        """
        studyPrompt = (
            "Test Session {}/{}: Are the following objects indoor or outdoor?\n\n('{}' to continue)"
            .format(session, 10, self.pauseButton))
        studyText = TextStim(self.window, studyPrompt, color='Black')
        studyText.draw(self.window)
        self.window.flip()
        continueKey = waitKeys(keyList=[self.pauseButton, 'escape'])

        if (continueKey[0] == 'escape'):
            self.logfile.write("\n\n\nStudy Not Run Early\n\n\n")
            return

        self.logfile.write("\nBegin Study %d\n" % (session))
        self.logfile.write("{h1:<6}{h2:<23}{h3:<10}{h4}\n".format(
            h1="Trial", h2="Image", h3="Response", h4="RT"))

        #Run trial for each image in the image block
        for i in range(0, len(imageBlock)):
            keyPresses = self.RunTrialSingle(imageBlock[i])
            if (keyPresses == []):
                respKey = ''
                respRT = 0
            else:
                respKey = keyPresses[0][0]
                respRT = keyPresses[0][1]
            if (respKey == "escape"):
                self.logfile.write("\n\n\nStudy block terminated early\n\n\n")
                break
            elif (respKey == self.pauseButton):
                self.Pause()

            self.logfile.write("{:^5}{:<23}{:^11}{:<1.3f}\n".format(
                i + 1, imageBlock[i], respKey, respRT))

        return

    def RunTest(self, imageBlock, pairList, session):
        """Runs the test, i.e. the second half of each experimental block.
        Wites all relevant information about the test to a logfile

        imageBlock: List of images to display during the test
        pairList: List of paired image indexes w/ trial type
        session: the number of the session (block number) that is running
        """
        testPrompt = (
            "In this phase, the same series of objects will be shown\n\nWhich came first: Left or Right?\n\n('{}' to continue)"
            .format(self.pauseButton))
        testText = TextStim(self.window, testPrompt, color='Black')
        testText.draw(self.window)
        self.window.flip()
        continueKey = waitKeys(keyList=[self.pauseButton, 'escape'])

        if (continueKey[0] == 'escape'):
            self.logfile.write("\n\n\nTest Not Run\n\n\n")
            return 0

        self.logfile.write("\nBegin Test %d\n" % (session))
        lghead = "{a:<7}{b:<7}{c:<23}{d:<23}{e:<7}{f:<7}{g:<10}{h:<7}{i}\n".format(
            a="Trial",
            b="TType",
            c="LeftImage",
            d="RightImage",
            e="LNum",
            f="RNum",
            g="CorResp",
            h="Resp",
            i="RT")
        self.logfile.write(lghead)

        #Randomize if pair is shown: (bef > aft) or (aft > bef) order
        sideOrder = range(0, len(pairList))
        random.shuffle(sideOrder)
        correct = ''
        keyPresses = []

        #Run dual image trial for each pair in the pairlist
        for i in range(0, len(pairList)):
            trialNum = i + 1
            trialType = pairList[i][2]
            firstIdx = pairList[i][0]
            secondIdx = pairList[i][1]
            firstImg = imageBlock[pairList[i][0]]
            secondImg = imageBlock[pairList[i][1]]

            #Preserve the order images were shown in
            if (sideOrder[i] % 2 == 0):
                correct = self.leftButton
                leftIdx = firstIdx
                rightIdx = secondIdx
                leftImg = firstImg
                rightImg = secondImg
                keyPresses = self.RunTrialDual(leftImg, rightImg)
            #Reverse order images were shown
            elif (sideOrder[i] % 2 == 1):
                correct = self.rightButton
                leftIdx = secondIdx
                rightIdx = firstIdx
                leftImg = secondImg
                rightImg = firstImg
                keyPresses = self.RunTrialDual(leftImg, rightImg)

            #Get first response, or set to none if no response
            if (keyPresses == []):
                respKey = ''
                respRT = 0
            else:
                respKey = keyPresses[0][0]
                respRT = keyPresses[0][1]
            #Break out of image block with escape, break out of program with f5
            if (respKey == 'escape'):
                self.logfile.write("\n\nTest block terminated early\n\n")
                break
            elif (respKey == self.pauseButton):
                self.Pause()

            #Keep track of score
            if (respKey):
                self.scoreList[pairList[i][2] - 1][2] += 1
                if (respKey == correct):
                    self.scoreList[pairList[i][2] - 1][0] += 1
                else:
                    self.scoreList[pairList[i][2] - 1][1] += 1

            #Write info to logfile
            lgspace = "{:^5}{:^9}{:<23}{:<23}{:<7}{:<10}{:<8}{:<6}{:<1.3f}\n"
            lgform = (lgspace.format(trialNum, trialType, leftImg, rightImg,
                                     leftIdx, rightIdx, correct, respKey,
                                     respRT))
            self.logfile.write(lgform)

        return 1

    def Pause(self):
        """Pauses the task, and displays a message waiting for a spacebar
        input from the user before continuing to proceed.
        """
        pauseMsg = "Experiment Paused\n\nPress '{}' to continue".format(
            self.pauseButton)
        pauseText = TextStim(self.window,
                             text=pauseMsg,
                             color='Black',
                             height=40)
        pauseText.draw(self.window)
        self.window.flip()
        waitKeys(keyList=[self.pauseButton])
        clearEvents()

    def SegmentPracticeImages(self, images):
        '''
        Return the indexes for the test, it will index the image list from study:
            [[index_left_image, index_right_image, trialType]]
        '''
        # Since we know that the images are already randomized, we can just iterate over them
        # In order for the code to work, we want 4 practice images per practice block
        if len(images) != 4:
            print "Assertion error: length of practice images is not equal to 4"
            self.window.close()
            sys.exit()

        # Trial type of 4 means long distance
        large_dist = (0, 3, 4) if random.random() > .5 else (3, 0, 4)
        mid_dist_1 = (0, 2, 2) if random.random() > .5 else (2, 0, 2)
        mid_dist_2 = (1, 3, 2) if random.random() > .5 else (3, 1, 2)
        adjacent = (0, 1, 1) if random.random() > .5 else (1, 0, 1)
        adjacent_2 = (1, 2, 1) if random.random() > .5 else (2, 1, 1)
        adjacent = adjacent if random.random() > .5 else adjacent_2

        all = [large_dist, mid_dist_1, mid_dist_2, adjacent]
        random.shuffle(all)

        return all

    def ShowPromptAndWaitForSpace(self, prompt, keylist=['space', 'escape']):
        '''
        Show the prompt on the screen and wait for space, or the keylist specified
        returns the key pressed
        '''
        keylist = [self.pauseButton, 'escape']
        text = TextStim(self.window, prompt, color='Black')
        text.draw(self.window)
        self.window.flip()
        continueKey = waitKeys(keyList=keylist)
        if len(continueKey) != 0 and continueKey[0] == 'escape':
            self.logfile.write("Terminated early.")
            self.logfile.close()
            sys.exit()
        return continueKey

    def RunSinglePractice(self, practiceBlock, imgs):
        '''
        Read in the images we want, and run the practice block for this subject
        Run encoding and test, and write to the logs 
        
        Return:
           float: ratio correct
        '''
        random.shuffle(imgs)

        ### Encoding
        # imgs = [[img, trialType, Study(x,y), Test(x,y)]]
        testIdxs = self.SegmentPracticeImages(imgs)

        self.ShowPromptAndWaitForSpace(
            " Indoor or Outdoor?\n\n('{}' to continue)".format(
                self.pauseButton))

        self.logfile.write("\nBegin Practice Study {}\n".format(practiceBlock))
        self.logfile.write("{h1:<6}{h2:<23}{h3:<10}{h4}\n".format(
            h1="Trial", h2="Image", h3="Response", h4="RT"))

        # Run the trial for each encoding trial
        for i in range(0, len(imgs)):
            keyPresses = self.RunTrialSingle(imgs[i])
            if (keyPresses == []):
                respKey = ''
                respRT = 0
            else:
                respKey = keyPresses[0][0]
                respRT = keyPresses[0][1]
            if (respKey == "escape"):
                self.logfile.write("\n\n\nStudy block terminated early\n\n\n")
                break
            elif (respKey == self.pauseButton):
                self.Pause()

            self.logfile.write("{:^5}{:<23}{:^11}{:<1.3f}\n".format(
                i + 1, imgs[i], respKey, respRT))

        ### Test
        self.ShowPromptAndWaitForSpace(
            " Which came first? Left or right? ('{}' to continue)".format(
                self.pauseButton))

        self.logfile.write("\nBegin Practice Test {}\n".format(practiceBlock))
        self.logfile.write(
            "{a:<7}{b:<7}{c:<23}{d:<23}{e:<7}{f:<7}{g:<10}{h:<7}{i}\n".format(
                a="Trial",
                b="TType",
                c="LeftImage",
                d="RightImage",
                e="LNum",
                f="RNum",
                g="CorResp",
                h="Resp",
                i="RT"))

        # Keep track of the total number they got correct
        totalCorrect = 0
        for trialNum, idxes in enumerate(testIdxs):
            leftImgIdx, rightImgIdx, trialType = idxes

            leftImg = imgs[leftImgIdx]
            rightImg = imgs[rightImgIdx]

            keyPresses = self.RunTrialDual(leftImg, rightImg)
            correct = self.leftButton if leftImgIdx < rightImgIdx else self.rightButton

            #Get first response, or set to none if no response
            if (keyPresses == []):
                respKey = ''
                respRT = 0
            else:
                respKey = keyPresses[0][0]
                respRT = keyPresses[0][1]
            #Break out of image block with escape, break out of program with f5
            if (respKey == 'escape'):
                self.logfile.write("\n\nPractice block terminated early\n\n")
                self.logfile.close()
                sys.exit()

            #Write info to logfile
            lgspace = "{:^5}{:^9}{:<23}{:<23}{:<7}{:<10}{:<8}{:<6}{:<1.3f}\n"
            lgform = (lgspace.format(trialNum + 1, trialType, leftImg,
                                     rightImg, leftImgIdx, rightImgIdx,
                                     correct, respKey, respRT))
            self.logfile.write(lgform)

            if respKey == correct:
                totalCorrect += 1

        # Return the percentage correct
        return totalCorrect / len(imgs)

    def RunPractice(self):
        '''
        Runs three rounds of practice trials. 
        If the participant gets a certain amount correct, they move on to the real test.
        '''

        dirFiles = os.listdir(self.imgDir)
        practiceImages = [img for img in dirFiles if "PR_" in img]
        if len(practiceImages) == 0:
            print "No practice images found"
            self.window.close()
            sys.exit()

        random.shuffle(practiceImages)

        # Split the practice images into three sets
        practiceImages = np.array_split(practiceImages, 3)

        # Run each practice session
        for i in range(3):
            practicePrompt = "Let's practice\n\n('{}' to continue)".format(
                self.pauseButton)
            self.ShowPromptAndWaitForSpace(practicePrompt)

            results = self.RunSinglePractice(
                i + 1, [img for img in practiceImages[i]])

            # If they get a certain percentage correct, then stop the practice
            self.ShowPromptAndWaitForSpace(
                "You got {}% correct! ('{}' to continue)".format(
                    int(results * 100), self.pauseButton))
            if results > .6:
                return

    def RunExp(self):
        """Runs through an instance of the MDT-T experiment, which includes
        arranging the images into lists/sublists, running through a given
        number of study/test blocks, and writing the scores to a logfile. 
        """

        #Print task ending message to the screen; wait for user to press escape
        def EndExp():
            exitPrompt = ("This concludes the session. Thank you for "
                          "participating!\n\nPress Escape to quit")
            exitText = TextStim(self.window, exitPrompt, color='Black')
            exitText.draw(self.window)
            self.window.flip()
            waitKeys(keyList=['escape'])
            self.window.close()

        # Run practice
        if self.runPractice:
            self.RunPractice()

        #Put image files from folder into list
        imageList = []
        for img in os.listdir(self.imgDir):
            if (
                    img[-4:] == ".jpg" and "PR_" not in img
            ):  # Make sure that PR (practice image) is not included for study/tests
                imageList.append(img)
        random.shuffle(imageList)

        #Divide imagelist into <numBlocks> # of lists, put into one list
        #Each sublist contains <numStim> # of stimuli
        imageBlockList = []
        for i in range(0, self.numBlocks):
            block = []
            for j in range(i * self.numStim,
                           self.numStim + (i * self.numStim)):
                block.append(imageList[j])
            imageBlockList.append(block)

        #Run through each study/test block
        blockOrder = range(0, self.numBlocks)
        random.shuffle(blockOrder)
        writeScores = True
        for i in range(0, len(blockOrder)):
            pairList = self.CreatePairsSpaced()
            self.RunStudy(imageBlockList[i], i + 1)
            testFinished = self.RunTest(imageBlockList[i], pairList, i + 1)
            if not testFinished:
                writeScores = False
                continue

        EndExp()
        #Return logfile and scorelist if all study/test blocks gone through
        if writeScores:
            return (self.logfile, self.scoreList)
        else:
            return (-1, -1)
Exemplo n.º 23
0
    def run(self):
        pressToContinue = TextStim(self.win,
                                   text="<press any key to continue>",
                                   pos=(0, -0.9),
                                   height=0.06,
                                   units="norm",
                                   alignHoriz="center")
        #fixation = TextStim(win, text="+", height=0.1, color="#FFFFFF")

        instruct_1_text = """You will see five squares on the screen, which correspond with 'Spacebar', 'J', 'K', 'L', and ';'."""
        instruct1 = self.makeTextStim(instruct_1_text, vertpos=0.3)

        # example_targets_blank = TargetArray(win, vertpos=-0.1, drawLabels=False)
        example_targets_labeled = TargetArray(win,
                                              vertpos=-0.1,
                                              drawLabels=True,
                                              color=COLORS['purple'])

        instruct_2_text = "When a square lights up, your job is to press that key as quickly as possible.\n\n"
        instruct_2_text += "If two squares light up, press them at the same time (or as close as you can)."
        instruct2 = self.makeTextStim(instruct_2_text, vertpos=0.3)

        instruct_3_text = "You should press 'SPACEBAR' with your thumb, 'J' with your index finger, 'K' with your middle finger, 'L' with your ring finger, and ';' with your pinky.\n\n"
        instruct_3_text += "Hold your thumb over space and one finger on each of the subsequent letters (See image below).\n\n"
        instruct_3_text += "If you need to adjust where the keyboard is for this to be comfortable, please do so now."
        instruct3 = self.makeTextStim(instruct_3_text, vertpos=0.4)
        handStim = ImageStim(self.win,
                             image='img/hand.png',
                             size=(0.6, 0.45),
                             pos=(0, -0.3))

        instruct_4_text = "You will have a limited amount of time to make your response. "
        instruct_4_text += "The squares will remain on the screen for about 1 second, followed by a blank screen for another brief period.\n\n"

        instruct_4_text += "To answer correctly, press the correct keys before the squares disappear. "
        instruct_4_text += "If you press the wrong keys, the trial will count as a mistake. "
        instruct_4_text += "If you take too long to answer, the trial will count as a mistake.\n\n"

        instruct_4_text += "This may be difficult at first, but will become easier with practice. "
        instruct_4_text += "In either case, the blank screen will advance to the next trial after a few seconds."
        instruct4 = self.makeTextStim(instruct_4_text, vertpos=0)

        instruct_5_text = "You will complete six sequences of trials. Each sequence will last around 6-7 minutes. "
        instruct_5_text += "You can take a short break after each sequence.\n\n"
        instruct_5_text += "There are three distinct types of sequences. You may or may not notice differences between them. \n\n"
        instruct_5_text += "Each type of sequence will show a different shape in the middle of the screen for a few seconds before the sequence starts. The squares will also show up as a different color for each."
        instruct5 = self.makeTextStim(instruct_5_text, vertpos=0)

        instruct_6_text = "Once you finish the experiment, your accuracy will be calculated as the percentage of trials without a mistake. "
        instruct_6_text += "If this is at least 90%, you will receive a payment bonus of $5."
        instruct6 = self.makeTextStim(instruct_6_text, vertpos=0)

        example_targets_labeled.redraw()
        instruct1.draw()
        pressToContinue.draw()
        win.flip()
        event.waitKeys()

        instruct2.draw()
        example_targets_labeled.update([0, 1, 0, 1, 0])
        example_targets_labeled.redraw()
        win.flip()
        event.waitKeys()

        instruct3.draw()
        handStim.draw()
        win.flip()
        event.waitKeys()

        instruct4.draw()
        win.flip()
        event.waitKeys()

        instruct5.draw()
        win.flip()
        event.waitKeys()

        instruct6.draw()
        win.flip()
        event.waitKeys()
Exemplo n.º 24
0
class Display:
    def __init__(self, pars):
        self.win = initializers.setup_window()
        self.pars = pars
        self.geom = initializers.setup_geometry(self.win, self.pars)
        self.rotation_clocks = [None] * self.geom['numtargs']
        self.type = ['default'] * self.geom['numtargs']

        self.setup_sounds()
        self.setup_images()
        self.setup_text()

    def setup_sounds(self):
        self.cashsnd = Sound('resources/cash.wav')
        self.firesnd = Sound('resources/bbhit.wav')
        self.buzzsnd = Sound('resources/buzz.wav')

    def setup_images(self):
        self.notargs = []
        self.gotargs = []
        self.deftargs = []
        self.bkimg = ImageStim(self.win,
                               image='resources/pond.jpg',
                               units='norm',
                               size=(2.0, 2.0))

        for targ in range(self.geom['numtargs']):
            self.notargs.append(
                ImageStim(self.win,
                          image='resources/rfrog2.jpg',
                          size=self.geom['target_size'],
                          pos=self.geom['target_centers'][targ]))
            self.gotargs.append(
                ImageStim(self.win,
                          image='resources/gfrog2.jpg',
                          size=self.geom['target_size'],
                          pos=self.geom['target_centers'][targ]))
            self.deftargs.append(
                ImageStim(self.win,
                          image='resources/lilypad.jpg',
                          size=self.geom['target_size'],
                          pos=self.geom['target_centers'][targ]))

        # set initial target stims to be the defaults
        self.targets = []
        for targ in self.deftargs:
            self.targets.append(targ)

    def setup_text(self):
        self.scoretxt = TextStim(self.win,
                                 text="Total Points: ",
                                 font='Helvetica',
                                 alignHoriz='left',
                                 alignVert='top',
                                 units='norm',
                                 pos=(-1, 1),
                                 height=0.2,
                                 color=[178, 34, 34],
                                 colorSpace='rgb255',
                                 wrapWidth=2)

        self.targtxt = []
        for targ in range(self.geom['numtargs']):
            self.targtxt.append(
                TextStim(self.win,
                         pos=self.geom['target_centers'][targ],
                         color='White',
                         units='height',
                         height=0.05,
                         text=''))

    def set_target_image(self, index, value='default'):
        if value == 'go':
            self.targets[index] = self.gotargs[index]
        elif value == 'no':
            self.targets[index] = self.notargs[index]
        elif value == 'default':
            self.targets[index] = self.deftargs[index]

    def set_target_text(self, index, value):
        self.targtxt[index].setText(value)

    def set_score(self, pts):
        self.scoretxt.setText('Total Points: ' + str(pts))

    def onset(self, index, value):
        self.rotation_clocks[index] = Clock()
        self.type[index] = value

    def offset(self, index):
        self.rotation_clocks[index] = Clock()
        self.type[index] = 'default'

    def update(self):
        # for each target with clock running (i.e., rotating) ...
        for idx, clk in enumerate(self.rotation_clocks):
            if clk:
                rot_time = clk.getTime()
                rot_dur = self.pars['rot_dur']

                if rot_time > rot_dur:
                    rotfrac = -1  # rotation completed
                else:
                    rotfrac = cos(pi * rot_time / self.pars['rot_dur'])

                # adjust target size to give illusion of rotation
                base_size = self.geom['target_size']
                self.targets[idx].size = (abs(rotfrac) * base_size[0],
                                          base_size[1])

                # set correct image on target based on rotation angle
                if rotfrac < 0:
                    self.set_target_image(idx, self.type[idx])

    def draw(self):
        self.update()
        self.bkimg.draw()
        self.scoretxt.draw()
        for stim in self.targets:
            stim.draw()
        for stim in self.targtxt:
            stim.draw()
        self.win.flip()

    def close(self):
        self.win.close()
Exemplo n.º 25
0
#log file
log = open ('logfileprisonersdilemma.txt', 'w')
log.write(' .... ') #insert headers of what should be logged

#response keys
resp = getKeys(keyList = ('q', 'space', 'left', 'right'))

strategy = [1,2,3,4,5]  #random assignment of opponents strategy
shuffle(strategy)

randostrategy = [1,2] #for strategy 3


condlist = 
n_trials =  #need to set that


#starting the game
background_image.draw()
win.flip()


#trial loop
for i in range(n_trials):
	
	#strategies

	#opponent always cooperates
	if strategy == 1:
		opponent.draw()
		cooptxt.draw()
		win.flip()