from otree.api import * import random doc = """ Siyasal Kamu Malı Deneyi — Hazine Versiyonu (Rastgele Ufuk) ============================================================ Threshold Public Goods Game with Treasury, Political Competition, Strategic Information Distortion, and a RANDOM HORIZON. Length rule: • Rounds 1–3 are always played. • Round 4 is played with probability 0.50 (after round 3). • Round 5 is played with probability 0.25 (after round 4, conditional). • Round 5 is the certain maximum. """ class C(BaseConstants): NAME_IN_URL = 'pgg' PLAYERS_PER_GROUP = 7 NUM_ROUNDS = 20 # maximum possible rounds N_VOTERS = 5 # ── Period structure ─────────────────────────────────────────────── PERIOD_LENGTH = 4 GUARANTEED_PERIODS = 3 MAX_PERIODS = 5 # Periods 1–3 are always played. # Period 4 is played with probability 0.50. # Period 5 is played with probability 0.25, conditional on reaching period 4. CONTINUATION_PROBS_BY_PERIOD = { 4: 0.50, 5: 0.25, } GUARANTEED_ROUNDS = GUARANTEED_PERIODS * PERIOD_LENGTH # 12 # Elections occur at the end of each 4-round term, # but only if another period will actually be played. ELECTION_ROUNDS = [4, 8, 12, 16] # New leader terms start after elections. TERM_START_ROUNDS = [1, 5, 9, 13, 17] # Economy ENDOWMENT = 20 THRESHOLD = 50 MPCR_MIN = 0.2 MPCR_MAX = 1 REFUND_RATE_FAIL = 0.80 # Belief elicitation BELIEF_BONUS = 2 BELIEF_TOLERANCE_REVENUE = 5 # Treasury INITIAL_TREASURY = 50 TREASURY_FLOOR = -50 # Salaries LEADER_SALARY = 20 OPP_SALARY = 20 # Elections — only fire if a subsequent round will actually be played ELECTION_ROUNDS = [4, 8] TERM_START_ROUNDS = [1, 5, 9] # Roles ROLE_LEADER = 'leader' ROLE_OPPOSITION = 'opposition' ROLE_VOTER = 'voter' LEADER_ID = 1 OPPOSITION_ID = 2 class Subsession(BaseSubsession): pass def creating_session(subsession: Subsession): if subsession.round_number == 1: # Roles are NOT fixed in advance. A pre-game election (held during # round 1, before normal play) decides who becomes leader/opposition. # Until then everyone is a placeholder 'voter'. for p in subsession.get_players(): p.participant.vars.setdefault('role', C.ROLE_VOTER) # ── Decide the random horizon ONCE for the whole session ───── final_period = C.GUARANTEED_PERIODS for period in range(C.GUARANTEED_PERIODS + 1, C.MAX_PERIODS + 1): if random.random() < C.CONTINUATION_PROBS_BY_PERIOD.get(period, 0): final_period = period else: break final_round = final_period * C.PERIOD_LENGTH subsession.session.vars['final_period'] = final_period subsession.session.vars['final_round'] = final_round for p in subsession.get_players(): p.role_in_game = p.participant.vars.get('role', C.ROLE_VOTER) def current_role(player: 'Player'): return player.participant.vars.get('role', player.role_in_game or C.ROLE_VOTER) # ───────────────────────────────────────────────────────────────────── # RANDOM-HORIZON HELPERS # ───────────────────────────────────────────────────────────────────── def get_final_round(player: 'Player'): """The realised last round for this session: 12, 16, or 20.""" return player.session.vars.get('final_round', C.NUM_ROUNDS) def game_active(player: 'Player'): """True while the current round is within the realised horizon.""" return player.round_number <= get_final_round(player) def is_last_round(player: 'Player'): return player.round_number == get_final_round(player) def get_final_period(player: 'Player'): """The realised last period for this session: 3, 4, or 5.""" return player.session.vars.get('final_period', C.MAX_PERIODS) def get_current_period(player: 'Player'): """Current political period/term: 1, 2, 3, 4, or 5.""" return ((player.round_number - 1) // C.PERIOD_LENGTH) + 1 def get_round_in_period(player: 'Player'): """Round within the current 4-round period: 1, 2, 3, or 4.""" return ((player.round_number - 1) % C.PERIOD_LENGTH) + 1 def election_active(player: 'Player'): """ Election happens at the end of a 4-round period, but only if another period will actually be played. """ return ( game_active(player) and player.round_number in C.ELECTION_ROUNDS and player.round_number < get_final_round(player) ) class Group(BaseGroup): # State mpcr = models.FloatField() # Announcements announced_distribution = models.FloatField(initial=0) opp_announced_distribution = models.FloatField(initial=0) # Contributions total_contribution = models.FloatField(initial=0) threshold_met = models.BooleanField(initial=False) excess_contribution = models.FloatField(initial=0) # Revenue allocation actual_project_revenue = models.FloatField(initial=0) revenue_gap = models.FloatField(initial=0) gap_to_treasury = models.FloatField(initial=0) leader_private_gap = models.FloatField(initial=0) excess_to_treasury = models.FloatField(initial=0) leader_private_excess = models.FloatField(initial=0) # Treasury treasury_start = models.FloatField(initial=C.INITIAL_TREASURY) treasury_pre_tax = models.FloatField(initial=0) treasury_end = models.FloatField(initial=0) tax_per_voter = models.FloatField(initial=0) deficit_used_this_term = models.BooleanField(initial=False) # Election votes_incumbent = models.IntegerField(initial=0) votes_opposition = models.IntegerField(initial=0) election_held = models.BooleanField(initial=False) election_winner = models.StringField(initial='') # Pre-game candidacy & election (round 1 only) n_volunteers = models.IntegerField(initial=0) candidate1_id = models.IntegerField(initial=0) candidate2_id = models.IntegerField(initial=0) pregame_votes_c1 = models.IntegerField(initial=0) pregame_votes_c2 = models.IntegerField(initial=0) pregame_winner_id = models.IntegerField(initial=0) pregame_loser_id = models.IntegerField(initial=0) # Helpers def get_leader(self): return next((p for p in self.get_players() if current_role(p) == C.ROLE_LEADER), None) def get_opposition(self): return next((p for p in self.get_players() if current_role(p) == C.ROLE_OPPOSITION), None) def get_voters(self): return [p for p in self.get_players() if current_role(p) == C.ROLE_VOTER] # ── Pre-game candidacy & election ──────────────────────────────── def select_candidates(self): """ Choose exactly 2 leader candidates from volunteers: • >= 2 volunteers → 2 random among volunteers • == 1 volunteer → that volunteer + 1 random from the others • == 0 volunteers → 2 random from everyone """ players = list(self.get_players()) volunteers = [p for p in players if p.field_maybe_none('wants_candidate') is True] self.n_volunteers = len(volunteers) if len(volunteers) >= 2: chosen = random.sample(volunteers, 2) elif len(volunteers) == 1: others = [p for p in players if p.id_in_group != volunteers[0].id_in_group] chosen = [volunteers[0]] + random.sample(others, 1) else: chosen = random.sample(players, 2) self.candidate1_id = chosen[0].id_in_group self.candidate2_id = chosen[1].id_in_group for p in players: p.is_candidate = p.id_in_group in (self.candidate1_id, self.candidate2_id) def conduct_pregame_election(self): players = list(self.get_players()) voters = [p for p in players if not p.is_candidate] c1, c2 = self.candidate1_id, self.candidate2_id v1 = v2 = 0 for v in voters: choice = v.field_maybe_none('pre_game_vote') if choice is None: continue # Hem id ('4') hem placeholder ('Aday 1') değerlerini tanı if choice == str(c1) or choice == 'Aday 1': v1 += 1 elif choice == str(c2) or choice == 'Aday 2': v2 += 1 self.pregame_votes_c1 = v1 self.pregame_votes_c2 = v2 if v1 > v2: winner, loser = c1, c2 elif v2 > v1: winner, loser = c2, c1 else: winner, loser = random.sample([c1, c2], 2) self.pregame_winner_id = winner self.pregame_loser_id = loser for p in players: if p.id_in_group == winner: role = C.ROLE_LEADER elif p.id_in_group == loser: role = C.ROLE_OPPOSITION else: role = C.ROLE_VOTER # Store role at participant level p.participant.vars['role'] = role # Store role in every round's Player object for fp in p.participant.get_players(): fp.role_in_game = role # Core mechanics def draw_mpcr(self): self.mpcr = round(random.uniform(C.MPCR_MIN, C.MPCR_MAX), 2) def initialize_round_state(self): if self.round_number == 1: self.treasury_start = C.INITIAL_TREASURY self.deficit_used_this_term = False else: prev = self.in_round(self.round_number - 1) self.treasury_start = prev.treasury_end if self.round_number in C.TERM_START_ROUNDS: self.deficit_used_this_term = False else: self.deficit_used_this_term = prev.deficit_used_this_term def max_allowed_announcement(self): base = self.treasury_start + C.THRESHOLD * self.mpcr * C.N_VOTERS if self.deficit_used_this_term: return max(0.0, round(base, 2)) return max(0.0, round(base + abs(C.TREASURY_FLOOR), 2)) def check_threshold(self): voters = self.get_voters() self.total_contribution = round(sum(v.contribution or 0 for v in voters), 2) self.threshold_met = self.total_contribution >= C.THRESHOLD self.excess_contribution = round(max(0.0, self.total_contribution - C.THRESHOLD), 2) def collect_opposition_decision(self): if self.session.config.get('treatment', 'T2') != 'T2': self.opp_announced_distribution = 0 return opp = self.get_opposition() if opp is None: self.opp_announced_distribution = 0 return val = opp.field_maybe_none('opp_announced_distribution_input') if val is None: val = round(C.THRESHOLD * self.mpcr * C.N_VOTERS, 2) self.opp_announced_distribution = round(val, 2) def collect_leader_decisions(self): leader = self.get_leader() if leader is None: self.revenue_gap = 0 self.gap_to_treasury = 0 self.leader_private_gap = 0 self.excess_to_treasury = 0 self.leader_private_excess = 0 return actual_revenue = round(C.THRESHOLD * self.mpcr * C.N_VOTERS, 2) self.revenue_gap = round(actual_revenue - self.announced_distribution, 2) positive_gap = max(0.0, self.revenue_gap) gap_input = leader.field_maybe_none('gap_to_treasury_input') if gap_input is None: gap_input = 0 self.gap_to_treasury = round(min(max(gap_input, 0), positive_gap), 2) self.leader_private_gap = round(positive_gap - self.gap_to_treasury, 2) excess_input = leader.field_maybe_none('excess_to_treasury_input') if excess_input is None: excess_input = 0 self.excess_to_treasury = round(min(max(excess_input, 0), self.excess_contribution), 2) self.leader_private_excess = round(self.excess_contribution - self.excess_to_treasury, 2) def calculate_payoffs(self): voters = self.get_voters() leader = self.get_leader() opposition = self.get_opposition() if self.threshold_met: self.actual_project_revenue = round(C.THRESHOLD * self.mpcr * C.N_VOTERS, 2) else: self.actual_project_revenue = 0 if not self.threshold_met: self.revenue_gap = 0 self.gap_to_treasury = 0 self.leader_private_gap = 0 self.excess_to_treasury = 0 self.leader_private_excess = 0 if self.threshold_met: shortfall = max(0, round(self.announced_distribution - self.actual_project_revenue, 2)) self.treasury_pre_tax = round( self.treasury_start - shortfall + self.gap_to_treasury + self.excess_to_treasury, 2 ) else: self.treasury_pre_tax = round(self.treasury_start, 2) if self.treasury_pre_tax < 0: self.tax_per_voter = round((-self.treasury_pre_tax) / C.N_VOTERS, 2) self.treasury_end = 0 self.deficit_used_this_term = True else: self.tax_per_voter = 0 self.treasury_end = round(self.treasury_pre_tax, 2) for p in voters: if self.threshold_met: pre_tax = round( C.ENDOWMENT - p.contribution + self.announced_distribution / C.N_VOTERS, 2 ) else: pre_tax = round( C.ENDOWMENT - p.contribution + C.REFUND_RATE_FAIL * p.contribution, 2 ) belief_val = p.field_maybe_none('belief') if belief_val is not None and abs(belief_val - self.actual_project_revenue) <= C.BELIEF_TOLERANCE_REVENUE: pre_tax += C.BELIEF_BONUS p.belief_correct = True else: p.belief_correct = False p.payoff_pre_tax = round(pre_tax, 2) p.tax_paid = round(self.tax_per_voter, 2) p.payoff_this_round = round(pre_tax - self.tax_per_voter, 2) p.payoff = cu(p.payoff_this_round) if leader: if self.threshold_met: leader_income = C.LEADER_SALARY + self.leader_private_gap + self.leader_private_excess else: leader_income = C.LEADER_SALARY leader.payoff_this_round = round(leader_income, 2) leader.payoff = cu(leader.payoff_this_round) if opposition: opposition.payoff_this_round = round(C.OPP_SALARY, 2) opposition.payoff = cu(opposition.payoff_this_round) def conduct_election(self): self.election_held = True voters = self.get_voters() self.votes_incumbent = sum(1 for v in voters if v.vote == 'incumbent') self.votes_opposition = sum(1 for v in voters if v.vote == 'opposition') if self.votes_opposition > self.votes_incumbent: self.election_winner = 'opposition' leader_participant = None opposition_participant = None for p in self.get_players(): if current_role(p) == C.ROLE_LEADER: leader_participant = p.participant elif current_role(p) == C.ROLE_OPPOSITION: opposition_participant = p.participant if leader_participant and opposition_participant: leader_participant.vars['role'] = C.ROLE_OPPOSITION opposition_participant.vars['role'] = C.ROLE_LEADER for future_p in leader_participant.get_players(): if future_p.round_number >= self.round_number: future_p.role_in_game = C.ROLE_OPPOSITION for future_p in opposition_participant.get_players(): if future_p.round_number >= self.round_number: future_p.role_in_game = C.ROLE_LEADER else: self.election_winner = 'incumbent' class Player(BasePlayer): role_in_game = models.StringField() # ── Pre-game candidacy & election ──────────────────────────────── wants_candidate = models.BooleanField( choices=[[True, 'Evet, lider adayı olmak istiyorum'], [False, 'Hayır, aday olmak istemiyorum']], widget=widgets.RadioSelect, label='Lider adayı olmak ister misiniz?', blank=True, ) is_candidate = models.BooleanField(initial=False) pre_game_vote = models.StringField( choices=['Aday 1', 'Aday 2'], # placeholder — sayfada dinamik olarak ezilecek widget=widgets.RadioSelect, blank=True, ) announced_distribution_input = models.FloatField( min=0, label='Proje başarılı olursa 5 seçmene toplam kaç ECU dağıtılacak?', blank=True, ) opp_announced_distribution_input = models.FloatField( min=0, label='Proje başarılı olursa 5 seçmene toplam kaç ECU dağıtılacak?', blank=True, ) gap_to_treasury_input = models.FloatField( min=0, label='Duyurulan ödeme sonrası kalan kamu geliri fazlasının kaç ECU’sunu hazineye aktarıyorsunuz?', blank=True, ) excess_to_treasury_input = models.FloatField( min=0, label='Aşım katkının kaç ECU’sunu hazineye aktarıyorsunuz?', blank=True, ) contribution = models.FloatField( min=0, max=C.ENDOWMENT, initial=0, label='Kamu projesine katkı miktarınızı giriniz (0 – 20 ECU):', ) belief = models.FloatField( min=0, label='Bu turdaki gerçek proje geliri sizce kaç ECU?', blank=True, ) belief_correct = models.BooleanField(initial=False) vote = models.StringField( choices=[['incumbent', 'Mevcut Lider'], ['opposition', 'Muhalefet Lideri']], widget=widgets.RadioSelect, label='Bir sonraki dönem için kimi destekliyorsunuz?', blank=True, ) payoff_pre_tax = models.FloatField(initial=0) tax_paid = models.FloatField(initial=0) payoff_this_round = models.FloatField(initial=0) class Instructions(Page): @staticmethod def is_displayed(player: Player): return player.round_number == 1 @staticmethod def vars_for_template(player: Player): election_rounds_text = ' ve '.join(str(r) for r in C.ELECTION_ROUNDS) refund_loss_percent = int(round((1 - C.REFUND_RATE_FAIL) * 100)) return dict( role=current_role(player), treatment=player.session.config.get('treatment', 'T2'), endowment=C.ENDOWMENT, threshold=C.THRESHOLD, mpcr_min=C.MPCR_MIN, mpcr_max=C.MPCR_MAX, refund_rate=int(C.REFUND_RATE_FAIL * 100), refund_loss_percent=refund_loss_percent, belief_bonus=C.BELIEF_BONUS, belief_tolerance_revenue=C.BELIEF_TOLERANCE_REVENUE, leader_salary=C.LEADER_SALARY, opp_salary=C.OPP_SALARY, initial_treasury=C.INITIAL_TREASURY, treasury_floor=C.TREASURY_FLOOR, election_rounds=C.ELECTION_ROUNDS, election_rounds_text=election_rounds_text, guaranteed_rounds=C.GUARANTEED_ROUNDS, num_rounds=C.NUM_ROUNDS, ) # ── Pre-game candidacy & election (round 1 only) ───────────────────── class CandidacyPage(Page): form_model = 'player' form_fields = ['wants_candidate'] @staticmethod def is_displayed(player: Player): return player.round_number == 1 @staticmethod def vars_for_template(player: Player): return dict( treatment=player.session.config.get('treatment', 'T2'), ) @staticmethod def before_next_page(player: Player, timeout_happened): if player.field_maybe_none('wants_candidate') is None: player.wants_candidate = False class SelectCandidatesWaitPage(WaitPage): title_text = 'Adaylar belirleniyor…' body_text = 'Lütfen bekleyin.' @staticmethod def is_displayed(player: Player): return player.round_number == 1 @staticmethod def after_all_players_arrive(group: Group): group.select_candidates() class PreGameElectionPage(Page): form_model = 'player' form_fields = ['pre_game_vote'] @staticmethod def is_displayed(player: Player): return player.round_number == 1 and not player.is_candidate @staticmethod def pre_game_vote_choices(player: Player): g = player.group return [ [str(g.candidate1_id), 'Aday 1'], [str(g.candidate2_id), 'Aday 2'], ] # pre_game_vote_widget METODU YOK — desteklenmiyor @staticmethod def vars_for_template(player: Player): g = player.group return dict( candidate1_id=g.candidate1_id, candidate2_id=g.candidate2_id, ) @staticmethod def before_next_page(player: Player, timeout_happened): if player.field_maybe_none('pre_game_vote') is None: player.pre_game_vote = str(player.group.candidate1_id) class PreGameElectionWaitPage(WaitPage): title_text = 'Seçim sonucu hesaplanıyor…' body_text = 'Lütfen bekleyin.' @staticmethod def is_displayed(player: Player): return player.round_number == 1 @staticmethod def after_all_players_arrive(group: Group): group.conduct_pregame_election() # Defensive role sync after election for p in group.get_players(): role = p.participant.vars.get('role', C.ROLE_VOTER) p.role_in_game = role for fp in p.participant.get_players(): fp.role_in_game = role class PreGameResultPage(Page): @staticmethod def is_displayed(player: Player): return player.round_number == 1 @staticmethod def vars_for_template(player: Player): g = player.group return dict( candidate1_id=g.candidate1_id, candidate2_id=g.candidate2_id, votes_c1=g.pregame_votes_c1, votes_c2=g.pregame_votes_c2, winner_id=g.pregame_winner_id, loser_id=g.pregame_loser_id, my_id=player.id_in_group, my_role=current_role(player), was_candidate=player.is_candidate, n_volunteers=g.n_volunteers, ) class StartRoundWaitPage(WaitPage): title_text = 'Tur başlıyor…' body_text = 'Lütfen diğer oyuncuların hazır olmasını bekleyin.' @staticmethod def is_displayed(player: Player): return game_active(player) @staticmethod def after_all_players_arrive(group: Group): group.draw_mpcr() group.initialize_round_state() class LeaderInfoPage(Page): @staticmethod def is_displayed(player: Player): return game_active(player) and current_role(player) == C.ROLE_LEADER @staticmethod def vars_for_template(player: Player): g = player.group return dict( role=current_role(player), mpcr=round(g.mpcr, 2), round_number=player.round_number, treasury_start=round(g.treasury_start, 2), deficit_used=g.deficit_used_this_term, actual_revenue=round(C.THRESHOLD * g.mpcr * C.N_VOTERS, 2), max_announcement=g.max_allowed_announcement(), threshold=C.THRESHOLD, treasury_floor=C.TREASURY_FLOOR, leader_salary=C.LEADER_SALARY, ) class LeaderAnnouncementPage(Page): form_model = 'player' form_fields = ['announced_distribution_input'] @staticmethod def is_displayed(player: Player): return game_active(player) and current_role(player) == C.ROLE_LEADER @staticmethod def error_message(player: Player, values): a = values.get('announced_distribution_input') or 0 max_a = player.group.max_allowed_announcement() if a > max_a: return f'Bu tur için maksimum duyuru miktarı {max_a} ECU’dur.' @staticmethod def vars_for_template(player: Player): g = player.group return dict( mpcr=round(g.mpcr, 2), round_number=player.round_number, treasury_start=round(g.treasury_start, 2), actual_revenue=round(C.THRESHOLD * g.mpcr * C.N_VOTERS, 2), max_announcement=g.max_allowed_announcement(), deficit_used=g.deficit_used_this_term, leader_salary=C.LEADER_SALARY, threshold=C.THRESHOLD, ) @staticmethod def before_next_page(player: Player, timeout_happened): if timeout_happened or player.field_maybe_none('announced_distribution_input') is None: player.announced_distribution_input = round( C.THRESHOLD * player.group.mpcr * C.N_VOTERS, 2 ) player.group.announced_distribution = round( player.announced_distribution_input, 2 ) class CollectAnnouncementWaitPage(WaitPage): title_text = 'Liderin duyurusu bekleniyor…' body_text = 'Lütfen bekleyin.' @staticmethod def is_displayed(player: Player): return game_active(player) @staticmethod def after_all_players_arrive(group: Group): # Fallback only. Main saving happens in LeaderAnnouncementPage.before_next_page. leader = group.get_leader() if leader: a = leader.field_maybe_none('announced_distribution_input') if a is not None: group.announced_distribution = round(a, 2) class OppositionAnnouncementPage(Page): form_model = 'player' form_fields = ['opp_announced_distribution_input'] @staticmethod def is_displayed(player: Player): return ( game_active(player) and current_role(player) == C.ROLE_OPPOSITION and player.session.config.get('treatment', 'T2') == 'T2' ) @staticmethod def vars_for_template(player: Player): g = player.group actual_revenue = round(C.THRESHOLD * g.mpcr * C.N_VOTERS, 2) leader_announcement = round(g.announced_distribution, 2) return dict( mpcr=round(g.mpcr, 2), actual_revenue=actual_revenue, round_number=player.round_number, treasury_start=round(g.treasury_start, 2), threshold=C.THRESHOLD, leader_announcement=leader_announcement, leader_announcement_per_voter=round(leader_announcement / C.N_VOTERS, 2), leader_gap=round(actual_revenue - leader_announcement, 2), ) @staticmethod def before_next_page(player: Player, timeout_happened): if timeout_happened or player.field_maybe_none('opp_announced_distribution_input') is None: player.opp_announced_distribution_input = round( C.THRESHOLD * player.group.mpcr * C.N_VOTERS, 2 ) player.group.opp_announced_distribution = round( player.opp_announced_distribution_input, 2 ) class CollectOppositionAnnouncementWaitPage(WaitPage): title_text = 'Muhalefetin duyurusu bekleniyor…' body_text = 'Lütfen bekleyin.' @staticmethod def is_displayed(player: Player): return ( game_active(player) and player.session.config.get('treatment', 'T2') == 'T2' ) @staticmethod def after_all_players_arrive(group: Group): # Fallback only. Main saving happens in OppositionAnnouncementPage.before_next_page. group.collect_opposition_decision() class BeliefElicitationPage(Page): form_model = 'player' form_fields = ['belief'] @staticmethod def is_displayed(player: Player): return game_active(player) and current_role(player) == C.ROLE_VOTER @staticmethod def vars_for_template(player: Player): g = player.group treatment = player.session.config.get('treatment', 'T2') show_opp = (treatment == 'T2' and g.opp_announced_distribution != 0) return dict( announced_distribution=round(g.announced_distribution, 2), announced_per_voter=round(g.announced_distribution / C.N_VOTERS, 2), opp_announced_distribution=round(g.opp_announced_distribution, 2), opp_per_voter=round(g.opp_announced_distribution / C.N_VOTERS, 2), show_opposition=show_opp, treasury_start=round(g.treasury_start, 2), threshold=C.THRESHOLD, belief_bonus=C.BELIEF_BONUS, belief_tolerance_revenue=C.BELIEF_TOLERANCE_REVENUE, round_number=player.round_number, num_rounds=C.NUM_ROUNDS, ) class ContributionPage(Page): form_model = 'player' form_fields = ['contribution'] @staticmethod def is_displayed(player: Player): return game_active(player) and current_role(player) == C.ROLE_VOTER @staticmethod def vars_for_template(player: Player): g = player.group treatment = player.session.config.get('treatment', 'T2') show_opp = (treatment == 'T2' and g.opp_announced_distribution != 0) return dict( endowment=C.ENDOWMENT, threshold=C.THRESHOLD, announced_distribution=round(g.announced_distribution, 2), announced_per_voter=round(g.announced_distribution / C.N_VOTERS, 2), opp_announced_distribution=round(g.opp_announced_distribution, 2), opp_per_voter=round(g.opp_announced_distribution / C.N_VOTERS, 2), show_opposition=show_opp, refund_rate=int(C.REFUND_RATE_FAIL * 100), round_number=player.round_number, num_rounds=C.NUM_ROUNDS, ) class CheckContributionWaitPage(WaitPage): title_text = 'Katkılar toplanıyor…' body_text = 'Lütfen bekleyin.' @staticmethod def is_displayed(player: Player): return game_active(player) @staticmethod def after_all_players_arrive(group: Group): group.check_threshold() class LeaderAllocationPage(Page): form_model = 'player' form_fields = ['gap_to_treasury_input', 'excess_to_treasury_input'] @staticmethod def is_displayed(player: Player): if not game_active(player): return False if current_role(player) != C.ROLE_LEADER: return False if not player.group.threshold_met: return False actual_revenue = round(C.THRESHOLD * player.group.mpcr * C.N_VOTERS, 2) positive_gap = max(0, round(actual_revenue - player.group.announced_distribution, 2)) excess = player.group.excess_contribution return positive_gap > 0 or excess > 0 @staticmethod def error_message(player: Player, values): actual_revenue = round(C.THRESHOLD * player.group.mpcr * C.N_VOTERS, 2) positive_gap = max(0, round(actual_revenue - player.group.announced_distribution, 2)) excess = player.group.excess_contribution gap_val = values.get('gap_to_treasury_input') or 0 excess_val = values.get('excess_to_treasury_input') or 0 if gap_val < 0 or gap_val > positive_gap: return f'Gelir farkından hazineye aktarılacak miktar 0 ile {positive_gap} arasında olmalıdır.' if excess_val < 0 or excess_val > excess: return f'Aşım katkıdan hazineye aktarılacak miktar 0 ile {excess} arasında olmalıdır.' @staticmethod def vars_for_template(player: Player): g = player.group actual_revenue = round(C.THRESHOLD * g.mpcr * C.N_VOTERS, 2) positive_gap = max(0, round(actual_revenue - g.announced_distribution, 2)) return dict( threshold=C.THRESHOLD, n_voters=C.N_VOTERS, mpcr=round(g.mpcr, 2), actual_revenue=actual_revenue, announced_distribution=round(g.announced_distribution, 2), announced_per_voter=round(g.announced_distribution / C.N_VOTERS, 2), positive_gap=positive_gap, excess_contribution=round(g.excess_contribution, 2), treasury_start=round(g.treasury_start, 2), ) @staticmethod def before_next_page(player: Player, timeout_happened): if timeout_happened or player.field_maybe_none('gap_to_treasury_input') is None: player.gap_to_treasury_input = 0 if timeout_happened or player.field_maybe_none('excess_to_treasury_input') is None: player.excess_to_treasury_input = 0 class CalculatePayoffsWaitPage(WaitPage): title_text = 'Sonuçlar hesaplanıyor…' body_text = 'Diğer oyuncular bekleniyor.' @staticmethod def is_displayed(player: Player): return game_active(player) @staticmethod def after_all_players_arrive(group: Group): group.collect_leader_decisions() group.calculate_payoffs() class RoundResultsPage(Page): @staticmethod def is_displayed(player: Player): return game_active(player) @staticmethod def vars_for_template(player: Player): g = player.group treatment = player.session.config.get('treatment', 'T2') show_opp = (treatment == 'T2' and g.opp_announced_distribution != 0) total_so_far = round(float(sum(p.payoff for p in player.in_all_rounds())), 2) actual_rev = round(g.actual_project_revenue, 2) announced = round(g.announced_distribution, 2) announce_diff = round(announced - actual_rev, 2) positive_gap = round(max(0, actual_rev - announced), 2) opp_lie = round(g.opp_announced_distribution - actual_rev, 2) if treatment == 'T2' else 0 voter_contribution_raw = float(player.field_maybe_none('contribution') or 0) voter_contribution_2dp = f"{voter_contribution_raw:.2f}" refund_loss_amount = round((1 - C.REFUND_RATE_FAIL) * voter_contribution_raw, 2) refund_loss_amount_2dp = f"{refund_loss_amount:.2f}" leader_obj = g.get_leader() debug_gap_input = leader_obj.field_maybe_none('gap_to_treasury_input') if leader_obj else None return dict( role=current_role(player), mpcr=round(g.mpcr, 2), actual_project_revenue=actual_rev, announced_distribution=announced, announced_per_voter=round(announced / C.N_VOTERS, 2), opp_announced_distribution=round(g.opp_announced_distribution, 2), opp_per_voter=round(g.opp_announced_distribution / C.N_VOTERS, 2), opp_lie=opp_lie, show_opposition=show_opp, announce_diff=announce_diff, positive_gap=positive_gap, leader_overannounced=(announce_diff > 0), leader_underannounced=(announce_diff < 0), leader_truthful=(announce_diff == 0), total_contribution=round(g.total_contribution, 2), threshold=C.THRESHOLD, threshold_met=g.threshold_met, excess_contribution=round(g.excess_contribution, 2), gap_to_treasury=round(g.gap_to_treasury, 2), leader_private_gap=round(g.leader_private_gap, 2), excess_to_treasury=round(g.excess_to_treasury, 2), leader_private_excess=round(g.leader_private_excess, 2), leader_total_private_take=round(g.leader_private_gap + g.leader_private_excess, 2), treasury_start=round(g.treasury_start, 2), treasury_pre_tax=round(g.treasury_pre_tax, 2), tax_per_voter=round(g.tax_per_voter, 2), treasury_end=round(g.treasury_end, 2), deficit_used=g.deficit_used_this_term, payoff_this_round=round(float(player.payoff_this_round), 2), payoff_pre_tax=round(float(player.payoff_pre_tax), 2) if current_role(player) == C.ROLE_VOTER else None, tax_paid=round(float(player.tax_paid), 2) if current_role(player) == C.ROLE_VOTER else None, voter_contribution=voter_contribution_raw, voter_contribution_2dp=voter_contribution_2dp, refund_loss_amount=refund_loss_amount, refund_loss_amount_2dp=refund_loss_amount_2dp, belief=round(float(player.field_maybe_none('belief') or 0), 2), belief_correct=player.belief_correct if current_role(player) == C.ROLE_VOTER else False, belief_bonus=C.BELIEF_BONUS, total_so_far=total_so_far, endowment=C.ENDOWMENT, leader_salary=C.LEADER_SALARY, opp_salary=C.OPP_SALARY, is_election_round=election_active(player), round_number=player.round_number, num_rounds=C.NUM_ROUNDS, debug_gap_input=debug_gap_input, debug_revenue_gap=round(g.revenue_gap, 2), debug_gap_to_treasury=round(g.gap_to_treasury, 2), debug_leader_private_gap=round(g.leader_private_gap, 2), ) class ElectionPage(Page): form_model = 'player' form_fields = ['vote'] @staticmethod def is_displayed(player: Player): return current_role(player) == C.ROLE_VOTER and election_active(player) @staticmethod def vars_for_template(player: Player): history = [] treatment = player.session.config.get('treatment', 'T2') for r in range(max(1, player.round_number - 3), player.round_number + 1): g = player.group.in_round(r) diff = round(g.announced_distribution - g.actual_project_revenue, 2) opp_diff = round(g.opp_announced_distribution - g.actual_project_revenue, 2) history.append(dict( round=r, mpcr=round(g.mpcr, 2), actual_revenue=round(g.actual_project_revenue, 2), announced=round(g.announced_distribution, 2), opp_announced=round(g.opp_announced_distribution, 2), diff=diff, overannounced=(diff > 0), underannounced=(diff < 0), truthful=(diff == 0), opp_diff=opp_diff, opp_overannounced=(opp_diff > 0), opp_underannounced=(opp_diff < 0), opp_truthful=(opp_diff == 0), threshold_met=g.threshold_met, treasury_end=round(g.treasury_end, 2), tax_per_voter=round(g.tax_per_voter, 2), )) return dict( round_number=player.round_number, history=history, treatment=treatment, ) @staticmethod def before_next_page(player: Player, timeout_happened): if timeout_happened or player.field_maybe_none('vote') is None: player.vote = 'incumbent' class ElectionWaitPage(WaitPage): title_text = 'Seçim sonuçları bekleniyor…' body_text = 'Lütfen bekleyin.' @staticmethod def is_displayed(player: Player): return election_active(player) @staticmethod def after_all_players_arrive(group: Group): group.conduct_election() class ElectionResultsPage(Page): @staticmethod def is_displayed(player: Player): return election_active(player) @staticmethod def vars_for_template(player: Player): g = player.group total_votes = g.votes_incumbent + g.votes_opposition if player.round_number > 1: old_role = player.in_round(player.round_number - 1).role_in_game else: old_role = player.role_in_game new_role = player.participant.vars.get('role', player.role_in_game) return dict( role=old_role, old_role=old_role, new_role=new_role, votes_incumbent=g.votes_incumbent, votes_opposition=g.votes_opposition, election_winner=g.election_winner, role_changed=(old_role != new_role), round_number=player.round_number, pct_incumbent=round(g.votes_incumbent / max(total_votes, 1) * 100), pct_opposition=round(g.votes_opposition / max(total_votes, 1) * 100), treasury_end=round(g.treasury_end, 2), ) class FinalResultsPage(Page): @staticmethod def is_displayed(player: Player): # Show on the REALISED last round (3, 4 or 5) return is_last_round(player) @staticmethod def vars_for_template(player: Player): total_ecus = round(float(sum(p.payoff for p in player.in_all_rounds())), 2) return dict( total_ecus=total_ecus, real_money=round(total_ecus * player.session.config['real_world_currency_per_point'], 2), role=current_role(player), final_treasury=round(player.group.treasury_end, 2), rounds_played=player.round_number, ) page_sequence = [ # ── Pre-game election (round 1 only) ── CandidacyPage, SelectCandidatesWaitPage, PreGameElectionPage, PreGameElectionWaitPage, PreGameResultPage, Instructions, # ── Normal round flow ── StartRoundWaitPage, LeaderInfoPage, LeaderAnnouncementPage, CollectAnnouncementWaitPage, OppositionAnnouncementPage, CollectOppositionAnnouncementWaitPage, BeliefElicitationPage, ContributionPage, CheckContributionWaitPage, LeaderAllocationPage, CalculatePayoffsWaitPage, RoundResultsPage, ElectionPage, ElectionWaitPage, ElectionResultsPage, FinalResultsPage, ]