from otree.api import * import random import math doc = """ Siyasal Kamu Malı Deneyi — Hazine Versiyonu (Rastgele Dönem Ufku) ================================================================= Threshold Public Goods Game with Treasury, Political Competition, Strategic Information Distortion, pre-election diagnostic tests, and a RANDOM PERIOD HORIZON. Structure: • Each political period/term consists of 4 rounds. • Periods 1–3 are always played: 12 guaranteed rounds. • Period 4 is played with probability 0.50. • Period 5 is played with probability 0.25, conditional on reaching period 4. • The game ends for certain after period 5. • Maximum length: 20 rounds. Pre-game block: • All participants complete SVO, Short Dark Triad, and CRT tasks. • Participants then decide whether to be a leader candidate. • Voters choose between two candidates after seeing candidates' test reports. """ 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] # ── Pre-election diagnostic tests ─────────────────────────────── # These tests are diagnostic only. They are not separately paid here. USE_DARK_TRIAD = True # SVO Slider Measure: 6 primary matrices. # Each tuple is (allocation_for_self, allocation_for_other). SVO_MATRICES = [ [(85, 85), (85, 76), (85, 68), (85, 59), (85, 50), (85, 41), (85, 33), (85, 24), (85, 15)], [(85, 15), (87, 19), (89, 24), (91, 28), (93, 33), (94, 37), (96, 41), (98, 46), (100, 50)], [(50, 100), (54, 98), (59, 96), (63, 94), (68, 93), (72, 91), (76, 89), (81, 87), (85, 85)], [(50, 100), (54, 89), (59, 79), (63, 68), (68, 58), (72, 47), (76, 36), (81, 26), (85, 15)], [(100, 50), (94, 56), (88, 63), (81, 69), (75, 75), (69, 81), (63, 88), (56, 94), (50, 100)], [(100, 50), (98, 54), (96, 59), (94, 63), (93, 68), (91, 72), (89, 76), (87, 81), (85, 85)], ] # Short Dark Triad (SD3): 27 items; 1–9 Machiavellianism, # 10–18 Narcissism, 19–27 Psychopathy. SD3_QUESTIONS = [ {"id": 1, "text": "It's not wise to tell your secrets.", "rev": False}, {"id": 2, "text": "I like to use clever manipulation to get my way.", "rev": False}, {"id": 3, "text": "Whatever it takes, you must get the important people on your side.", "rev": False}, {"id": 4, "text": "Avoid direct conflict with others because they may be useful in the future.", "rev": False}, {"id": 5, "text": "It is wise to keep track of information that you can use against people later.", "rev": False}, {"id": 6, "text": "You should wait for the right time to get back at people.", "rev": False}, {"id": 7, "text": "There are things you should hide from other people to preserve your reputation.", "rev": False}, {"id": 8, "text": "Make sure your plans benefit yourself, not others.", "rev": False}, {"id": 9, "text": "Most people can be manipulated.", "rev": False}, {"id": 10, "text": "People see me as a natural leader.", "rev": False}, {"id": 11, "text": "I hate being the center of attention.", "rev": True}, {"id": 12, "text": "Many group activities tend to be dull without me.", "rev": False}, {"id": 13, "text": "I know that I am special because everyone keeps telling me so.", "rev": False}, {"id": 14, "text": "I like to get acquainted with important people.", "rev": False}, {"id": 15, "text": "I feel embarrassed if someone compliments me.", "rev": True}, {"id": 16, "text": "I have been compared to famous people.", "rev": False}, {"id": 17, "text": "I am an average person.", "rev": True}, {"id": 18, "text": "I insist on getting the respect I deserve.", "rev": False}, {"id": 19, "text": "I like to get revenge on authorities.", "rev": False}, {"id": 20, "text": "I avoid dangerous situations.", "rev": True}, {"id": 21, "text": "Payback needs to be quick and nasty.", "rev": False}, {"id": 22, "text": "People often say I am out of control.", "rev": False}, {"id": 23, "text": "It is true that I can be mean to others.", "rev": False}, {"id": 24, "text": "People who mess with me always regret it.", "rev": False}, {"id": 25, "text": "I have never gotten into trouble with the law.", "rev": True}, {"id": 26, "text": "I enjoy having sex with people I hardly know.", "rev": False}, {"id": 27, "text": "I will say anything to get what I want.", "rev": False}, ] NUM_SD3_QUESTIONS = len(SD3_QUESTIONS) # CRT-3. Answers are scored internally and shown as a 0–3 score. CRT_QUESTIONS = [ { "id": 1, "text": "A bat and a ball cost 1.10 TL in total. The bat costs 1.00 TL more than the ball. How much does the ball cost?", "correct_numbers": [0.05], }, { "id": 2, "text": "If 5 machines take 5 minutes to make 5 widgets, how many minutes would 100 machines take to make 100 widgets?", "correct_numbers": [5], }, { "id": 3, "text": "In a lake, lily pads double in size every day. If they cover the whole lake in 48 days, on which day do they cover half the lake?", "correct_numbers": [47], }, ] NUM_CRT_QUESTIONS = len(CRT_QUESTIONS) # 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 # Roles ROLE_LEADER = 'leader' ROLE_OPPOSITION = 'opposition' ROLE_VOTER = 'voter' LEADER_ID = 1 OPPOSITION_ID = 2 # Dict lookup is module-level because oTree constants are read-only after class creation. SD3_QUESTIONS_DICT = {q['id']: q for q in C.SD3_QUESTIONS} 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 common_template_vars(player: 'Player'): # Do not expose C.NUM_ROUNDS, final_round, or final_period here. # Participants should see the current round/period, not the maximum or realised horizon. return dict( round_number=player.round_number, period_number=get_current_period(player), round_in_period=get_round_in_period(player), period_length=C.PERIOD_LENGTH, ) 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-election diagnostic test scores ───────────────────────── # SVO hidden-choice fields; values are filled by SVOPage.html. svo_choice_1_self = models.IntegerField(blank=True) svo_choice_1_other = models.IntegerField(blank=True) svo_choice_2_self = models.IntegerField(blank=True) svo_choice_2_other = models.IntegerField(blank=True) svo_choice_3_self = models.IntegerField(blank=True) svo_choice_3_other = models.IntegerField(blank=True) svo_choice_4_self = models.IntegerField(blank=True) svo_choice_4_other = models.IntegerField(blank=True) svo_choice_5_self = models.IntegerField(blank=True) svo_choice_5_other = models.IntegerField(blank=True) svo_choice_6_self = models.IntegerField(blank=True) svo_choice_6_other = models.IntegerField(blank=True) svo_mean_self = models.FloatField(blank=True) svo_mean_other = models.FloatField(blank=True) svo_angle = models.FloatField(blank=True) svo_type = models.StringField(blank=True) sd3_mach = models.FloatField(blank=True) sd3_narc = models.FloatField(blank=True) sd3_psych = models.FloatField(blank=True) crt_score = models.IntegerField(initial=0) sd3_1 = models.IntegerField( choices=[[1, '1'], [2, '2'], [3, '3'], [4, '4'], [5, '5']], widget=widgets.RadioSelectHorizontal, label=C.SD3_QUESTIONS[0]['text'], blank=True, ) sd3_2 = models.IntegerField( choices=[[1, '1'], [2, '2'], [3, '3'], [4, '4'], [5, '5']], widget=widgets.RadioSelectHorizontal, label=C.SD3_QUESTIONS[1]['text'], blank=True, ) sd3_3 = models.IntegerField( choices=[[1, '1'], [2, '2'], [3, '3'], [4, '4'], [5, '5']], widget=widgets.RadioSelectHorizontal, label=C.SD3_QUESTIONS[2]['text'], blank=True, ) sd3_4 = models.IntegerField( choices=[[1, '1'], [2, '2'], [3, '3'], [4, '4'], [5, '5']], widget=widgets.RadioSelectHorizontal, label=C.SD3_QUESTIONS[3]['text'], blank=True, ) sd3_5 = models.IntegerField( choices=[[1, '1'], [2, '2'], [3, '3'], [4, '4'], [5, '5']], widget=widgets.RadioSelectHorizontal, label=C.SD3_QUESTIONS[4]['text'], blank=True, ) sd3_6 = models.IntegerField( choices=[[1, '1'], [2, '2'], [3, '3'], [4, '4'], [5, '5']], widget=widgets.RadioSelectHorizontal, label=C.SD3_QUESTIONS[5]['text'], blank=True, ) sd3_7 = models.IntegerField( choices=[[1, '1'], [2, '2'], [3, '3'], [4, '4'], [5, '5']], widget=widgets.RadioSelectHorizontal, label=C.SD3_QUESTIONS[6]['text'], blank=True, ) sd3_8 = models.IntegerField( choices=[[1, '1'], [2, '2'], [3, '3'], [4, '4'], [5, '5']], widget=widgets.RadioSelectHorizontal, label=C.SD3_QUESTIONS[7]['text'], blank=True, ) sd3_9 = models.IntegerField( choices=[[1, '1'], [2, '2'], [3, '3'], [4, '4'], [5, '5']], widget=widgets.RadioSelectHorizontal, label=C.SD3_QUESTIONS[8]['text'], blank=True, ) sd3_10 = models.IntegerField( choices=[[1, '1'], [2, '2'], [3, '3'], [4, '4'], [5, '5']], widget=widgets.RadioSelectHorizontal, label=C.SD3_QUESTIONS[9]['text'], blank=True, ) sd3_11 = models.IntegerField( choices=[[1, '1'], [2, '2'], [3, '3'], [4, '4'], [5, '5']], widget=widgets.RadioSelectHorizontal, label=C.SD3_QUESTIONS[10]['text'], blank=True, ) sd3_12 = models.IntegerField( choices=[[1, '1'], [2, '2'], [3, '3'], [4, '4'], [5, '5']], widget=widgets.RadioSelectHorizontal, label=C.SD3_QUESTIONS[11]['text'], blank=True, ) sd3_13 = models.IntegerField( choices=[[1, '1'], [2, '2'], [3, '3'], [4, '4'], [5, '5']], widget=widgets.RadioSelectHorizontal, label=C.SD3_QUESTIONS[12]['text'], blank=True, ) sd3_14 = models.IntegerField( choices=[[1, '1'], [2, '2'], [3, '3'], [4, '4'], [5, '5']], widget=widgets.RadioSelectHorizontal, label=C.SD3_QUESTIONS[13]['text'], blank=True, ) sd3_15 = models.IntegerField( choices=[[1, '1'], [2, '2'], [3, '3'], [4, '4'], [5, '5']], widget=widgets.RadioSelectHorizontal, label=C.SD3_QUESTIONS[14]['text'], blank=True, ) sd3_16 = models.IntegerField( choices=[[1, '1'], [2, '2'], [3, '3'], [4, '4'], [5, '5']], widget=widgets.RadioSelectHorizontal, label=C.SD3_QUESTIONS[15]['text'], blank=True, ) sd3_17 = models.IntegerField( choices=[[1, '1'], [2, '2'], [3, '3'], [4, '4'], [5, '5']], widget=widgets.RadioSelectHorizontal, label=C.SD3_QUESTIONS[16]['text'], blank=True, ) sd3_18 = models.IntegerField( choices=[[1, '1'], [2, '2'], [3, '3'], [4, '4'], [5, '5']], widget=widgets.RadioSelectHorizontal, label=C.SD3_QUESTIONS[17]['text'], blank=True, ) sd3_19 = models.IntegerField( choices=[[1, '1'], [2, '2'], [3, '3'], [4, '4'], [5, '5']], widget=widgets.RadioSelectHorizontal, label=C.SD3_QUESTIONS[18]['text'], blank=True, ) sd3_20 = models.IntegerField( choices=[[1, '1'], [2, '2'], [3, '3'], [4, '4'], [5, '5']], widget=widgets.RadioSelectHorizontal, label=C.SD3_QUESTIONS[19]['text'], blank=True, ) sd3_21 = models.IntegerField( choices=[[1, '1'], [2, '2'], [3, '3'], [4, '4'], [5, '5']], widget=widgets.RadioSelectHorizontal, label=C.SD3_QUESTIONS[20]['text'], blank=True, ) sd3_22 = models.IntegerField( choices=[[1, '1'], [2, '2'], [3, '3'], [4, '4'], [5, '5']], widget=widgets.RadioSelectHorizontal, label=C.SD3_QUESTIONS[21]['text'], blank=True, ) sd3_23 = models.IntegerField( choices=[[1, '1'], [2, '2'], [3, '3'], [4, '4'], [5, '5']], widget=widgets.RadioSelectHorizontal, label=C.SD3_QUESTIONS[22]['text'], blank=True, ) sd3_24 = models.IntegerField( choices=[[1, '1'], [2, '2'], [3, '3'], [4, '4'], [5, '5']], widget=widgets.RadioSelectHorizontal, label=C.SD3_QUESTIONS[23]['text'], blank=True, ) sd3_25 = models.IntegerField( choices=[[1, '1'], [2, '2'], [3, '3'], [4, '4'], [5, '5']], widget=widgets.RadioSelectHorizontal, label=C.SD3_QUESTIONS[24]['text'], blank=True, ) sd3_26 = models.IntegerField( choices=[[1, '1'], [2, '2'], [3, '3'], [4, '4'], [5, '5']], widget=widgets.RadioSelectHorizontal, label=C.SD3_QUESTIONS[25]['text'], blank=True, ) sd3_27 = models.IntegerField( choices=[[1, '1'], [2, '2'], [3, '3'], [4, '4'], [5, '5']], widget=widgets.RadioSelectHorizontal, label=C.SD3_QUESTIONS[26]['text'], blank=True, ) crt_1 = models.StringField( label=C.CRT_QUESTIONS[0]['text'], blank=True, ) crt_2 = models.StringField( label=C.CRT_QUESTIONS[1]['text'], blank=True, ) crt_3 = models.StringField( label=C.CRT_QUESTIONS[2]['text'], blank=True, ) def set_svo_score(self): values_self = [] values_other = [] for i in range(1, len(C.SVO_MATRICES) + 1): values_self.append(getattr(self, f'svo_choice_{i}_self')) values_other.append(getattr(self, f'svo_choice_{i}_other')) self.svo_mean_self = round(sum(values_self) / len(values_self), 3) self.svo_mean_other = round(sum(values_other) / len(values_other), 3) self.svo_angle = round( math.degrees(math.atan2(self.svo_mean_other - 50, self.svo_mean_self - 50)), 3, ) if self.svo_angle > 57.15: self.svo_type = 'Altruistic' elif self.svo_angle > 22.45: self.svo_type = 'Prosocial' elif self.svo_angle > -12.04: self.svo_type = 'Individualistic' else: self.svo_type = 'Competitive' self.participant.vars['svo_angle'] = self.svo_angle self.participant.vars['svo_type'] = self.svo_type self.participant.vars['svo_mean_self'] = self.svo_mean_self self.participant.vars['svo_mean_other'] = self.svo_mean_other def set_sd3_scores(self): def get_val(idx): q = SD3_QUESTIONS_DICT[idx] val = getattr(self, f'sd3_{idx}') return (6 - val) if q['rev'] else val self.sd3_mach = round(sum(get_val(i) for i in range(1, 10)) / 9, 2) self.sd3_narc = round(sum(get_val(i) for i in range(10, 19)) / 9, 2) self.sd3_psych = round(sum(get_val(i) for i in range(19, 28)) / 9, 2) self.participant.vars['sd3_mach'] = self.sd3_mach self.participant.vars['sd3_narc'] = self.sd3_narc self.participant.vars['sd3_psych'] = self.sd3_psych @staticmethod def _parse_number(raw): if raw is None: return None txt = str(raw).strip().lower().replace(',', '.') txt = txt.replace('tl', '').replace('ecu', '').replace('minutes', '').replace('minute', '').strip() try: return float(txt) except ValueError: return None def set_crt_score(self): score = 0 for q in C.CRT_QUESTIONS: raw = getattr(self, f'crt_{q["id"]}', '') val = self._parse_number(raw) if val is not None: for correct in q['correct_numbers']: if abs(val - correct) < 0.001: score += 1 break self.crt_score = score self.participant.vars['crt_score'] = score # ── 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) def candidate_report(candidate: Player): return dict( id=candidate.id_in_group, svo_type=candidate.participant.vars.get('svo_type', 'NA'), svo_angle=candidate.participant.vars.get('svo_angle', None), crt_score=candidate.participant.vars.get('crt_score', None), sd3_mach=candidate.participant.vars.get('sd3_mach', None), sd3_narc=candidate.participant.vars.get('sd3_narc', None), sd3_psych=candidate.participant.vars.get('sd3_psych', None), ) class SVOPage(Page): form_model = 'player' @staticmethod def is_displayed(player: Player): return player.round_number == 1 @staticmethod def get_form_fields(player: Player): fields_self = [f'svo_choice_{i}_self' for i in range(1, len(C.SVO_MATRICES) + 1)] fields_other = [f'svo_choice_{i}_other' for i in range(1, len(C.SVO_MATRICES) + 1)] return fields_self + fields_other @staticmethod def js_vars(player: Player): return dict( matrices=C.SVO_MATRICES, fill_auto=player.session.config.get('fill_auto', False), ) @staticmethod def vars_for_template(player: Player): return dict( **common_template_vars(player), matrices=C.SVO_MATRICES, ) @staticmethod def error_message(player: Player, values): missing = [] for i in range(1, len(C.SVO_MATRICES) + 1): if values.get(f'svo_choice_{i}_self') is None or values.get(f'svo_choice_{i}_other') is None: missing.append(i) if missing: return 'Lütfen tüm karar tablolarında bir seçenek işaretleyiniz.' @staticmethod def before_next_page(player: Player, timeout_happened): if timeout_happened: for i in range(1, len(C.SVO_MATRICES) + 1): selected = random.choice(C.SVO_MATRICES[i - 1]) setattr(player, f'svo_choice_{i}_self', selected[0]) setattr(player, f'svo_choice_{i}_other', selected[1]) player.set_svo_score() class DarkTriadPage(Page): form_model = 'player' @staticmethod def is_displayed(player: Player): return player.round_number == 1 and C.USE_DARK_TRIAD @staticmethod def get_form_fields(player: Player): return [f'sd3_{i}' for i in range(1, C.NUM_SD3_QUESTIONS + 1)] @staticmethod def vars_for_template(player: Player): return common_template_vars(player) @staticmethod def error_message(player: Player, values): for i in range(1, C.NUM_SD3_QUESTIONS + 1): if values.get(f'sd3_{i}') is None: return 'Lütfen tüm ifadeler için bir seçenek işaretleyiniz.' @staticmethod def before_next_page(player: Player, timeout_happened): if timeout_happened: for i in range(1, C.NUM_SD3_QUESTIONS + 1): setattr(player, f'sd3_{i}', random.randint(1, 5)) player.set_sd3_scores() class CRTPage(Page): form_model = 'player' @staticmethod def is_displayed(player: Player): return player.round_number == 1 @staticmethod def get_form_fields(player: Player): return [f'crt_{q["id"]}' for q in C.CRT_QUESTIONS] @staticmethod def vars_for_template(player: Player): return dict( **common_template_vars(player), num_questions=C.NUM_CRT_QUESTIONS, ) @staticmethod def error_message(player: Player, values): for q in C.CRT_QUESTIONS: if not str(values.get(f'crt_{q["id"]}', '')).strip(): return 'Lütfen tüm problem çözme sorularını cevaplayınız.' @staticmethod def before_next_page(player: Player, timeout_happened): if timeout_happened: for q in C.CRT_QUESTIONS: setattr(player, f'crt_{q["id"]}', '') player.set_crt_score() 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( **common_template_vars(player), 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, ) # ── 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( **common_template_vars(player), 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 c1 = g.get_player_by_id(g.candidate1_id) c2 = g.get_player_by_id(g.candidate2_id) return dict( **common_template_vars(player), candidate1_id=g.candidate1_id, candidate2_id=g.candidate2_id, candidate1_report=candidate_report(c1), candidate2_report=candidate_report(c2), ) @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( **common_template_vars(player), 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( **common_template_vars(player), role=current_role(player), mpcr=round(g.mpcr, 2), 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( **common_template_vars(player), mpcr=round(g.mpcr, 2), 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( **common_template_vars(player), mpcr=round(g.mpcr, 2), actual_revenue=actual_revenue, 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( **common_template_vars(player), 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, ) 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( **common_template_vars(player), 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), ) 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( **common_template_vars(player), 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( **common_template_vars(player), 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), 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), )) incumbent = player.group.get_leader() opposition = player.group.get_opposition() return dict( **common_template_vars(player), history=history, treatment=treatment, incumbent_id=incumbent.id_in_group if incumbent else None, opposition_id=opposition.id_in_group if opposition else None, incumbent_report=candidate_report(incumbent) if incumbent else None, opposition_report=candidate_report(opposition) if opposition else None, ) @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( **common_template_vars(player), 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), 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): final_round = get_final_round(player) # If the realised game ends before the app's technical maximum, # show the payoff page in the first inactive round. if final_round < C.NUM_ROUNDS: return player.round_number == final_round + 1 # If the game reaches the technical maximum, show it at the end of that round. return player.round_number == final_round @staticmethod def vars_for_template(player: Player): final_round = get_final_round(player) final_player = player.in_round(final_round) payoff_rounds = player.in_rounds(1, final_round) total_ecus = round(float(sum(float(p.payoff or 0) for p in payoff_rounds)), 2) conversion_rate = player.session.config.get('real_world_currency_per_point', 0) return dict( **common_template_vars(player), total_ecus=total_ecus, real_money=round(total_ecus * conversion_rate, 2), role=current_role(final_player), final_treasury=round(final_player.group.treasury_end, 2), rounds_played=final_round, ) page_sequence = [ # ── Pre-game diagnostic tests, all participants ── SVOPage, DarkTriadPage, CRTPage, # ── 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, ]