"""INTERFER v16: worker task, pairing and initial-earnings quiz.""" from otree.api import * from interfer_shared import Config import random import secrets import string import time import json class C(BaseConstants): NAME_IN_URL = 'worker' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 TASK_SECONDS = Config.TASK_SECONDS WORDS = Config.WORDS W = Config.W class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): score = models.IntegerField(initial=0) task_incorrect = models.IntegerField(initial=0) pairing1 = models.StringField(blank=True) pairing2 = models.StringField(blank=True) pairing3 = models.StringField(blank=True) pairing_quiz_first_wrong = models.IntegerField(initial=0) pairing_quiz_total_wrong = models.IntegerField(initial=0) pairing_quiz_first_wrong_ids = models.LongStringField(initial='[]') def initialize_work(player): """Initialize only once, on the server, before the page is rendered. The task and its absolute deadline survive reloads. In particular, the first mapping does not depend on a websocket/live message being received. """ participant = player.participant if 'work_started' not in participant.vars: now = time.time() participant.vars['work_started'] = now participant.vars['task_deadline'] = now + C.TASK_SECONDS participant.vars['task_count'] = 0 participant.vars['task_errors'] = 0 participant.vars['task_done'] = False participant.vars['task_nonce'] = '' participant.vars['task_item'] = None participant.vars['word_remaining'] = [] if participant.vars['task_item'] is None and not participant.vars['task_done']: make_work_item(participant) return participant def make_work_item(participant): # Draw each word once per cycle, then reshuffle if the pool is exhausted. # The letter-number mapping is regenerated for EVERY new word. remaining = list(participant.vars.get('word_remaining') or []) if not remaining: remaining = [w for w in C.WORDS if len(w) == 4] random.shuffle(remaining) word = remaining.pop() # Assign the updated list explicitly. In-place mutation of a nested list # inside participant.vars may not persist reliably across oTree requests. participant.vars['word_remaining'] = remaining alphabet = list(string.ascii_uppercase) extra = random.sample([x for x in alphabet if x not in word], 15 - len(set(word))) letters = list(dict.fromkeys(word)) + extra random.shuffle(letters) numbers = [random.randrange(10) for _ in letters] mapping = dict(zip(letters, numbers)) participant.vars['task_item'] = dict( word=word, letters=letters, numbers=numbers, answer=''.join(str(mapping[x]) for x in word), ) participant.vars['task_nonce'] = secrets.token_hex(12) def work_status(participant): remaining = max(0, participant.vars['task_deadline'] - time.time()) if remaining <= 0: participant.vars['task_done'] = True return dict(done=True, count=participant.vars['task_count'], remaining=0) item = participant.vars['task_item'] return dict(word=item['word'], letters=item['letters'], numbers=item['numbers'], nonce=participant.vars['task_nonce'], count=participant.vars['task_count'], remaining=remaining) class WorkerIntro(Page): @staticmethod def is_displayed(player): return player.round_number == 1 and player.participant.vars.get('consent_given', False) class Work(Page): @staticmethod def is_displayed(player): return player.round_number == 1 and player.participant.vars.get('consent_given', False) @staticmethod def vars_for_template(player): participant = initialize_work(player) status = work_status(participant) return dict(seconds=C.TASK_SECONDS, initial_status_json=json.dumps(status), deadline_ms=int(participant.vars['task_deadline'] * 1000)) @staticmethod def get_timeout_seconds(player): # Native oTree timeout automatically submits/advances the page even if # live messaging fails; based on the original absolute server deadline. participant = initialize_work(player) return max(0, participant.vars['task_deadline'] - time.time()) @staticmethod def live_method(player, data): participant = initialize_work(player) if time.time() >= participant.vars['task_deadline']: participant.vars['task_done'] = True player.score = participant.vars['task_count'] player.task_incorrect = participant.vars['task_errors'] return {player.id_in_group: work_status(participant)} if data.get('action') == 'submit': item = participant.vars['task_item'] if not item or data.get('nonce') != participant.vars['task_nonce']: result = work_status(participant) result['error'] = 'Your word has changed. Please use the displayed word.' return {player.id_in_group: result} answer = str(data.get('answer', '')).strip() if answer == item['answer']: participant.vars['task_count'] += 1 make_work_item(participant) else: participant.vars['task_errors'] += 1 result = work_status(participant) result['error'] = 'The sequence is not correct. Please try again.' return {player.id_in_group: result} return {player.id_in_group: work_status(participant)} @staticmethod def before_next_page(player, timeout_happened): participant = initialize_work(player) player.score = participant.vars['task_count'] or 0 player.task_incorrect = participant.vars['task_errors'] or 0 participant.vars['task_done'] = True class WorkerScore(Page): @staticmethod def is_displayed(player): return player.round_number == 1 and player.participant.vars.get('consent_given', False) @staticmethod def vars_for_template(player): # This page is gated by Work.js but also persists server-side elapsed time. return dict(score=player.participant.vars['task_count'] or 0) @staticmethod def before_next_page(player, timeout_happened): player.score = player.participant.vars['task_count'] or 0 player.task_incorrect = player.participant.vars['task_errors'] or 0 class Pairing(Page): """Future anonymous matching and on-page three-question comprehension check.""" form_model = 'player' form_fields = ['pairing1', 'pairing2', 'pairing3'] @staticmethod def is_displayed(player): return player.round_number == 1 and player.participant.vars.get('consent_given', False) @staticmethod def error_message(player, values): expected = {'pairing1': 'one', 'pairing2': 'coin', 'pairing3': 'higher'} wrong = [field for field, answer in expected.items() if values.get(field) != answer] if not wrong: return None previously_wrong = set(json.loads(player.pairing_quiz_first_wrong_ids or '[]')) player.pairing_quiz_first_wrong += len(set(wrong) - previously_wrong) player.pairing_quiz_total_wrong += len(wrong) player.pairing_quiz_first_wrong_ids = json.dumps(sorted(previously_wrong | set(wrong))) hints = { 'pairing1': 'One worker initially receives the full amount; the other initially receives zero.', 'pairing2': 'Under Luck, both workers have the same chance, regardless of their scores.', 'pairing3': 'Under Performance, the worker with more correctly completed words receives the full amount. A tie is broken randomly.', } return {field: hints[field] for field in wrong} page_sequence = [WorkerIntro, Work, WorkerScore, Pairing]