You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

oTree如何创建依赖玩家输入的概率分布随机变量实现中奖判定

oTree 投资中奖概率判定功能实现步骤

1. 先在 models.py 中新增必要存储字段

你需要先在Player类中补充两个字段,用于存储随机摇奖结果和中奖状态,完整示例代码如下:

from otree.api import *

class Player(BasePlayer):
    # 你原有定义的投资积分选择字段保留
    points = models.IntegerField(
        label="How many points would you like to invest?",
        choices=[
             [0, "None"],
             [1, "1 point"],
             [2, "2 points"],
             [3, "3 points"]]
    )
    # 新增字段:存储1-10的随机摇出数字
    rolled_num = models.IntegerField()
    # 新增字段:存储是否中奖的状态
    is_won = models.BooleanField()

2. 在 pages.py 中编写随机判定逻辑

注意不要使用Python自带的random库,要使用oTree内置的随机方法,避免出现兼容性问题,逻辑可以写在投资提交页的before_next_page方法中,确保用户提交投资选择后立刻生成固定的中奖结果,不会随页面刷新变动:

# 你原有定义的投资选择页类,补充before_next_page方法即可
class InvestPage(Page):
    form_model = 'player'
    form_fields = ['points']

    def before_next_page(player, timeout_happened):
        # 生成1-10的等概率随机整数
        player.rolled_num = player.random.randint(1, 10)
        # 按规则计算中奖阈值:(1+投资积分),摇出数字小于等于阈值即为中奖
        win_threshold = 1 + player.points
        player.is_won = player.rolled_num <= win_threshold

# 你原有定义的收益页类,补充变量传递逻辑
class ResultPage(Page):
    def vars_for_template(player):
        # 拼接你需要展示的结果文案,直接传给模板调用
        result_msg = f"You have rolled the number {player.rolled_num}. That means you have {'won' if player.is_won else 'lost'}."
        return {"result_msg": result_msg}

3. 在收益页的HTML模板中展示结果

打开对应收益页的HTML文件(一般命名为ResultPage.html),直接插入下面的代码即可展示结果文案:

<p>{{ result_msg }}</p>

注意事项

  • 必须使用player.random调用随机方法,这是oTree封装的专用随机工具,符合实验的可复现要求,也不会出现你遇到的无法运行的问题
  • 不要直接在模板中生成随机数,会导致每次刷新页面结果变动,影响实验数据准确性

内容的提问来源于stack exchange,提问作者tanja94

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 08:30:04