How to use the otree.api.BasePlayer function in otree

To help you get started, we’ve selected a few otree examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github oTree-org / otree-core / otree / checks / __init__.py View on Github external
))
        misplaced_templates.discard(helper.app_config.label)
        if misplaced_templates:
            hint = (
                'Move template files from "{app}/templates/" '
                'to "{app}/templates/{app}" subfolder'.format(
                    app=helper.app_config.label)
            )
            helper.add_error(
                "TemplatesInWrongDir: Templates files in app's root template directory",
                hint=hint, numeric_id=103,
            )


base_model_attrs = {
    'Player': set(dir(BasePlayer)),
    'Group': set(dir(BaseGroup)),
    'Subsession': set(dir(BaseSubsession)),
}

model_field_substitutes = {
    int: 'IntegerField',
    float: 'FloatField',
    bool: 'BooleanField',
    str: 'CharField',
    Currency: 'CurrencyField',
    type(None): 'IntegerField' # not always int, but it's a reasonable suggestion
}


def model_classes(helper: AppCheckHelper, **kwargs):
github WZBSocialScienceCenter / otreeutils / otreeutils / surveys.py View on Github external
raise ValueError('duplicate field name: `%s`' % field_name)
        model_attrs[field_name] = qdef['field']

    for survey_page in survey_definitions:
        for fielddef in survey_page['survey_fields']:
            if isinstance(fielddef, dict):
                for field_name, qdef in fielddef['fields']:
                    add_field(field_name, qdef)
            else:
                add_field(*fielddef)

    # add optional fields
    model_attrs.update(other_fields)

    # dynamically create model
    model_cls = type('Player', (BasePlayer, _SurveyModelMixin), model_attrs)

    return model_cls
github oTree-org / oTree / public_goods_simple / models.py View on Github external
class Group(BaseGroup):
    total_contribution = models.CurrencyField()
    individual_share = models.CurrencyField()

    def set_payoffs(self):
        players = self.get_players()
        contributions = [p.contribution for p in players]
        self.total_contribution = sum(contributions)
        self.individual_share = (
            self.total_contribution * Constants.multiplier / Constants.players_per_group
        )
        for p in players:
            p.payoff = Constants.endowment - p.contribution + self.individual_share


class Player(BasePlayer):
    contribution = models.CurrencyField(min=0, max=Constants.endowment)
github oTree-org / oTree / guess_two_thirds / models.py View on Github external
self.best_guess = min(
            guesses, key=lambda guess: abs(guess - self.two_thirds_avg)
        )

        winners = [p for p in players if p.guess == self.best_guess]
        self.num_winners = len(winners)

        for p in winners:
            p.is_winner = True
            p.payoff = Constants.jackpot / self.num_winners

    def two_thirds_avg_history(self):
        return [g.two_thirds_avg for g in self.in_previous_rounds()]


class Player(BasePlayer):
    guess = models.IntegerField(min=0, max=Constants.guess_max)
    is_winner = models.BooleanField(initial=False)
github Leeps-Lab / high_frequency_trading / hft_bcs / utility.py View on Github external
def validate_model(model):
        if isinstance(model, BasePlayer):
            return 'player'
        elif isinstance(model, BaseSubsession):
            return 'subsession'
        else:
            raise ValueError('invalid model %s' % model.__class__.__name__)
    model_type = validate_model(model)
github oTree-org / oTree / volunteer_dilemma / models.py View on Github external
num_volunteers = models.IntegerField()

    def set_payoffs(self):
        players = self.get_players()
        self.num_volunteers = sum([p.volunteer for p in players])
        if self.num_volunteers > 0:
            baseline_amount = Constants.general_benefit
        else:
            baseline_amount = c(0)
        for p in players:
            p.payoff = baseline_amount
            if p.volunteer:
                p.payoff -= Constants.volunteer_cost


class Player(BasePlayer):
    volunteer = models.BooleanField(doc="""Whether player volunteers""")
github oTree-org / oTree / bargaining / models.py View on Github external
class Group(BaseGroup):
    total_requests = models.CurrencyField()

    def set_payoffs(self):
        players = self.get_players()
        self.total_requests = sum([p.request for p in players])
        if self.total_requests <= Constants.amount_shared:
            for p in players:
                p.payoff = p.request
        else:
            for p in players:
                p.payoff = c(0)


class Player(BasePlayer):
    request = models.CurrencyField(
        doc="""
        Amount requested by this player.
        """,
        min=0,
        max=Constants.amount_shared,
    )

    def other_player(self):
        return self.get_others_in_group()[0]
github oTree-org / oTree / common_value_auction / models.py View on Github external
minimum = self.item_value - Constants.estimate_error_margin
        maximum = self.item_value + Constants.estimate_error_margin
        estimate = random.uniform(minimum, maximum)

        estimate = round(estimate, 1)

        if estimate < Constants.min_allowable_bid:
            estimate = Constants.min_allowable_bid
        if estimate > Constants.max_allowable_bid:
            estimate = Constants.max_allowable_bid

        return estimate


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:
github oTree-org / oTree / survey / models.py View on Github external
class Constants(BaseConstants):
    name_in_url = 'survey'
    players_per_group = None
    num_rounds = 1


class Subsession(BaseSubsession):
    pass


class Group(BaseGroup):
    pass


class Player(BasePlayer):

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

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

    crt_bat = models.IntegerField(
        label='''
        A bat and a ball cost 22 dollars in total.
        The bat costs 20 dollars more than the ball.
        How many dollars does the ball cost?'''
    )
github oTree-org / oTree / bertrand / models.py View on Github external
players = self.get_players()
        self.winning_price = min([p.price for p in players])
        winners = [p for p in players if p.price == self.winning_price]
        winner = random.choice(winners)

        for p in players:
            if p == winner:
                p.is_winner = True
                p.payoff = p.price
            else:
                p.is_winner = False
                p.payoff = c(0)


class Player(BasePlayer):
    price = models.CurrencyField(
        min=0,
        max=Constants.maximum_price,
        doc="""Price player offers to sell product for""",
    )

    is_winner = models.BooleanField()