Ejemplo n.º 1
0
class Player(BasePlayer):
    early_finish = models.BooleanField(
        doc='if decided to abandon the waiting page clickin Finish the study')
    wp_timer_start = djmodels.DateTimeField(null=True, blank=True)
    sec_spent = models.IntegerField(
        doc='number of seconds spent on waiting page')
    sec_earned = models.FloatField(doc='dollars earned for waiting')
    decision_order = models.IntegerField(initial=10 ^ 10)
    current_ball = models.StringField(
    )  # the color of the ball a player will draw
    choice_of_urn = models.StringField(  # the guess by the player
        choices=['A', 'B'],
        widget=widgets.RadioSelectHorizontal())

    def set_payoffs(self):
        if self.choice_of_urn == self.subsession.storyline:
            self.payoff = Constants.bonus
        else:
            self.payoff = 0
Ejemplo n.º 2
0
class Group(BaseGroup):
    allocation_bureau = models.CurrencyField(
        verbose_name='How much do you want to allocate?')

    allocation_pol = models.CurrencyField(
        choices=currency_range(c(0), c(100), 1),
        verbose_name='How much do you want to allocate?')

    public_payoff = models.CurrencyField(initial=c(0))

    citizen_payoff = models.CurrencyField(initial=c(0))

    is_elected = models.BooleanField(
        verbose_name=
        'Do you want to re-elect the politician for another 4 rounds?')

    # def set_budget(self):
    #   p2 = self.get_player_by_role('Bureaucrat')
    #    p1 = self.get_player_by_role('Politician')
    #     p2.bureau_budget= p1.allocation_pol

    def set_payoffs(self):
        politician = self.get_player_by_role('Politician')
        bureaucrat = self.get_player_by_role('Bureaucrat')
        citizen = self.get_player_by_role('Citizen')
        waiting = self.get_player_by_role('Waiting')

        for player in [politician, bureaucrat]:
            if (self.round_number == self.session.vars['paying_round']):
                player.payoff = sum([
                    p.public_payoff for p in self.player.in_all_rounds()
                ]) * (Constants.multiplication_factor /
                      Constants.players_per_round)

        for player in [citizen]:
            if (self.round_number == self.session.vars['paying_round']):
                player.payoff = sum([
                    p.public_payoff for p in self.player.in_all_rounds()
                ]) * (Constants.multiplication_factor /
                      Constants.players_per_round) + sum([
                          p.citizen_payoff
                          for p in self.player.in_all_rounds()
                      ])
Ejemplo n.º 3
0
class Group(BaseGroup):

    group_account = models.IntegerField(initial=0)
    num_giver = models.IntegerField(initial=0)

    # boolean that shows if there is a majority in voting
    majority = models.BooleanField(initial=False)

    # 1:Keeper 2:Giver 3:No one , if None there is no majority
    majority_type = models.IntegerField()

    def set_num_giver(self):
        count_givers = 0
        for player in self.get_players():
            if player.binary_choice == 2:
                count_givers += 1
        self.num_giver = count_givers

    def set_group_account(self):
        self.group_account = self.num_giver * Constants.ini_privat

    # TODO: note: this function depends on 3 voting decisions, is not flexible to change in game design
    # TODO: it is also not flexible against the number of players per group
    # check for majority and determine who gets bonus
    def define_bonus(self):
        # votes coding according to player vars: 1: keeper, 2:giver , 3:no one
        votesdic = {1: 0, 2: 0, 3: 0}
        for player in self.get_players():
            votesdic[player.vote] += 1

        # check for majority
        for dec in votesdic.keys():
            if votesdic[dec] > 1:  #TODO only works for 3 players per group
                self.majority = True
                self.majority_type = dec
                break

        # determine which of the players will get no bonus (per default all get bonus)
        if self.majority and self.majority_type != 3:
            for player in self.get_players():
                if player.binary_choice == self.majority_type:
                    player.gets_bonus = False
                    player.bonus_amount = 0
Ejemplo n.º 4
0
class Decision(Model
               ):  # our custom model inherits from Django's base class "Model"
    REASONS = (
        ('dont_know', "Don't know"),
        ('example_reason', "Example reason"),
        ('another_example_reason', "Another example reason"),
    )

    value = models.IntegerField()  # will be randomly generated
    player_decision = models.BooleanField()
    reason = models.CharField(choices=REASONS)

    player = ForeignKey(
        Player
    )  # creates 1:m relation -> this decision was made by a certain player

    def __str__(self):
        return 'decision #%d for player %d (participant %d) - value %d'\
               % (self.pk, self.player.pk, self.player.participant.id_in_session, self.value)
Ejemplo n.º 5
0
class Player(BasePlayer):
    question_id = models.IntegerField()
    question = models.StringField()
    solution = models.IntegerField()
    solution_text = models.StringField()
    submitted_answer_text = models.StringField()
    submitted_answer = models.IntegerField()
    is_correct = models.BooleanField(initial=False, choices=[[True, _('Yes')], [False, _('No')]])
    explanation = models.StringField()
    n_try = models.IntegerField(initial=1)

    def current_question(self):
        return self.session.vars['quiz_file_list'][self.round_number - 1]

    def check_correct(self):
        self.is_correct = (self.submitted_answer == self.solution)
        self.submitted_answer_text = str(self.submitted_answer)
        if not self.is_correct:
            self.n_try = self.n_try + 1
Ejemplo n.º 6
0
class Appreciation(
        Model):  # our custom model inherits from Django's base class "Model"
    player = ForeignKey(
        Player, null=True, blank=True
    )  # creates 1:m relation -> this appreciation was made by a certain player
    proposition = ForeignKey(
        Proposition, null=True, blank=True
    )  # creates 1:m relation -> this appreciation is related to a certain proposition
    app_player_ID_ingroup = models.IntegerField()

    note = models.IntegerField(min=Constants.c_min_note,
                               max=Constants.c_max_note)
    reaction = models.CharField()
    related_version = models.PositiveIntegerField(initial=999)
    up_to_date = models.BooleanField(initial=False)

    def __str__(self):
        return "Appreciation n°{id}: {reaction}".format(id=self.pk,
                                                        reaction=self.reaction)
Ejemplo n.º 7
0
class Player(BasePlayer):
    item_value_estimate = models.CurrencyField(
        doc="""Estimate of the common value, may be different for each player"""
    )

    bid_amount = models.CurrencyField(min=Constants.min_allowable_bid,
                                      max=Constants.max_allowable_bid,
                                      doc="""Amount bidded by the player""")

    is_winner = models.BooleanField(
        initial=False, doc="""Indicates whether the player is the winner""")

    def set_payoff(self):
        if self.is_winner:
            self.payoff = self.group.item_value - self.bid_amount
            if self.payoff < 0:
                self.payoff = 0
        else:
            self.payoff = 0
Ejemplo n.º 8
0
class Player(BasePlayer):
    age = models.IntegerField(min=18, max=99, label="What is your age?")
    gender = models.StringField(
        choices=['Male', 'Female', 'Other', 'I don\'t want to say it'],
        label='What is your gender?')
    math_grade = models.FloatField(blank=True,
                                   min=1,
                                   max=6,
                                   label='What was your last math grade?')
    falk_time = models.IntegerField(
        choices=list(range(11)),
        widget=widgets.RadioSelectHorizontal,
        label=
        "How willing are you to give up something that is beneficial for you today in order to benefit more from that in the future?"
    )

    # Additional field to check if the participant wants to revise the answer
    revise_question = models.BooleanField(
        label="Do you want to change your answers?")
Ejemplo n.º 9
0
class Player(BasePlayer):
    waiting_period = models.IntegerField()
    treatment_method = models.StringField()
    sooner_period = models.StringField()
    comprehend_correct = models.BooleanField()

    switch_point = models.StringField(
        label='Silakan pilih "situasi" Anda',
        widget=widgets.RadioSelect,
    )

    def switch_point_choices(self):
        options_part1 = OptionOfGetMoney.formatted_option(self)
        options_1 = options_part1 + " "
        options_2 = " token, " + str(
            self.waiting_period) + " " + OptionOfGetMoney.part3

        return [
            #['test', str(type(Constants.spaces))],
            ['1', options_1 + '110' + options_2],
            ['2', options_1 + '120' + options_2],
            ['3', options_1 + '130' + options_2],
            ['4', options_1 + '140' + options_2],
            ['5', options_1 + '150' + options_2],
            ['6', options_1 + '160' + options_2],
            ['7', options_1 + '170' + options_2],
            ['8', options_1 + '180' + options_2],
            ['9', options_1 + '190' + options_2],
            ['10', 'Saya menolak untuk menunggu.'],
        ]

    comprehend = models.StringField(
        label='Berdasarkan pilihan anda, opsi manakah yang benar dibawah ini?',
        widget=widgets.RadioSelect,
    )

    def comprehend_choices(self):
        return [
            ['a', 'Anda akan menerima 100 token hari ini.'],
            ['b', 'Anda akan menerima 100 token 3 minggu kemudian.'],
            ['c', 'Anda akan menerima 150 token hari ini.'],
            ['d', 'Anda akan menerima 150 token 3 minggu kemudian.'],
        ]
Ejemplo n.º 10
0
class Group(BaseGroup):
    amount_offered = models.CurrencyField()

    offer_accepted = models.BooleanField(doc="if offered amount is accepted",
                                         widget=widgets.RadioSelectHorizontal,
                                         choices=(
                                             (True, 'Accept'),
                                             (False, 'Reject'),
                                         ))

    def set_payoffs(self):
        proposer = self.get_player_by_role('proposer')
        responder = self.get_player_by_role('responder')
        if self.offer_accepted:
            proposer.payoff = Constants.endowment - self.amount_offered
            responder.payoff = Constants.endowment + self.amount_offered
        else:
            proposer.payoff = Constants.payoff_if_rejected
            responder.payoff = Constants.payoff_if_rejected
Ejemplo n.º 11
0
class Player(BasePlayer):
    count = models.IntegerField(min=0, label='How many ones are in the table?')
    correct_counts = models.IntegerField(initial=0)
    counts_submitted = models.IntegerField(initial=0)
    pay_for_round = models.CurrencyField(initial=c(0))
    claimed_earnings = models.CurrencyField(
        label='Please announce your income in the box, then click next',
        min=c(0))
    tax_audit = models.BooleanField()
    tax_message = models.StringField()
    tax_on_claimed = models.CurrencyField(initial=c(0))
    post_tax_earnings = models.CurrencyField(initial=c(0))
    final_earnings = models.CurrencyField(initial=c(0))

    def check_answer(self):
        self.counts_submitted += 1
        if self.count == self.participant.vars['next_correct_answer']:
            self.correct_counts += 1
            self.pay_for_round += Constants.table_pay

    def update_iterator(self):
        self.participant.vars['i'] += 1
        if self.participant.vars['i'] >= Constants.max_tables_in_round:
            self.participant.vars['i'] = 0

    def handle_taxes(self):
        self.tax_audit = choice([True, False], p=[0.2, 0.8])
        self.tax_on_claimed = self.claimed_earnings * Constants.tax_rate
        self.post_tax_earnings = self.pay_for_round - self.tax_on_claimed
        if self.tax_audit:
            self.tax_message = 'You have been reviewed. '
            if self.claimed_earnings >= self.pay_for_round:
                self.tax_message = self.tax_message + 'However, you announced all of your earnings, so don\'t face any deductions.'
                self.final_earnings = self.post_tax_earnings
            else:
                not_claimed = self.pay_for_round - self.claimed_earnings
                extra_tax = not_claimed * 2 * Constants.tax_rate
                self.tax_message = self.tax_message + f'You did not announce {not_claimed} ECU of your earnings. You are deducted {extra_tax} ECU.'
                self.final_earnings = self.post_tax_earnings - extra_tax
        else:
            self.tax_message = 'You have not been reviewed this round.'
            self.final_earnings = self.post_tax_earnings
        self.participant.vars['payoff'] += self.final_earnings
Ejemplo n.º 12
0
class Player(BasePlayer):
    donation = models.CurrencyField(
        min=0,
        max=Constants.endowment,
        doc="donation in EUR",
        verbose_name='How much do you want to donate?')
    treatment = models.CharField(choices=Constants.treatment_specifications)
    claimed_content = models.CharField(
        choices=Constants.treatment_specifications +
        Constants.additional_specifications,
        doc="Claimed content of the picture",
        verbose_name="What do you see in the picture on the previous page?")
    claimed_content_correct = models.BooleanField()

    def check_claim(self):
        self.claimed_content_correct = self.treatment == self.claimed_content

    def calculate_payoff(self):
        self.payoff = Constants.endowment - self.donation
Ejemplo n.º 13
0
class Player(BasePlayer):
    item_value_estimate = models.CurrencyField(
        doc="""Aproximado del valor común, puede diferir entre jugadores""")

    bid_amount = models.CurrencyField(
        min=Constants.min_allowable_bid,
        max=Constants.max_allowable_bid,
        doc="""Cantidad ofertada por el jugador""")

    is_winner = models.BooleanField(initial=False,
                                    doc="""Indica si el jugador ha ganado""")

    def set_payoff(self):
        if self.is_winner:
            self.payoff = self.group.item_value - self.bid_amount
            if self.payoff < 0:
                self.payoff = 0
        else:
            self.payoff = 0
Ejemplo n.º 14
0
class Group(BaseGroup):
    total_contribution = models.CurrencyField()
    individual_share = models.CurrencyField()
    round_num = models.IntegerField()
    current_share = models.FloatField()
    # p1 = models.IntegerField()
    # p2 = models.IntegerField()
    # p3 = models.IntegerField()
    # p1_payoff = models.CurrencyField()
    # p2_payoff = models.CurrencyField()
    # p3_payoff = models.CurrencyField()
    global_contribution = models.CurrencyField()
    success = models.BooleanField()

    # glob_cont=models.CurrencyField()

    # def __init__(self):
    #    self.group = None
    def round_number(self):
        return self.subsession.round_number

    def set_payoffs(self):
        self.total_contribution = sum(
            [p.contribution for p in self.get_players()])
        self.individual_share = self.total_contribution * Constants.efficiency_factor / Constants.players_per_group
        self.global_contribution = sum(
            [p.total_contribution for p in self.in_all_rounds()])
        self.current_share = self.global_contribution * 100 / Constants.threshold
        # if Group.flood<self.current_share:
        #     self.success = 1
        # else:
        #     self.success = 0

        for p in self.get_players():
            p.payoff = Constants.endowment - p.contribution  # + self.individual_share
            # p1 = self.get_player_by_id(1)
            # p2 = self.get_player_by_id(2)
            # p3 = self.get_player_by_id(3)
            # p1_payoff = sum([p.payoff for p in self.in_previous_rounds() if p.p1 == 1])
            # p2_payoff = sum([p.payoff for p in self.in_previous_rounds() if p.p2 == 2])
            # p3_payoff = sum([p.payoff for p in self.in_previous_rounds() if p.p3 == 3])  # in_all_rounds
            print('p.payoff_is', p.payoff)
Ejemplo n.º 15
0
class Player(BasePlayer):
    numStage = models.IntegerField()
    # whether bomb is collected or not
    # store as integer because it's easier for interop with JS
    bomb = models.IntegerField()

    # location of bomb
    bomb_row = models.PositiveIntegerField()
    bomb_col = models.PositiveIntegerField()

    # number of collected boxes
    boxes_collected = models.IntegerField()

    # --- set round results and player's payoff
    # ------------------------------------------------------------------------------------------------------------------
    pay_this_round = models.BooleanField()
    round_result = models.FloatField()

    def set_payoff(self):

        # determine round_result as (potential) payoff per round
        if self.bomb:
            self.round_result = 0
        else:
            self.round_result = self.boxes_collected * Constants.box_value

        # set payoffs if <random_payoff = True> to round_result of randomly chosen round
        # randomly determine round to pay on player level
        if self.subsession.round_number == 1:
            self.participant.vars['round_to_pay'] = random.randint(1,Constants.num_rounds)

        if Constants.random_payoff:
            if self.subsession.round_number == self.participant.vars['round_to_pay']:
                self.pay_this_round = True
                self.payoff = self.round_result
            else:
                self.pay_this_round = False
                self.payoff = 0

        # set payoffs to round_result if <random_payoff = False>
        else:
            self.payoff = self.round_result
Ejemplo n.º 16
0
class Group(BaseGroup):
    total_contribution = models.IntegerField()
    total_payoff = models.IntegerField()

    #Add additional variables to this sequence if you want more players
    payout_from_manager_1 = models.FloatField(min=0)
    payout_from_manager_2 = models.FloatField(min=0)
    payout_from_manager_3 = models.FloatField(min=0)
    payout_from_manager_4 = models.FloatField(min=0)

    equally_distributed = models.BooleanField(blank=True)

    def set_poll(self):
        self.total_contribution = sum(
            [p.contribution for p in self.get_players()])
        self.total_payoff = self.total_contribution * Constants.multiplier
        self.set_fairly_distributed_amount()

    def set_fairly_distributed_amount(self):
        for p in self.get_players():
            p.fairly_distributed_amount()

    def set_payoffs(self):
        residuals = (self.total_payoff -
                     (self.payout_from_manager_1 + self.payout_from_manager_2 +
                      self.payout_from_manager_3 + self.payout_from_manager_4)
                     ) / Constants.players_per_group

        # Add additional elif statements to this sequence if you want more players
        for p in self.get_players():
            if p.id_in_group == 1:
                p.earnings = self.payout_from_manager_1
                p.payoff = self.payout_from_manager_1 + residuals
            elif p.id_in_group == 2:
                p.earnings = self.payout_from_manager_2
                p.payoff = self.payout_from_manager_2 + residuals
            elif p.id_in_group == 3:
                p.earnings = self.payout_from_manager_3
                p.payoff = self.payout_from_manager_3 + residuals
            elif p.id_in_group == 4:
                p.earnings = self.payout_from_manager_4
                p.payoff = self.payout_from_manager_4 + residuals
Ejemplo n.º 17
0
class Subsession(BaseSubsession):
    utility_slider = models.IntegerField()
    is_peak = models.BooleanField()
    peak_mean = models.IntegerField()
    offpeak_mean = models.IntegerField()
    alpha = models.IntegerField()

    def creating_session(self):
        if self.round_number % Constants.repeat_span != 1:
            self.group_randomly(fixed_id_in_group=True)

        self.peak_mean = self.in_round(
            self.round_number - 1
        ).peak_mean if self.round_number % Constants.repeat_span != 1 else Constants.peak_mean_base + np.random.randint(
            2)
        self.offpeak_mean = self.in_round(
            self.round_number - 1
        ).offpeak_mean if self.round_number % Constants.repeat_span != 1 else Constants.offpeak_mean_base + np.random.randint(
            2)
        self.alpha = self.in_round(
            self.round_number - 1
        ).alpha if self.round_number % Constants.repeat_span != 1 else np.round(
            Constants.alpha_base +
            np.random.randn() * Constants.alpha_amplifier)

        self.set_is_peak()
        self.update_utility()

    def update_utility(self):
        self.utility_slider = self.peak_mean if self.is_peak else self.offpeak_mean
        self.utility_slider += np.round(np.random.randn())

    def utility(self, x):
        return np.round(self.alpha / (1 + np.exp(self.utility_slider - x)))

    def set_is_peak(self):
        if self.round_number % Constants.repeat_span == 1:
            self.is_peak = False
        elif self.round_number % Constants.repeat_span == 2:
            self.is_peak = True
        else:
            self.is_peak = np.random.rand() > .2
Ejemplo n.º 18
0
class Player(BasePlayer):
    endowment = models.IntegerField()
    bid = models.CurrencyField(
        min=0, max=20, initial=0,
        blank=True)  # min will be set in Bid template to current price
    stop = models.BooleanField()
    accepted_bids = models.IntegerField()
    total_payoff = models.CurrencyField()

    def vars_for_template(self):
        if self.subsession.round_number % self.session.config[
                "rounds_per_session"] == 0:
            round_in_session = 3  # else it would return 0
        else:
            round_in_session = self.subsession.round_number % self.session.config[
                "rounds_per_session"]
        return dict(
            endowment=self.participant.vars["endowment"],
            land=self.participant.vars["land"],
            num_land=len(self.participant.vars["land"]),
            player_accepted_bids=self.participant.vars["accepted_bids"],
            price=self.session.vars["price"],
            num_stopped=self.session.vars["players_stopped"],
            round_in_session=round_in_session,
            total_endowments=self.session.vars["total_num_endowments"],
            payoff=self.participant.vars["payoff"],
            rounds_per_session=self.session.config["rounds_per_session"])

    def calculate_payoffs(self):
        net_units = self.participant.vars["endowment"] - self.participant.vars[
            "accepted_bids"]
        cash_change = self.session.vars["price"] * net_units
        profit_irrigated = sum(self.participant.vars["land"]
                               [:self.participant.vars["accepted_bids"]])
        profit_dry = len(self.participant.vars["land"]
                         ) - self.participant.vars["accepted_bids"]
        profit_land = profit_irrigated + profit_dry
        profit = profit_land + cash_change
        self.participant.vars["payoff"] += profit

    def store_payoffs(self):
        self.total_payoff = self.participant.vars["payoff"]
Ejemplo n.º 19
0
class Subsession(BaseSubsession):
    storyline = models.StringField()
    room_busy = models.BooleanField(initial=False)
    pay_per_min = models.FloatField(
        doc='how much to pay per minute of waiting. Set to 0 to pay nothing')
    wait_before_leave = models.IntegerField(
        doc='how many seconds to wait. Set to negative number '
        'to switch off the option. Set to 0 to show immediately')

    def creating_session(self):
        self.storyline = random.choice(Constants.urns)
        self.pay_per_min = self.session.config.get('pay_per_min',
                                                   Constants.pay_per_min)
        self.wait_before_leave = self.session.config.get(
            'wait_before_leave', Constants.wait_before_leave)
        for p in self.get_players():
            if self.storyline == 'A':
                p.current_ball = random.choice(Constants.urn_A)
            else:
                p.current_ball = random.choice(Constants.urn_B)
Ejemplo n.º 20
0
class Player(BasePlayer):
    answer = models.IntegerField(choices=[1, 2, 3, 4, 5, 6, 7, 8])
    ans_correct = models.BooleanField()

    #Cognitive
    bat = models.IntegerField(min=0, max=110)
    machines = models.IntegerField(min=0, max=300)
    lake = models.IntegerField(min=0, max=48)

    # Demographics
    age = models.IntegerField(label='What is your age?', min=13, max=125)

    gender = models.StringField(choices=['Male', 'Female', 'Other'],
                                label='What is your gender?',
                                widget=widgets.RadioSelect)

    income = models.IntegerField(
        label='What is the annual income of your family in USD?',
        min=100,
        max=3000000)
Ejemplo n.º 21
0
class Player(BasePlayer):
    pay_round = models.IntegerField()
    choice = models.StringField()
    win = models.BooleanField()

    sur_q01 = make_survey_field(1)

    sur_q02 = make_survey_field(2)

    sur_q03 = make_survey_field(3)

    sur_q04 = make_survey_field(4)

    sur_q05 = make_survey_field(5)

    sur_q06 = make_survey_field(6)

    sur_q07 = make_survey_field(7)

    sur_q08 = make_survey_field(8)
Ejemplo n.º 22
0
class Player(BasePlayer):
    player_role = models.IntegerField()

    tn = models.StringField(blank=False)
    accept_info = models.BooleanField(blank=False,
                                      widget=widgets.CheckboxInput)
    accept_1 = models.BooleanField(blank=False, widget=widgets.CheckboxInput)
    accept_2 = models.BooleanField(blank=False, widget=widgets.CheckboxInput)
    accept_3 = models.BooleanField(blank=False, widget=widgets.CheckboxInput)

    pay_this_round = models.BooleanField()
    round_result = models.CurrencyField()
    extension = models.IntegerField()

    Instr1 = models.IntegerField(blank=False,
                                 choices=[[1, 'True'], [2, 'False']],
                                 widget=widgets.RadioSelect)
    Instr2 = models.IntegerField(blank=False,
                                 choices=[[1, 'True'], [2, 'False']],
                                 widget=widgets.RadioSelect)
    Instr3 = models.IntegerField(blank=False,
                                 choices=[[1, 'True'], [2, 'False']],
                                 widget=widgets.RadioSelect)
    Instr4 = models.IntegerField(blank=False,
                                 choices=[[1, 'True'], [2, 'False']],
                                 widget=widgets.RadioSelect)

    round_start = models.BooleanField(blank=False,
                                      widget=widgets.CheckboxInput)

    def define_condition_player(self):
        self.extension = self.participant.vars.get('extension')

    def set_final_payoff(self):
        if self.subsession.round_number == 1:
            self.participant.vars['round_to_pay'] = random.randint(
                1, Constants.num_rounds)

        if self.subsession.round_number == self.participant.vars[
                'round_to_pay']:
            self.pay_this_round = True
            self.payoff = self.round_result
            self.participant.vars['payoff_lira'] = self.round_result
            self.participant.vars[
                'payoff_eur'] = self.round_result.to_real_world_currency(
                    self.session)
        else:
            self.pay_this_round = False
            self.payoff = c(0)
Ejemplo n.º 23
0
class Player(BasePlayer):
    # Variable para saber si alguien tiene o no el bien x (True lo tiene, False no)
    bien_x = models.BooleanField()
    dotacion_A = models.CurrencyField(initial=Constants.dotacion_inicial_A)
    dotacion_B = models.CurrencyField(initial=Constants.dotacion_inicial_B)

    extraccion = models.CurrencyField(max=Constants.dotacion_inicial_A,
                                      min=0,
                                      initial=0)
    # Pago ronda anterior
    pago_anterior = models.CurrencyField(initial=0)

    def role(self):
        if self.id_in_group == 1:
            return 'A'
        else:
            return 'B'

    def extraccion_max(self):
        return self.dotacion
Ejemplo n.º 24
0
class Player(BasePlayer):
    investment = models.CurrencyField(
        verbose_name="How much do you want to invest?")
    lottery_payoff = models.CurrencyField()
    lottery_won = models.BooleanField()
    selected_round = models.PositiveIntegerField()

    def play_lottery(self):
        if random() >= Constants.winning_probability:
            self.lottery_won = False
            self.lottery_payoff = Constants.endowment - self.investment
        else:
            self.lottery_won = True
            self.lottery_payoff = Constants.endowment + self.investment * (
                1 + Constants.winning_return)

    def pick_round(self):
        self.selected_round = randint(1, Constants.num_rounds)
        correct_player = self.in_round(self.selected_round)
        self.payoff = correct_player.lottery_payoff
Ejemplo n.º 25
0
class Player(BasePlayer):
    amount_risky = models.CurrencyField(max=Constants.endowment, min=0)
    project_success = models.BooleanField()
    return_from_investment = models.CurrencyField(initial=0)

    def set_payoffs(self):
        import random
        random_number = random.random()
        print(random_number)
        self.payoff = Constants.endowment - self.amount_risky
        if random_number > Constants.p_success:
            self.project_success = False
        else:
            self.project_success = True
            self.return_from_investment = self.amount_risky * Constants.multiplier
        self.payoff = self.payoff + self.return_from_investment
        print('amount invested:', self.amount_risky)
        print('project success:', self.project_success)
        print('return from investment:', self.return_from_investment)
        print('payoff:', self.payoff)
Ejemplo n.º 26
0
class Group(BaseGroup):
    peak_pricing = models.IntegerField(min=Constants.minimum_price)

    offpeak_pricing = models.IntegerField(min=Constants.minimum_price)

    is_blackout = models.BooleanField()

    total_consumption = models.CurrencyField()

    def pricing(self):
        n = (self.subsession.round_number -
             1) // Constants.repeat_span * Constants.repeat_span + 1
        return self.in_round(
            n).peak_pricing if self.subsession.is_peak else self.in_round(
                n).offpeak_pricing

    def set_payoffs(self):
        self.total_consumption = sum([
            p.consumption for p in self.get_players() if p.role() == 'Consumer'
        ])
        self.is_blackout = self.total_consumption >= Constants.blackout_criteria
        for p in self.get_players():
            if p.role() == 'Producer':
                p.payoff = Constants.profit_per_kw * self.total_consumption
                if self.total_consumption in range(
                        *Constants.bonus_consumption_range):
                    p.payoff += Constants.consumption_bonus
                elif self.total_consumption not in range(
                        *Constants.penalty_consumption_range):
                    p.payoff += Constants.consumption_penalty
            else:
                p.payoff = Constants.blackout_penalty if self.is_blackout else self.subsession.utility(
                    p.consumption)
                if self.subsession.round_number % Constants.repeat_span == 0:
                    repeat_span_idx = self.subsession.round_number // Constants.repeat_span
                    p.payoff -= sum([
                        self.in_round(i).pricing() * p.in_round(i).consumption
                        for i in
                        range((repeat_span_idx - 1) * Constants.repeat_span +
                              1, repeat_span_idx * Constants.repeat_span + 1)
                    ])
Ejemplo n.º 27
0
class Player(BasePlayer):
    dump_tasks = models.LongStringField()
    qs_not_available = models.BooleanField(
        initial=False
    )  # When this is true the user asnwers all questions correctly.

    @property
    def total_attempts(self):
        """We get all tasks associated to the current user, to which he provided any answers."""
        return self.tasks.filter(answer__isnull=False).count()

    @property
    def correct_answers(self):
        """We get all tasks associated to the current user, to which he provided correct answers."""
        return self.tasks.filter(answer=F('question__solution')).count()

    @property
    def available_qs(self):
        """Here we check for all questions that already correctly answered by a user."""
        correct_qs_ids = self.tasks.filter(
            answer=F('question__solution')).values_list('question__id',
                                                        flat=True)
        return Q.objects.exclude(id__in=correct_qs_ids)

    def get_random_question(self):
        """We pick a random question from the list of available ones.
        NB: If the list of questions  is huge it should be done differently. """
        available_qs = self.available_qs
        if available_qs.exists():
            return random.choice(available_qs)

    def get_or_create_task(self):
        """We check whether there is unfinished task, if there is we return it. If there is not, we create a new one."""
        unfinished_tasks = self.tasks.filter(answer__isnull=True)
        if unfinished_tasks.exists():
            return unfinished_tasks.latest()
        else:
            q = self.get_random_question()
            if q:
                task = self.tasks.create(question=q)
                return task
Ejemplo n.º 28
0
class Group(BaseGroup):
    offer = models.PositiveIntegerField(
        max=Constants.pot_size,
        min=0,
        widget=widgets.SliderInput(attrs={'step': '1'}),
        verbose_name=
        "Please decide about the quantity to share with the other player")
    accepted = models.BooleanField(
        choices=[(True, 'Yes'), (False, 'No')],
        verbose_name="Please decide about the other player's offer",
        doc="response choice")

    def calc_payoff(self):
        proposer = self.get_player_by_role('proposer')
        responder = self.get_player_by_role('responder')
        if self.accepted:
            proposer.payoff = Constants.pot_size - self.offer
            responder.payoff = self.offer
        else:
            proposer.payoff = c(0)
            responder.payoff = c(0)
Ejemplo n.º 29
0
class Player(BasePlayer):
    question_id = models.IntegerField()
    question = models.StringField()
    choice_1 = models.StringField()
    choice_2 = models.StringField()
    choice_3 = models.StringField()
    choice_4 = models.StringField()
    solution = models.StringField()
    current_score = models.IntegerField(min=0, max=5, initial=0)
    submitted_answer = models.StringField(widget=widgets.RadioSelect)
    is_correct = models.BooleanField()

    def current_question(self):
        return self.participant.vars['questions'][self.round_number - 1]

    def check_correct(self):
        self.is_correct = (self.submitted_answer == self.solution)

    def calc_current_score(self):
        player_in_all_rounds = self.in_all_rounds()
        self.current_score = sum([p.is_correct for p in player_in_all_rounds])
Ejemplo n.º 30
0
class Risk(djmodels.Model):
    player = models.ForeignKey(Player, related_name="risks")
    left_col = models.IntegerField()
    right_col = models.IntegerField()
    answer = models.BooleanField(null=True,
                                 doc='False - option A, True - option B',
                                 widget=widgets.RadioSelectHorizontal)

    def __str__(self):
        answer_to_str = None
        if self.answer == True:
            answer_to_str = 'Option B'
        elif self.answer == False:
            answer_to_str = 'Option A'
        return 'choosing between option A({}) and B({}) with the probs {}/{} {} was chosen'.format(
            Constants.risk_choices_A,
            Constants.risk_choices_B,
            self.left_col,
            self.right_col,
            answer_to_str,
        )