def make_meals(self, num_meals): humans = list(Player.current_players().filter(team='H')) zombies = list(Player.current_players().filter(team='Z')) g = Game.imminent_game() days = (g.end_date - g.start_date).days day = g.start_date while day < g.end_date: meals_per_hour = [0 for i in xrange(24)] for i in xrange(int(num_meals / days)): meals_per_hour[int(random.gauss(13, 4)) % 24] += 1 for hour in xrange(24): for meal in xrange(meals_per_hour[hour]): z = int(random.random() * len(zombies)) h = int(random.random() * len(humans)) Meal( eater=zombies[z], eaten=humans[h], time=datetime.combine(day, time(hour=hour)), location=random.choice(Building.objects.all()), ).save() # Instead of retrieving the entire zombie and human lists # again, why don't we just add the human to the zombie # horde ourselves? zombies.append(humans.pop(h)) day += timedelta(days=1)
def form_valid(self, form): sender = "*****@*****.**" # sender = "*****@*****.**" if form.is_valid(): # send email using the self.cleand_data dictionary subject = form.cleaned_data['subject'] body = form.cleaned_data['body'] recipient_title = form.cleaned_data['recipient'] # based on inputs from the recipients field, retrieve the list of players # to send emails to, options are: # all players, humans, or zombies if (recipient_title == MailerForm.ALLPLAYERS): recipients = [p.user.email for p in Player.current_players()] elif (recipient_title == MailerForm.HUMANS): recipients = [ p.user.email for p in Player.current_players() if p.team == "H" ] elif (recipient_title == MailerForm.ZOMBIES): recipients = [ p.user.email for p in Player.current_players() if p.team == "Z" ] # send mail based on the given inputs send_mail(subject, body, sender, recipients) return super(Mailer, self).form_valid(form)
def form_valid(self, form): kindOptions = {"Humans": "H", "ZOMBIES": "Z"} sender = "*****@*****.**" # sender = "*****@*****.**" if form.is_valid(): # send email using the self.cleand_data dictionary subject = form.cleaned_data['subject'] body = form.cleaned_data['body'] recipient_title = form.cleaned_data['recipient'] schoolSelection = form.cleaned_data['school'] kind_recipients = [] kind_label = "[" + recipient_title + "]" # Using a dictionary to have more robust way to select players if (recipient_title in kindOptions): kind_recipients = [ p.user.email for p in Player.current_players() if p.team == kindOptions[recipient_title] ] else: # Default recipients list is all players kind_recipients = [p.user.email for p in Player.current_players()] subject = kind_label + subject school_recipients = [] for schools in schoolSelection: school_label = "[" + schools + "]" subject = school_label + subject school_recipients.append([ p.user.email for p in Player.current_players() if p.school.name == schools ]) # flatten the list of lists school_recipients = [ item for sublist in school_recipients for item in sublist ] # combine two lists to get to right list of recipients recipients = [] if (len(school_recipients) == 0): recipients = kind_recipients else: recipients = list( set(kind_recipients).intersection(set(school_recipients))) # TODO: Authentication error for sender for [email protected] mailBag = EmailMessage(subject, body, sender, [], recipients) mailBag.send(fail_silently=False) return super(Mailer, self).form_valid(form)
def clean_email(self): """Ensure that a user does not register twice for the same game.""" email = self.cleaned_data['email'] if Player.current_players().filter(user__username=email).exists(): raise ValidationError(self.error_messages['duplicate_user']) return email
def clean_feed(self): """Ensure that the same feed code is not used twice in the same game.""" feedcode = self.cleaned_data['feed'] if Player.current_players().filter(feed=feedcode).exists(): raise ValidationError(self.error_messages['duplicate_feed']) return feedcode
def clean_feed(self): """Ensure that the same feed code is not used twice in the same game.""" feedcode = self.cleaned_data['feed'] if Player.current_players().filter(feed=feedcode).exists(): raise ValidationError(self.error_messages['duplicate_feed']) return feedcode
def clean_email(self): """Ensure that a user does not register twice for the same game.""" email = self.cleaned_data['email'] if Player.current_players().filter( Q(user__username=email) | Q(user__email=email)).exists(): raise ValidationError(self.error_messages['duplicate_user']) return email
def pick_ozs(self, num_ozs): ozs = Player.current_players().order_by('?')[:num_ozs] for p in ozs: # Retroactively volunteer the mock player p.can_oz = True p.team = 'Z' p.upgrade = 'O' p.save()
def form_valid(self, form): failure_url = '/api/failure/' sender = "*****@*****.**" # sender = "*****@*****.**" if form.is_valid(): # send email using the self.cleand_data dictionary subject = form.cleaned_data['subject'] body = form.cleaned_data['body'] recipient_title = form.cleaned_data['recipient'] # based on inputs from the recipients field, retrieve the list of players # to send emails to, options are: # all players, humans, or zombies if(recipient_title == MailerForm.ALLPLAYERS): recipients = [p.user.email for p in Player.current_players()] elif(recipient_title == MailerForm.HUMANS): recipients = [p.user.email for p in Player.current_players() if p.team == "H"] elif(recipient_title == MailerForm.ZOMBIES): recipients = [p.user.email for p in Player.current_players() if p.team == "Z"] # option to send emails to players from a specific college # should we add Keck and CGU as well? elif(recipient_title == MailerForm.HMC): recipients = [p.user.email for p in Player.current_players() if p.school.name == "Mudd"] elif(recipient_title == MailerForm.CMC): recipients = [p.user.email for p in Player.current_players() if p.school.name == "CMC"] elif(recipient_title == MailerForm.PITZER): recipients = [p.user.email for p in Player.current_players() if p.school.name == "Pitzer"] elif(recipient_title == MailerForm.POMONA): recipients = [p.user.email for p in Player.current_players() if p.school.name == "Pomona"] elif(recipient_title == MailerForm.SCRIPPS): recipients = [p.user.email for p in Player.current_players() if p.school.name == "Scripps"] # TODO: Authentication error for sender for [email protected] mailBag = EmailMessage(subject, body, sender, [], recipients) try: mailBag.send(fail_silently=False) except Exception as ex: global exception exception = ex return redirect(failure_url) return super(Mailer, self).form_valid(form)
def get_queryset(self): queryset = Player.current_players() if self.kwargs.get('gradyear'): queryset = queryset.filter(grad_year=self.kwargs['gradyear']) if self.kwargs.get('school'): queryset = queryset.filter( school__name__istartswith=self.kwargs['school']) return (queryset.select_related('user', 'school__name').annotate( meal_count=Count('meal_set')).order_by('-meal_count'))
def handle(self, *args, **options): try: self.game = Game.imminent_game() except Game.DoesNotExist: # Create game and players call_command( 'randomplayers', players=options.get('players'), ozs=options.get('ozs'), password=options.get('password'), stdout=self.stdout, stderr=self.stderr, ) self.game = Game.imminent_game() humans = Player.current_players().filter(team='H') zombies = Player.current_players().filter(team='Z') if not len(humans) or not len(zombies): self.stderr.write( '\n'.join(["There are no players in the current game.", "To generate a batch of random players, run", " ./manage.py randomplayers"])) return num_meals = options.get('meals') or len(humans) / 2 self.stdout.write("Creating {} meals".format(num_meals)) if not num_meals: return if len(humans) < num_meals: self.stderr.write( "There are only {} humans in the current game.".format(len(humans)) ) num_meals = len(humans) meals = self.make_meals(num_meals) Meal.objects.bulk_create(meals)
def get_context_data(self, **kwargs): context = super(PlayerListView, self).get_context_data(**kwargs) context['game_season'] = Game.nearest_game().season() context['schools'] = School.objects.all().annotate( num_players=Count('player_set')).order_by('-num_players') context['years'] = map( str, sorted(set([p.grad_year for p in Player.current_players()]))) context['school'] = self.kwargs.get('school', '') context['gradyear'] = self.kwargs.get('gradyear', '') return context
def get_context_data(self, **kwargs): context = super(PlayerListView, self).get_context_data(**kwargs) context['game_season'] = Game.nearest_game().season() context['schools'] = School.objects.all().annotate( num_players=Count('player_set') ).order_by('-num_players') context['years'] = map(str, sorted(set([p.grad_year for p in Player.current_players()]))) context['school'] = self.kwargs.get('school', '') context['gradyear'] = self.kwargs.get('gradyear', '') return context
def get_queryset(self): queryset = Player.current_players() if self.kwargs.get('gradyear'): queryset = queryset.filter(grad_year=self.kwargs['gradyear']) if self.kwargs.get('school'): queryset = queryset.filter(school__name__istartswith=self.kwargs['school']) return (queryset. select_related('user', 'school__name'). annotate(meal_count=Count('meal_set')). order_by('-meal_count'))
def clean_email(self): """Ensure that a user does not register twice for the same game.""" email = self.cleaned_data['email'] # Check both username and email because we're using both # fields for the same purpose... slice is there because # Django's builtin username field has a limit of 30 # characters. if Player.current_players().filter( Q(user__username=email[:30]) | Q(user__email=email) ).exists(): raise ValidationError(self.error_messages['duplicate_user']) return email
def raw_serialization(self, context): game = Game.nearest_game() t0, tf = time_endpoints(game) players = Player.current_players().all() meals = Meal.objects.select_related('eaten').all() eaten_zombies = set([m.eaten for m in meals]) ozs = [p for p in players if p.team == 'Z' and p not in eaten_zombies] num_zombies = len(ozs) num_humans = len(players) - num_zombies human_tally = [] zombie_tally = [] meals_vs_hours = meals_per_hour(game, self.get_queryset()) for hour in xrange(len(meals_vs_hours)): t = t0 + timedelta(hours=hour) # Stop the graph at the current time if t > settings.NOW(): break meal_count = meals_vs_hours[hour] num_humans -= meal_count num_zombies += meal_count human_tally.append([json_format_time(t), num_humans]) zombie_tally.append([json_format_time(t), num_zombies]) if not human_tally: human_tally = [[json_format_time(t0), num_humans]] if not zombie_tally: zombie_tally = [[json_format_time(t0), num_zombies]] return [ { 'label': 'humans', 'data': human_tally, 'color': 'rgb(128, 0, 0)' }, { 'label': 'zombies', 'data': zombie_tally, 'color': 'rgb(0, 128, 0)' }, ]
def json_get_all_names_and_emails(request): """A function that displays every players name and email in the current game. """ # Check out HVZ/main/models.py for helper functions relating to Players. # Player.current_players() returns all Players in the current Game. emails = [(str(p.user.first_name) + " " + str(p.user.last_name), p.mailbox) for p in Player.current_players()] # json.dumps creates a string from a Python object. You can then # read the string and convert it into an Objective-C data # structure using NSJSONSerialization in Objective-C. json_data = json.dumps(emails) return HttpResponse(json_data, content_type="application/json")
def json_get_all_emails(request): """A function that displays all emails. You should replace this with one you actually want. """ # Check out HVZ/main/models.py for helper functions relating to Players. # Player.current_players() returns all Players in the current Game. emails = [p.user.email for p in Player.current_players()] # json.dumps creates a string from a Python object. You can then # read the string and convert it into an Objective-C data # structure using NSJSONSerialization in Objective-C. json_data = json.dumps(emails) return HttpResponse(json_data, content_type="application/json")
def raw_serialization(self, context): game = Game.nearest_game() t0, tf = time_endpoints(game) players = Player.current_players().all() meals = Meal.objects.select_related('eaten').all() eaten_zombies = set([m.eaten for m in meals]) ozs = [p for p in players if p.team == 'Z' and p not in eaten_zombies] num_zombies = len(ozs) num_humans = len(players) - num_zombies human_tally = [] zombie_tally = [] meals_vs_hours = meals_per_hour(game, self.get_queryset()) for hour in xrange(len(meals_vs_hours)): t = t0 + timedelta(hours=hour) # Stop the graph at the current time if t > settings.NOW(): break meal_count = meals_vs_hours[hour] num_humans -= meal_count num_zombies += meal_count human_tally.append([json_format_time(t), num_humans]) zombie_tally.append([json_format_time(t), num_zombies]) if not human_tally: human_tally = [[json_format_time(t0), num_humans]] if not zombie_tally: zombie_tally = [[json_format_time(t0), num_zombies]] return [ {'label': 'humans', 'data': human_tally, 'color': 'rgb(128, 0, 0)'}, {'label': 'zombies', 'data': zombie_tally, 'color': 'rgb(0, 128, 0)'}, ]
def raw_serialization(self, context): self.players = Player.current_players().filter(team='Z').select_related('user') self.names = {p: p.user.get_full_name() for p in self.players} self.meals = (Meal.objects.filter(eater__game=Game.nearest_game()) .select_related('eater', 'eaten')) self.possible_ozs = set(self.players) self.children = defaultdict(list) for m in self.meals: if m.eaten not in self.players: continue self.children[m.eater].append(m.eaten) self.possible_ozs.remove(m.eaten) ozs = [p for p in self.players if p in self.possible_ozs] return { "name": "Subject Zero", "children": map(self.traverse, ozs), }
def json_get_all_graduation_years(request): """A pretty useless function that displays all graduation years. You should replace this with one you actually want. """ # Check out HVZ/main/models.py for helper functions relating to Players. # Player.current_players() returns all Players in the current Game. years = [p.grad_year for p in Player.current_players()] # json.dumps creates a string from a Python object. You can then # read the string and convert it into an Objective-C data # structure using NSJSONSerialization in Objective-C. json_data = json.dumps(years) return HttpResponse( json_data, content_type="application/json" )
def raw_serialization(self, context): self.players = Player.current_players().filter( team='Z').select_related('user') self.names = {p: p.user.get_full_name() for p in self.players} self.meals = (Meal.objects.filter( eater__game=Game.nearest_game()).select_related('eater', 'eaten')) self.possible_ozs = set(self.players) self.children = defaultdict(list) for m in self.meals: if m.eaten not in self.players: continue self.children[m.eater].append(m.eaten) self.possible_ozs.remove(m.eaten) ozs = [p for p in self.players if p in self.possible_ozs] return { "name": "Subject Zero", "children": map(self.traverse, ozs), }
class DonateForm(forms.Form): receiver = forms.ModelChoiceField( Player.current_players().filter(team="Z"), required=True, ) numberOfMeals = forms.IntegerField( required=True, label="Number of Brains", ) def __init__(self, *args, **kwargs): super(DonateForm, self).__init__(*args, **kwargs) def clean(self): cleaned_data = super(DonateForm, self).clean() if not 'receiver' in cleaned_data: raise forms.ValidationError( "You must specify a person to receive your brains!") if not 'numberOfMeals' in cleaned_data: raise forms.ValidationError( "You must specify a number of brains to donate!") receivingPlayer = cleaned_data['receiver'] if not receivingPlayer.team == "Z": raise forms.ValidationError( "You somehow donated brains to a Human! They don't want your brains! Yet..." ) num_meals = cleaned_data['numberOfMeals'] if num_meals <= 0: raise forms.ValidationError( "You must donate a positive number of brains!") return cleaned_data
def get_queryset(self): return Player.current_players()
def human_with_code(feedcode): """Ensure the feedcode corresponds to a currently-playing Human.""" if not Player.current_players().filter(team="H", feed=feedcode).exists(): raise ValidationError( "{} doesn't correspond to a playing human!".format(feedcode))
def human_with_code(feedcode): """Ensure the feedcode corresponds to a currently-playing Human.""" if not Player.current_players().filter(team="H", feed=feedcode).exists(): raise ValidationError( "{} doesn't correspond to a playing human!".format(feedcode))
def get_queryset(self): return Player.current_players()