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

在oTree中基于布尔输入重新分组玩家的技术求助

Pythonic Solution for Player Grouping

Here's a cleaned-up, adaptable implementation that meets your requirements:

import random

def after_all_players_arrive(group: Group):
    # Fetch all players from the group
    all_players = group.get_players()
    
    # Split players into participating/non-participating groups
    participating = [p for p in all_players if p.participating]
    non_participating = [p for p in all_players if not p.participating]
    
    # Handle odd participant count: move one random player to non-participating group
    if len(participating) % 2 != 0:
        moved_player = random.choice(participating)
        participating.remove(moved_player)
        non_participating.append(moved_player)
        # Optional: Update the player's participating status if needed
        # moved_player.participating = False
    
    # Shuffle participants to ensure random pairings
    random.shuffle(participating)
    
    # Split into groups of two (works for any even number of participants)
    game_groups = [participating[i:i+2] for i in range(0, len(participating), 2)]
    
    # Assign group identifiers to each player for easy reference
    for idx, game_group in enumerate(game_groups, start=1):
        for player in game_group:
            player.game_group = idx  # Or store the group object directly
    
    # Mark non-participating players with a distinct group ID
    for player in non_participating:
        player.game_group = 0

Key Improvements & Breakdown:

  • Clean List Comprehensions: Replace messy conditional loops with concise, readable splits for participating/non-participating players.
  • Randomized Fairness: Uses random.choice() to select a player to reassign when counts are odd, and random.shuffle() ensures unbiased pairings.
  • Flexible Pairing: The slicing pattern participating[i:i+2] automatically creates groups of two regardless of how many even-numbered participants there are—works for any group size.
  • Explicit Attribute Assignment: Adds a clear game_group attribute to each player, making it straightforward to track their group later in your logic.
  • Removed Redundancies: Eliminated unused variables (like number_players) and fixed incorrect list wrapping from the original code.

Notes:

  • If participating is a method (not a boolean attribute), adjust the list comprehensions to p.participating() instead of p.participating.
  • The optional step to update the moved player's participating status depends on whether you need to reflect the change in their core field, or just group them separately.
  • This code adapts seamlessly to any initial group size, as long as Group.get_players() returns an iterable of Player objects.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 09:10:23