Beispiel #1
0
 def element_iteration(p):
   f = world[p.getX()][p.getY()]
   if f[TYPE] == EMPTY or f[MOVED] == 1:
     return
   fish = None
   if f[TYPE] == SHARK :
     if f[STARVED] >= 3:
       viz_die(p)
       for i in range(4):
         f[i] = 0
       return
     fish = getsurroundings(p,FISH)
   spawn = None
   if fish:
     spawn = randomchoice(fish)
   else:
     emptyspaces = getsurroundings(p, EMPTY)
     if emptyspaces:
       spawn = randomchoice(emptyspaces)
   if spawn:        
     move(p,spawn)
   else:
       f[AGE] += 1
       if f[TYPE] == SHARK:
         f[STARVED] += 1
Beispiel #2
0
 def barterAi(self):
     listWithoutSelfId = list(range(0,len(villages)))
     listWithoutSelfId.remove(self.id)
     villageId = randomchoice(listWithoutSelfId)
     surplus = sorted(self.productAmount,reverse=True)[randomchoice((0,0,0,0,1,1,2))] #extra items that need to be transfered
     indexNo = self.productAmount.index(surplus)
     amount = round(self.productAmount[indexNo] * randomchoice((0.1, 0.1, 0.1, 0.15, 0.2)))
     self.barter(indexNo, villageId, amount)
Beispiel #3
0
	async def hadoken(self, ctx, *, user : discord.Member=None):
		"""Do the Hadoken on a user"""
		if ctx.invoked_subcommand is None:
			if user.id == self.bot.user.id:
				user = ctx.message.author
				await self.bot.say("- uses " + randomchoice(self.fists) + " on " + user.name + " - \n\n Next Time " + user.name + " Dont Hadoken Me! :crying_cat_face:" )
				return
			await self.bot.say("- uses " + randomchoice(self.fists) + " on " + user.name + " -")
Beispiel #4
0
 async def hadoken(self, ctx, *, user: discord.Member = None):
     """Do the Hadoken on a user"""
     if ctx.invoked_subcommand is None:
         if user.id == self.bot.user.id:
             user = ctx.message.author
             await self.bot.say("- uses " + randomchoice(self.fists) +
                                " on " + user.name + " - \n\n Next Time " +
                                user.name +
                                " Dont Hadoken Me! :crying_cat_face:")
             return
         await self.bot.say("- uses " + randomchoice(self.fists) + " on " +
                            user.name + " -")
Beispiel #5
0
	async def give(self, ctx, *, user : discord.Member=None):
		if ctx.invoked_subcommand is None:
			if user.id == self.bot.user.id:
				user = ctx.message.author
				await self.bot.say("- gives " + user.name +" a shovel and says 'Go clear that mountain for @Jan#7096'" )
				return
			await self.bot.say("- gives " + randomchoice(self.items) + " to " + user.name + "! Have fun :D -")
Beispiel #6
0
    def step(self):
        super().step()
        led = randomchoice(self.totem.rgb)
        led.r = self._random_x()
        led.g = self._random_x()
        led.b = self._random_x()

        led = randomchoice(self.totem.rgbw)
        led.r = self._random_x()
        led.g = self._random_x()
        led.b = self._random_x()
        led.w = self._random_x()

        self.totem.pushPieces()

        time.sleep(0.01)
Beispiel #7
0
 def step(self):
     super().step()
     for fade in self._rfades:
         fade.targetvalue = randint(0, 200)
     for gfade in self._gfades:
         gfade.targetvalue = 0
     randomchoice(self._gfades).targetvalue = randint(100, 200)
     totem.pushPieces()
     time.sleep(0.7)
def move(world, alex):
    if NAME not in world['entities']:
        position = (alex.config['player_start_x'] + 80 * (INDEX + 1),
                    alex.config['player_start_y'])
        send_movement(position, position, world['tick'], alex)
        return

    if NAME not in world['movements']:
        delta = randomchoice(DELTAS)
    else:
        movement = world['movements'][NAME]
        delta = (movement['to'][0] - movement['from'][0],
                 movement['to'][1] - movement['from'][1])
        if delta[0] == 0 and delta[1] == 0:
            delta = randomchoice(DELTAS)

    position = world['entities'][NAME]['position']
    new_position = (position[0] + delta[0], position[1] + delta[1])
    send_movement(position, new_position, world['tick'], alex)
def move(world, alex):
    if NAME not in world['entities']:
        position = (alex.config['player_start_x'] + 80 * (INDEX + 1),
                    alex.config['player_start_y'])
        send_movement(position, position, world['tick'], alex)
        return

    if NAME not in world['movements']:
        delta = randomchoice(DELTAS)
    else:
        movement = world['movements'][NAME]
        delta = (movement['to'][0] - movement['from'][0],
                 movement['to'][1] - movement['from'][1])
        if delta[0] == 0 and delta[1] == 0:
            delta = randomchoice(DELTAS)

    position = world['entities'][NAME]['position']
    new_position = (position[0] + delta[0], position[1] + delta[1])
    send_movement(position, new_position, world['tick'], alex)
Beispiel #10
0
 async def give(self, ctx, *, user: discord.Member = None):
     if ctx.invoked_subcommand is None:
         if user.id == self.bot.user.id:
             user = ctx.message.author
             await self.bot.say(
                 "- gives " + user.name +
                 " a shovel and says 'Go clear that mountain for @Jan#7096'"
             )
             return
         await self.bot.say("- gives " + randomchoice(self.items) + " to " +
                            user.name + "! Have fun :D -")
Beispiel #11
0
 def element_iteration(j,i):
   f = world[j][i]
   if f[TYPE] == EMPTY or f[MOVED] == 1:
     return
   if f[TYPE] == FISH and not getsurroundings(j,i, EMPTY):
     return
   p = Point(j,i)
   fish = None
   if f[TYPE] == SHARK :
     if f[STARVED] >= 3:
       #print "SHARK DIE ->",
       viz_die(p)
       for i in range(5):
         f[i] = 0
       return
     # Move to fish and eat it
     fish = getsurroundings(j,i,FISH)
     #print "BEFORE MOVE",
     #print _element(f)," at:",j,i,
     #win.update()
     #t = raw_input()
   spawn = None
   if fish:
     spawn = randomchoice(fish)
     #print " fishes nearby ",fish, "choosing ",spawn
   else:
     #Move to empty space
     emptyspaces = getsurroundings(j,i, EMPTY)
     if emptyspaces:
       spawn = randomchoice(emptyspaces)
   if spawn:        
     #if f[TYPE] == SHARK: print "from",f,
     to = world[spawn.getX()][spawn.getY()]
     move(_from=f,f=p,_to=to,t=spawn)
     f = to
     #if to[TYPE] == SHARK: print " to ",to
       
   else:
       f[AGE] += 1
       if f[TYPE] == SHARK:
         f[STARVED] += 1
Beispiel #12
0
        async def rum(ctx):
            """
            But why is the rum gone?!
            """

            phrase = randomchoice(BotLocalizer.RUM)
            try:
                output = phrase % ctx.message.author.id
            except TypeError:
                output = phrase

            # Response
            await ctx.send(output)
def available_results_get(ModelName=None, size=None):
    """Obtain a list of run results

    Return a list of all available run results. # noqa: E501

    :rtype: List[RunResults]
    """
    model = ModelName

    if model != None:
        if model.lower() not in available_models:
            return 'Model Not Found', 404, {'x-error': 'not found'}

    run_ids = []

    # no model or size
    if model == None and size == None:
        for m in available_models:
            if m in ['fsc', 'dssat', 'chirps', 'chirps-gefs']:
                m = m.upper()
            runs = list_runs_model_name_get(m)
            run_ids.extend(runs)

    # model provided but no size
    elif model != None and size == None:
        runs = list_runs_model_name_get(model)
        run_ids.extend(runs)

    # size provided but no model
    elif model == None and size != None:
        n = 1
        while n <= size:
            m = randomchoice(available_models)
            if m in ['fsc', 'dssat', 'chirps', 'chirps-gefs']:
                m = m.upper()
            rand_run = r.srandmember(m)
            if rand_run != None:
                run_ids.append(rand_run.decode('utf-8'))
                n += 1

    # model provided and size provided
    elif model != None and size != None:
        runs = [
            run.decode('utf-8') for run in list(r.srandmember(model, size))
        ]
        run_ids.extend(runs)

    results = []
    for id_ in run_ids:
        results.append(run_results_run_idget(id_))
    return results
Beispiel #14
0
def home_page_user(request):
    username_logged_in = request.user.username
    if username_logged_in:
        return redirect('/user/' + username_logged_in)

    else:
        new_user_username = generate_username()[0]
        new_user_password = generate_username()[0]
        new_user = User.objects.create_user(
            new_user_username,
            '*****@*****.**',
            new_user_password
        )
        new_user.save()

        new_profile_list = Profile.objects.filter(user=new_user)
        new_profile = new_profile_list.last()

        new_difficulty = randomchoice(four_by_four_setting_list)
        new_profile.low_medium_or_high_dots_setting = new_difficulty
        regret_forwards_boolean = randomchoice([True, False])
        new_profile.regret_forwards = regret_forwards_boolean
        new_profile.save()

        user_authenticated = authenticate(
            request,
            username=new_user_username,
            password=new_user_password
            )

        
        if user_authenticated is not None:
            login(request, user_authenticated)
            username_logged_in = user_authenticated.username
            return redirect('/user/' + username_logged_in)

        else:
            pass
Beispiel #15
0
def comboCheck(itemObj1, itemObj2):
    global combinations, inventory_list
    for tup in combinations:
        if itemObj1 in tup and itemObj2 in tup:
            inventory_list.append(tup[2])
            if itemObj1 in inventory_list:
                inventory_list.remove(itemObj1)
            if itemObj2 in inventory_list:
                inventory_list.remove(itemObj2)
            print(tup[2].firstDesc)
            return
    randText = randomchoice(["That didn't work.", "It no work buddy",
                             "That was a stupid idea.", "HAHAHAHA, no."])
    print(randText)
Beispiel #16
0
def play():
    user = input("What's your choice? 'r' for rock, 'p' for paper, 's' for scissors\n")
    user = user.lower()

    computer = random.randomchoice(['r', 'p', 's'])

    if user == computer:
         return (0, user, computer)

    # r > s, s > p, p > r
    if is_win(user, computer):
        return (1, user, computer)

    return (-1, user, computer)
Beispiel #17
0
def get_random_string(length):
    """A function to obtain a random string of the given length
    
    Parameters:
    -----------
    length: int, a integer specifying the desired length of the random string

    Returns:
    --------
    res: string, a randomly generated string of ASCII letters of length "length"
    """

    # Random string with the combination of lower and upper case letters
    letters = string.ascii_letters
    res = ''.join(randomchoice(letters) for i in range(length))
    return res
Beispiel #18
0
def create_new_user(request):

    alphabet = ascii_letters + digits
    new_user_username = ''.join(
        secretschoice(alphabet) for i in range(8)
        )
    new_user_password = ''.join(
        secretschoice(alphabet) for i in range(14)
        )
    new_user = User.objects.create_user(
        new_user_username,
        '*****@*****.**',
        new_user_password
    )
    new_user.save()

    new_profile_list = Profile.objects.filter(user=new_user)
    new_profile = new_profile_list.last()

    # change the difficulty here
    #new_difficulty = randomchoice(four_by_four_setting_list)
    #new_difficulty = randomchoice(four_by_four_setting_list_two_options)
    new_difficulty = "very_easy"

    new_profile.low_medium_or_high_dots_setting = new_difficulty
    regret_forwards_boolean = randomchoice([True, False])
    new_profile.regret_forwards = regret_forwards_boolean
    new_profile.save()

    user_authenticated = authenticate(
        request,
        username=new_user_username,
        password=new_user_password
        )

    
    if user_authenticated is not None:
        login(request, user_authenticated)
        username_logged_in = user_authenticated.username
        return redirect('/user/' + username_logged_in)

    else:
        pass
Beispiel #19
0
 def viterbi(self,input): 
     input = asmatrix(input)
     T = input.shape[0]
     pointers = zeros((self.numclasses,T),dtype='int')
     delta = matrix(zeros((self.numclasses,T),dtype=float))
     delta[:,0] = self.singlenodescore(input[0,:],arange(self.numclasses))
     for t in range(1,T):
         for y in range(self.numclasses):
             vals = asmatrix(delta[:,t-1].flatten() + \
                   self.dualnodescore(input,(arange(self.numclasses),y))\
                                   + self.singlenodescore(input[t,:],y)).T
             delta[y,t] = max(vals)
             pointers[y,t] = argmax(vals.flatten())
     #backtrack:
     outputs = zeros(T,dtype='int')
     optlast = where(delta[:,-1]==max(delta[:,-1]))[0]
     outputs[-1] = randomchoice(optlast)   #break ties randomly
     for t in range(T-2,-1,-1):
         outputs[t] = pointers[outputs[t+1],t+1]
     return outputs
Beispiel #20
0
 def viterbi(self, input):
     input = asmatrix(input)
     T = input.shape[0]
     pointers = zeros((self.numclasses, T), dtype='int')
     delta = matrix(zeros((self.numclasses, T), dtype=float))
     delta[:, 0] = self.singlenodescore(input[0, :],
                                        arange(self.numclasses))
     for t in range(1, T):
         for y in range(self.numclasses):
             vals = asmatrix(delta[:,t-1].flatten() + \
                   self.dualnodescore(input,(arange(self.numclasses),y))\
                                   + self.singlenodescore(input[t,:],y)).T
             delta[y, t] = max(vals)
             pointers[y, t] = argmax(vals.flatten())
     #backtrack:
     outputs = zeros(T, dtype='int')
     optlast = where(delta[:, -1] == max(delta[:, -1]))[0]
     outputs[-1] = randomchoice(optlast)  #break ties randomly
     for t in range(T - 2, -1, -1):
         outputs[t] = pointers[outputs[t + 1], t + 1]
     return outputs
Beispiel #21
0
    def seedGenome(self, genes={}):
        '''Returns a genome as an (inherently) ordered list of genes of length given by static GENOME_LENGTH variable'''
        genome = [randomchoice(list(settings.GENES)) for x in range(settings.GENOME_LENGTH)]

        return genome
Beispiel #22
0
 def pickDisease(self):
     return random.randomchoice(Character.diseaseList)
Beispiel #23
0
    def rawdefault(prompt, fn, default):
        x = raw_input(prompt + '[' + default + '] $ ')
        if x == 'prompt':
            import pdb; pdb.set_trace()
        if len(x) > 0:
            try:
                return fn(x)
            except:
                print 'invalid input'
                return rawdefault(prompt, fn, default)
        return fn(default)

    grid = grids_n_lines.grid
    lines = grids_n_lines.lines
    random = density_n_linewidth.random
    randomfn = lambda x,y,**kw: randomchoice([grid,lines,random])(x,y,**kw)

    DPI = rawdefault("DPI", int, "600")
    w_cm = rawdefault("Poster width in CM", float, "91.0")
    width = w_cm / 2.54
    w_pixels = int(width*DPI)

    csvpath = rawdefault("Path to CSV", str, "grid.csv")
    data = [x for x in csv.reader(csvnorm(csvpath))]
    data = [numpy.array([float(c) for c in r]) for r in data]
    data = numpy.array(data)
    if data.min() < 0 or data.max() > 1:
        fail('values not normalized')

    rot90 = rawdefault("Rotate 90 degrees?", bool, "")
    if rot90:
Beispiel #24
0
	async def quote(self, ctx):
		"""Random Quote to be Drawn"""
		await self.bot.say("Quote: " + randomchoice(self.quotes) + " ")
Beispiel #25
0
 async def quote(self, ctx):
     """Random Quote to be Drawn"""
     await self.bot.say("Quote: " + randomchoice(self.quotes) + " ")
Beispiel #26
0
def door_result_page(request, username):
    if request.method == "POST":
        user_logged_in = request.user
        username_logged_in = user_logged_in.username
        choose_final_door(request)
        return redirect('/user/' + username_logged_in + '/final-door-result')
    # !----- Need to make choice specific to the user ----!

    # find the trials by this user
    trial_existing_objects = Trial.objects.filter(
        user=request.user
    )
    trial_existing = trial_existing_objects.last()
    choices_from_this_trial = Choice.objects.filter(
        trial=trial_existing
    )
    choice = choices_from_this_trial.last()
    if choice:
        chosen_number = choice.door_number
        possible_numbers = [1, 2, 3]
        possible_numbers.remove(chosen_number)
        trial = choice.trial
        result = Result.objects.get(trial=trial)
        result_number = result.door_number
        try:
            possible_numbers.remove(result_number)
        except ValueError:
            pass
        # We should be left with either one or two numbers left
        if len(possible_numbers) == 1:
            number_to_remove = possible_numbers[0]
        elif len(possible_numbers) == 2:
            # if there's a choice of 2 numbers to remove,
            # in this case they've already chosen the right number,
            # then remove at random one of the remaining 2 numbers.
            number_to_remove = randomchoice(possible_numbers)
        other_door_choice_list = [1, 2, 3]
        other_door_choice_list.remove(chosen_number)
        other_door_choice_list.remove(number_to_remove)
        number_to_change_to = other_door_choice_list[0]

        doors_to_display_list = [chosen_number,
                                 number_to_change_to
                                 ]
        if 1 in doors_to_display_list:
            door_one_bool = True
        else:
            door_one_bool = False
        if 2 in doors_to_display_list:
            door_two_bool = True
        else:
            door_two_bool = False
        if 3 in doors_to_display_list:
            door_three_bool = True
        else:
            door_three_bool = False

        return render(request, 'door_result.html', {
            'door_chosen_number': str(choice.door_number),
            'door_to_remove_number': str(number_to_remove),
            'door_to_change_to_number': str(number_to_change_to),
            'door_one_bool': door_one_bool,
            'door_two_bool': door_two_bool,
            'door_three_bool': door_three_bool,
        })
    else:
        return render(request, 'door_result.html',
                      )
Beispiel #27
0
        'Task': 'Scene',
        'cue_stim': copy.copy(polygon_donut_b)
    },
    'dcb': {
        'cue': 'dcb',
        'Color': 'blue',
        'Texture': 'Donut',
        'Shape': 'Circle',
        'Task': 'Scene',
        'cue_stim': copy.copy(circle_donut_b)
    }
}

#select a random first trial

random_first = randomchoice(list(Cue_types))

#### Now create a massive trial dictionary. In this dictionary will save all the attributes for each trial, by its order.
#### The "key" to this dict will be the trial number, in each key will be anohter nested dictionary saving all the
#### attributes of each trial, the cue type, color, shape, texture, the cue stimuli , and the picture stim.
Trial_dict = {}
for i in range(len(Trial_order)):
    if i == 0:  #set first trial, randomly select
        Trial_dict[i] = Cue_types[random_first]
    else:
        if Trial_order[i] == 'Stay':  # stay
            if Trial_dict[i - 1]['cue'] in ['fpr', 'fpb']:
                Trial_dict[i] = Cue_types[randomchoice(['fpr', 'fpb'])].copy(
                )  # having .copy() is extremenly important, otherwise it will be
            elif Trial_dict[i - 1]['cue'] in [
                    'fcr', 'fcb'
Beispiel #28
0
#circle_donut=[]

##### create a attribute dictionary saving all cue types
# note, copying the shapestim and visual.circle object using copy.copy() turns out to be critical, otherwise can't change colors on the fly
Cue_types = {'fpr': {'cue':'fpr', 'Color': 'red', 'Texture': 'Filled', 'Shape': 'Polygon', 'Task': 'Face', 'cue_stim': copy.copy(polygon_filled_r) },
             'fpb': {'cue':'fpb', 'Color': 'blue', 'Texture': 'Filled', 'Shape': 'Polygon', 'Task': 'Face', 'cue_stim': copy.copy(polygon_filled_b) },
             'fcr': {'cue':'fcr', 'Color': 'red', 'Texture': 'Filled', 'Shape': 'Circle', 'Task': 'Scene', 'cue_stim': copy.copy(circle_filled_r) },
             'fcb': {'cue':'fcb', 'Color': 'blue', 'Texture': 'Filled', 'Shape': 'Circle', 'Task': 'Scene', 'cue_stim': copy.copy(circle_filled_b) },
             'dpr': {'cue':'dpr', 'Color': 'red', 'Texture': 'Donut', 'Shape': 'Polygon', 'Task': 'Face', 'cue_stim': copy.copy(polygon_donut_r) },
             'dcr': {'cue':'dcr', 'Color': 'red', 'Texture': 'Donut', 'Shape': 'Circle', 'Task': 'Face', 'cue_stim': copy.copy(circle_donut_r) },
             'dpb': {'cue':'dpb', 'Color': 'blue', 'Texture': 'Donut', 'Shape': 'Polygon', 'Task': 'Scene', 'cue_stim': copy.copy(polygon_donut_b) },
             'dcb': {'cue':'dcb', 'Color': 'blue', 'Texture': 'Donut', 'Shape': 'Circle', 'Task': 'Scene', 'cue_stim': copy.copy(circle_donut_b) }}

#select a random first trial

random_first = randomchoice(list(Cue_types))

#### Now create a massive trial dictionary. In this dictionary will save all the attributes for each trial, by its order.
#### The "key" to this dict will be the trial number, in each key will be anohter nested dictionary saving all the
#### attributes of each trial, the cue type, color, shape, texture, the cue stimuli , and the picture stim.
Trial_dict = {}
for i in range(len(Trial_order)):
    if i == 0 :   #set first trial, randomly select
        Trial_dict[i] = Cue_types[random_first]
    else:
        if Trial_order[i] == 'Stay':  # stay
            if Trial_dict[i-1]['cue'] in ['fpr', 'fpb']:
                Trial_dict[i] = Cue_types[randomchoice(['fpr', 'fpb'])].copy() # having .copy() is extremenly important, otherwise it will be
            elif Trial_dict[i-1]['cue'] in ['fcr', 'fcb']:# a link to original object and not "switch"
                Trial_dict[i] = Cue_types[randomchoice(['fcr', 'fcb'])].copy()
            elif Trial_dict[i-1]['cue'] in ['dpr', 'dcr']:
Beispiel #29
0
def random_start_position(alex):
    grid_width = alex.config['field_width'] / CELL_DIM
    grid_height = alex.config['field_height'] / CELL_DIM
    return (randomchoice(range(grid_width)) * CELL_DIM + DISPLACEMENT,
            randomchoice(range(grid_height)) * CELL_DIM + DISPLACEMENT)
Beispiel #30
0
        'cue': 'fcb',
        'Color': 'blue',
        'Texture': 'Filled',
        'Shape': 'Circle',
        'Task': 'Scene',
        'cue_stim': copy.copy(circle_filled_b)
    }
}
#'dpr': {'cue':'dpr', 'Color': 'red', 'Texture': 'Donut', 'Shape': 'Polygon', 'Task': 'Face', 'cue_stim': copy.copy(polygon_donut_r) },
#'dcr': {'cue':'dcr', 'Color': 'red', 'Texture': 'Donut', 'Shape': 'Circle', 'Task': 'Face', 'cue_stim': copy.copy(circle_donut_r) },
#'dpb': {'cue':'dpb', 'Color': 'blue', 'Texture': 'Donut', 'Shape': 'Polygon', 'Task': 'Scene', 'cue_stim': copy.copy(polygon_donut_b) },
#'dcb': {'cue':'dcb', 'Color': 'blue', 'Texture': 'Donut', 'Shape': 'Circle', 'Task': 'Scene', 'cue_stim': copy.copy(circle_donut_b) }}

#select a random first trial

random_first = randomchoice(list(Cue_types))

#### Now create a massive trial dictionary. In this dictionary will save all the attributes for each trial, by its order.
#### The "key" to this dict will be the trial number, in each key will be anohter nested dictionary saving all the
#### attributes of each trial, the cue type, color, shape, texture, the cue stimuli , and the picture stim.
Trial_dict = {}
for i in range(len(Trial_order)):

    if i == 0:  #set first trial, randomly select
        Trial_dict[i] = Cue_types[random_first]
    else:
        if Trial_order[i] == 'Stay':  # stay
            if Trial_dict[i - 1]['cue'] in ['fpr', 'fpb']:
                Trial_dict[i] = Cue_types[randomchoice(['fpr', 'fpb'])].copy(
                )  # having .copy() is extremenly important, otherwise it will be
            elif Trial_dict[i - 1]['cue'] in [
Beispiel #31
0
def random_start_position(alex):
    grid_width = alex.config['field_width'] / CELL_DIM
    grid_height = alex.config['field_height'] / CELL_DIM
    return (randomchoice(range(grid_width)) * CELL_DIM + DISPLACEMENT,
            randomchoice(range(grid_height)) * CELL_DIM + DISPLACEMENT)
def pracBlocks(n_trials=n_trials):

    #    while tutorial_video.status != visual.FINISHED:
    #        tutorial_video.draw()
    #        win.flip()
    #        if event.getKeys():
    #            breaks

    #tutorial_video.draw()
    #tutorial_video.play()
    #win.flip()
    #core.wait(5)

    Total_trials = n_trials
    Switch_probability = 0.5
    Extra_dimension_switch_probability = 0.7
    Intra_dimension_switch_probability = 0.3
    Cue_time = 2  #1
    Pic_time = 3
    ITIs = [1, 1.1, 1.2, 1.3, 1.4,
            1.5]  # need to jitter this for fMRI, no is just uniform random
    Initial_wait_time = 2
    Number_of_initial_stays = 3

    #### Set up the order of switch versus stay trials,
    # integer code for trial type
    Intra_dimension_switch = 11  #IDS, intra dimensional/tree switch
    #Extra_dimension_switch = 33  #EDS, shifting out of decision tree
    Stay_trial = 99

    #### setup number of trials for each trial type (EDS, IDS, stay)
    Total_switch_trials = round(Total_trials * Switch_probability)
    #Number_of_EDS = round(Total_switch_trials * Extra_dimension_switch_probability)
    Number_of_IDS = Total_switch_trials
    Number_of_stay = round(Total_trials * Switch_probability)

    #print(Number_of_EDS)
    print(Number_of_IDS)
    print(Number_of_stay)

    # ###setup switch and stay trials order, represented by integer code above
    Trial_order = np.concatenate((np.repeat(Stay_trial, Number_of_stay),
                                  np.repeat(Intra_dimension_switch,
                                            Number_of_IDS)))
    Trial_order_int = np.random.permutation(
        np.random.permutation(Trial_order))  #randomly permute the trial order
    Trial_order_int = np.concatenate(
        (np.repeat(Stay_trial, Number_of_initial_stays),
         Trial_order_int))  # always add 3 "Stay trials at the beginig"

    #### now change the integers to string ("switch", "IDS", "EDS") so it is more readable
    Trial_order = Trial_order_int.astype(
        'object'
    )  #convert integer representation of trial order into text for readability
    Trial_order[Trial_order == 99] = 'Stay'
    Trial_order[Trial_order == 11] = 'IDS'
    #Trial_order[Trial_order == 33] = 'EDS'

    # random sequence of face or scene picture presentation
    Pic_order = np.random.permutation(
        np.random.randint(1, 3, len(Trial_order)).astype('object'))
    Pic_order[Pic_order == 1] = 'Face'
    Pic_order[Pic_order == 2] = 'Scene'

    #Dictionaries and the corresponding file paths
    direc = os.getcwd(
    ) + '\localizer_stim/'  #_thisDir #'/Users/mpipoly/Desktop/Psychopy/localizer_stim/' #always setup path on the fly in case you switch computers
    ext = 'scenes\*.jpg'  #file delimiter
    faces_ext = 'faces\*.jpg'
    faces_list = glob.glob(direc + faces_ext)
    scenes_list = glob.glob(direc + ext)
    print(faces_list)
    print(scenes_list)
    Img_Scene = {}
    Img_Faces = {}
    Img_path = {}
    # randomly select pics from list, only load same number of pics as number of trials to save memory
    for i, f in enumerate(
            np.random.randint(low=0,
                              high=len(faces_list),
                              size=len(Trial_order))):

        if Pic_order[i] == 'Face':
            Img_Faces[i] = visual.ImageStim(win=win, image=faces_list[f])
            Img_path[i] = faces_list[f]
        if Pic_order[i] == 'Scene':
            Img_Scene[i] = visual.ImageStim(win=win, image=scenes_list[f])
            Img_path[i] = scenes_list[f]

    Cue_types = {
        'fpr': {
            'cue': 'fpr',
            'Color': 'red',
            'Texture': 'Filled',
            'Shape': 'Polygon',
            'Task': 'Face',
            'cue_stim': copy.copy(polygon_filled_r)
        },
        'fpb': {
            'cue': 'fpb',
            'Color': 'blue',
            'Texture': 'Filled',
            'Shape': 'Polygon',
            'Task': 'Face',
            'cue_stim': copy.copy(polygon_filled_b)
        },
        'fcr': {
            'cue': 'fcr',
            'Color': 'red',
            'Texture': 'Filled',
            'Shape': 'Circle',
            'Task': 'Scene',
            'cue_stim': copy.copy(circle_filled_r)
        },
        'fcb': {
            'cue': 'fcb',
            'Color': 'blue',
            'Texture': 'Filled',
            'Shape': 'Circle',
            'Task': 'Scene',
            'cue_stim': copy.copy(circle_filled_b)
        }
    }
    random_first = randomchoice(list(Cue_types))
    print('\n\n trial order: \n')
    print(len(Trial_order))
    Trial_dict = {}
    for i in range(len(Trial_order)):
        if i == 0:  #set first trial, randomly select
            Trial_dict[i] = Cue_types[random_first]
        else:
            #print('looking at trial 2')
            if Trial_order[i] == 'Stay':  # stay
                if Trial_dict[i - 1]['cue'] in ['fpr', 'fpb']:
                    Trial_dict[i] = Cue_types[randomchoice([
                        'fpr', 'fpb'
                    ])].copy(
                    )  # having .copy() is extremenly important, otherwise it will be
                elif Trial_dict[i - 1]['cue'] in [
                        'fcr', 'fcb'
                ]:  # a link to original object and not "switch"
                    Trial_dict[i] = Cue_types[randomchoice(['fcr',
                                                            'fcb'])].copy()
                elif Trial_dict[i - 1]['cue'] in ['dpr', 'dcr']:
                    Trial_dict[i] = Cue_types[randomchoice(['dpr',
                                                            'dcr'])].copy()
                elif Trial_dict[i - 1]['cue'] in ['dpb', 'dcb']:
                    Trial_dict[i] = Cue_types[randomchoice(['dpb',
                                                            'dcb'])].copy()
                else:
                    print('something wrong with stay trial sequence')
                    core.quit()

            elif Trial_order[i] == 'IDS':  #intra shift
                if Trial_dict[i - 1]['cue'] in ['fpr', 'fpb']:
                    Trial_dict[i] = Cue_types[randomchoice(['fcr',
                                                            'fcb'])].copy()
                elif Trial_dict[i - 1]['cue'] in ['fcr', 'fcb']:
                    Trial_dict[i] = Cue_types[randomchoice(['fpr',
                                                            'fpb'])].copy()
                elif Trial_dict[i - 1]['cue'] in ['dpr', 'dcr']:
                    Trial_dict[i] = Cue_types[randomchoice(['dpb',
                                                            'dcb'])].copy()
                elif Trial_dict[i - 1]['cue'] in ['dpb', 'dcb']:
                    Trial_dict[i] = Cue_types[randomchoice(['dpr',
                                                            'dcr'])].copy()
                else:
                    print(
                        'something wrong with intra dimensional shift trial sequence'
                    )
                    core.quit()

            elif Trial_order[i] == 'EDS':  # out of tree shift
                if Trial_dict[i - 1]['cue'] in ['fpr', 'fpb', 'fcr', 'fcb']:
                    Trial_dict[i] = Cue_types[randomchoice(
                        ['dpr', 'dcr', 'dpb', 'dcb'])].copy()
                elif Trial_dict[i - 1]['cue'] in ['dpr', 'dcr', 'dpb', 'dcb']:
                    Trial_dict[i] = Cue_types[randomchoice(
                        ['fpr', 'fpb', 'fcr', 'fcb'])].copy()
                else:
                    print(
                        'something wrong with extra dimensional shift trial sequence'
                    )
                    core.quit()
            else:
                print('something wrong with trial type sequence generation')
                core.quit()

        # record the trial type for each trial
        Trial_dict[i]['Trial_type'] = Trial_order[i]

        # random place scene or face picture
        Trial_dict[i]['pic'] = Pic_order[i]
        if Trial_dict[i]['pic'] == 'Face':
            Trial_dict[i]['pic_stim'] = Img_Faces[i]
        if Trial_dict[i]['pic'] == 'Scene':
            Trial_dict[i]['pic_stim'] = Img_Scene[i]
        Trial_dict[i]['img_path'] = Img_path[i]

    acc = []
    for trial_num in range(len(Trial_dict)):  #range(len(Trial_dict))
        # draw the cue
        ITI = np.random.choice(ITIs, 1)[0]
        if trial_num == 0:
            win.flip()
            get_ready = visual.TextStim(win=win,
                                        name='DemoInstruct',
                                        text=u'Get ready',
                                        alignVert='center',
                                        units='norm',
                                        pos=(0, 0),
                                        height=0.09,
                                        wrapWidth=None,
                                        ori=0,
                                        color=u'white',
                                        colorSpace='rgb',
                                        opacity=1,
                                        depth=0.0)
            get_ready.draw()
            win.flip()
            core.wait(2)

        Trial_dict[trial_num]['cue_stim'].draw()
        win.flip()
        core.wait(Cue_time)
        print(Trial_dict[trial_num])
        # this is for debug
        print(Trial_dict[trial_num]['Trial_type'])
        print(Trial_dict[trial_num]['cue'])
        print(Trial_dict[trial_num]['Color'])

        # draw the face or scene picture
        Trial_dict[trial_num]['pic_stim'].draw()
        win.flip()
        subRespo = event.waitKeys(maxWait=Pic_time,
                                  timeStamped=True,
                                  keyList=[yes_key, no_key, 'escape'])
        if Trial_dict[trial_num]['cue'] == 'dcr' or Trial_dict[trial_num][
                'cue'] == 'dpr':
            if Trial_dict[trial_num]['pic'] == 'Face':
                corr_resp = yes_key
            else:
                corr_resp = no_key
        if Trial_dict[trial_num]['cue'] == 'fpr' or Trial_dict[trial_num][
                'cue'] == 'fpb':
            if Trial_dict[trial_num]['pic'] == 'Face':
                corr_resp = yes_key
            else:
                corr_resp = no_key
        if Trial_dict[trial_num]['cue'] == 'fcr' or Trial_dict[trial_num][
                'cue'] == 'fcb':
            if Trial_dict[trial_num]['pic'] == 'Scene':
                corr_resp = yes_key
            else:
                corr_resp = no_key
        if Trial_dict[trial_num]['cue'] == 'dpb' or Trial_dict[trial_num][
                'cue'] == 'dcb':
            if Trial_dict[trial_num]['pic'] == 'Scene':
                corr_resp = yes_key
            else:
                corr_resp = no_key

        print(subRespo)

        if subRespo == None:
            trial_Corr = 0
        elif subRespo[0][0] == corr_resp:
            trial_Corr = 1
        elif subRespo[0][0] == 'escape':
            core.quit()
        else:
            trial_Corr = 0
        win.flip()
        #event.waitKeys()

        acc.append(trial_Corr)
        core.wait(ITI)
        #return;
    print('\n')
    print(acc)
    print(np.sum(acc))
    acc_feedback = visual.TextStim(
        win=win,
        name='accFeedback',
        text=u'Your accuracy was ' +
        str(int((np.sum(acc) / len(Trial_order)) * 100)) +
        ' percent. Would you like to try again? Press 1 or 0',
        font=u'Arial',
        alignVert='center',
        units='norm',
        pos=(0, 0),
        height=0.09,
        wrapWidth=None,
        ori=0,
        color=u'white',
        colorSpace='rgb',
        opacity=1,
        depth=0.0)
    Proportion = str(np.sum(acc) / n_trials * 100)
    print(Proportion)

    acc_feedback.draw()
    win.flip()
    anotherPrac = event.waitKeys(keyList=[yes_key, no_key])

    if anotherPrac[0] == yes_key:
        pracBlocks()
Beispiel #33
0
 def act(self, game):
     return random.randomchoice((['guard'], ['suicide']))