from otree.api import * import random import matplotlib.pyplot as plt doc = """ a.k.a. Keynesian beauty contest. Players all guess a number; whoever guesses closest to 2/3 of the average wins. See https://en.wikipedia.org/wiki/Guess_2/3_of_the_average """ class C(BaseConstants): PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 NAME_IN_URL = 'turst_uncertainty' JACKPOT = cu(100) GUESS_MAX = 100 class Subsession(BaseSubsession): pass class Group(BaseGroup): two_thirds_avg = models.FloatField() best_guess = models.IntegerField() num_winners = models.IntegerField() class Player(BasePlayer): # guess = models.IntegerField( # min=0, max=C.GUESS_MAX # ) instruction_version = models.StringField() random_sequence = models.StringField() class Plot(Page): def vars_for_template(self): player = self.player # Convert the stored random numbers back to a list random_numbers = [int(x) for x in player.random_sequence.split(', ')] # Create a simple line plot plt.plot(random_numbers) plt.xlabel('Index') plt.ylabel('Random Number') plt.title('Random Number Sequence') # Save the figure as an image img_path = f'_static/{self.subsession.session.code}_plot.png' plt.savefig(img_path) return {'image_path': img_path} # FUNCTIONS def set_payoffs(group: Group): players = group.get_players() guesses = [p.guess for p in players] two_thirds_avg = (2 / 3) * sum(guesses) / len(players) group.two_thirds_avg = round(two_thirds_avg, 2) group.best_guess = min(guesses, key=lambda guess: abs(guess - group.two_thirds_avg)) winners = [p for p in players if p.guess == group.best_guess] group.num_winners = len(winners) for p in winners: p.is_winner = True p.payoff = C.JACKPOT / group.num_winners # PAGES class Introduction(Page): @staticmethod def is_displayed(player: Player): player.instruction_version = random.choice(['a', 'b', 'c']) return player.round_number == 1 class Guess(Page): form_model = 'player' #form_fields = ['guess'] @staticmethod def vars_for_template(player: Player): group = player.group random_numbers = [str(random.randint(1, 100)) for _ in range(30)] # Generate 10 random numbers random_sequence = ', '.join(random_numbers) # Store the numbers as a comma-separated string #return player.round_number == 1 #def vars_for_template(self): #player = self.player # Convert the stored random numbers back to a list random_numbers = [int(x) for x in random_sequence.split(', ')] # Create a simple line plot plt.plot(random_numbers) plt.xlabel('Index') plt.ylabel('Random Number') plt.title('Random Number Sequence') # Save the figure as an image img_path = f'_static/{player.subsession.session.code}_plot.png' plt.savefig(img_path) imgg_pp=f'http://localhost:8000/static/{player.subsession.session.code}_plot.png' print(img_path) return { 'image_path': imgg_pp} class ResultsWaitPage(WaitPage): after_all_players_arrive = set_payoffs class Results(Page): @staticmethod def vars_for_template(player: Player): #group = player.group return {'round_n' : 1} page_sequence = [Introduction, Guess, Results]