def remove_from_league(user_id): """ Remove a certain user_id from their league, only if the draft hasn't already started """ #Current user's id, used to identify their data account = Account.get_or_insert(user_id) if league_key(account.league).get() and league_key( account.league).get().draft_current_position == 0: #Remove user's choices and lineup for the league choice = choice_key(account_key(user_id), account.league).get() if choice: lineup_query = Lineup.query(ancestor=choice.key).fetch() for lineup in lineup_query: lineup.key.delete() choice.key.delete() #If this is the last person in the league, or this is the commissioner, delete it after they leave players = Account.query().filter( Account.league == account.league).fetch() if len(players) == 1 or account.league == account.key.id(): past_league = account.league #Remove User's association with league account.league = '0' account.put() delete_league(past_league) #Remove User's association with league account.league = '0' account.put()
def get(self): """ When visited by the league commissioner, the draft is started The commissioner is then redirected to the draft page """ # Checks for active Google account session user = users.get_current_user() #Current user's id, used to identify their data user_id = user.user_id() account = globals.get_or_create_account(user) league_id = account.league league = league_key(league_id).get() league_comissioner = league.key.id() if league_comissioner == user_id: league_player_query = Account.query(Account.league == league_id) league_players = league_player_query.fetch() if len(league_players) > 1: if league.draft_current_position == 0: start_draft(league_id) setup_for_next_pick(league_id) self.redirect('/draft/') else: globals.display_error_page(self, self.request.referer, error_messages.draft_already_completed) else: globals.display_error_page(self, self.request.referer, error_messages.league_too_small) else: globals.display_error_page(self, self.request.referer,error_messages.access_denied)
def close_draft(league_id): """ Preform all of the operations necessary to finish the drafting process :param league_id: The league to do this in Called at the end of the draft Initialize lineup items Generate schedule """ league = league_key(league_id).get() league.draft_current_position = -1 # Indicate the draft is over league.draft_current_timeout = None league.put() #Build a schedule generate_schedule(league_id) #Initialize requirements for bench/active system and distribute a schedule league_player_query = Account.query(Account.league == league_id) league_players = league_player_query.fetch() for player in league_players: #For the active system choice = Choice.get_or_insert(league_id, parent=player.key) for i in range(1, globals.number_of_official_weeks + 1): initialize_lineup(i, choice) # Initialize weekly lineups player.record.append('') player.put()
def get_leader_board(league_id): """Return an array of dictionaries with leader board data for a league""" leader_board = [] league_player_query = Account.query(Account.league == league_id) league_players = league_player_query.fetch() rank_list = [] #Create a list to sort by league points for player in league_players: rank_list.append({ 'id': player.key.id(), 'nickname': player.nickname, 'points': get_league_points(player.key.id()) }) sorted_by_points = sorted(rank_list, key=lambda account: account['points'], reverse=True) #Build the leader board for i, player in enumerate(sorted_by_points): leader_board.append({ 'name': player['nickname'], 'rank': i + 1, 'record': get_player_record(player['id']), 'points': get_person_total_points(player['id']), }) # Remove bye week for player in leader_board: player['record'].pop() return leader_board
def get(self): """ When visited by the league commissioner, the draft is started The commissioner is then redirected to the draft page """ # Checks for active Google account session user = users.get_current_user() #Current user's id, used to identify their data user_id = user.user_id() account = globals.get_or_create_account(user) league_id = account.league league = league_key(league_id).get() league_comissioner = league.key.id() if league_comissioner == user_id: league_player_query = Account.query(Account.league == league_id) league_players = league_player_query.fetch() if len(league_players) > 1: if league.draft_current_position == 0: start_draft(league_id) setup_for_next_pick(league_id) self.redirect('/draft/') else: globals.display_error_page( self, self.request.referer, error_messages.draft_already_completed) else: globals.display_error_page(self, self.request.referer, error_messages.league_too_small) else: globals.display_error_page(self, self.request.referer, error_messages.access_denied)
def get_leader_board(league_id): """Returns an array of dictionaries with leader board data for a league""" leader_board = [] league_player_query = Account.query(Account.league == league_id) league_players = league_player_query.fetch() rank_list = [] #Create a list to sort by league points for player in league_players: rank_list.append({'id': player.key.id(), 'nickname': player.nickname, 'points': get_league_points(player.key.id()) }) sorted_by_points = sorted(rank_list, key=lambda account: account['points'], reverse=True) #Build the leader board for i, player in enumerate(sorted_by_points): leader_board.append({'name': player['nickname'], 'rank': i + 1, 'record': get_player_record(player['id'])}) # Remove bye week for player in leader_board: player['record'].pop() return leader_board
def get_schedule(league_id): league_player_query = Account.query(Account.league == league_id) league_players = league_player_query.fetch() master_schedule = [] for player in league_players: master_schedule.append({'user': player.key.id(), 'schedule': player.schedule}) return master_schedule
def delete_league(league_id): if league_id != '0': #Don't ever delete the default league league = league_key(league_id).get() players = Account.query().filter(Account.league == league_id).fetch() draft_picks = DraftPick.query(ancestor=league.key).fetch() for player in players: remove_from_league(player.key.id()) for draft_pick in draft_picks: draft_pick.key.delete() league.key.delete()
def get_taken_teams(league_id): """Returns a list of taken teams based on a league and event id""" taken_teams = [] league_player_query = Account.query(Account.league == league_id) league_players = league_player_query.fetch() for player in league_players: choice = Choice_key(account_key(player.key.id()), league_id).get() if choice: taken_teams.append(str(choice.drafted_team)) return taken_teams
def delete_league(league_id): """Delete a particular league""" if league_id != '0': #Don't ever delete the default league league = league_key(league_id).get() players = Account.query().filter(Account.league == league_id).fetch() draft_picks = DraftPick.query(ancestor=league.key).fetch() for player in players: remove_from_league(player.key.id()) for draft_pick in draft_picks: draft_pick.key.delete() league.key.delete()
def get_taken_teams(league_id): """Return a list of teams that have already been drafted based on a league and event id""" taken_teams = [] league_player_query = Account.query(Account.league == league_id) league_players = league_player_query.fetch() for player in league_players: choice = Choice.get_or_insert(league_id, parent=player.key) if choice: for team in choice.current_team_roster: taken_teams.append(str(team)) return taken_teams
def get_schedule(league_id): """Return the league master schedule for a league id""" league_player_query = Account.query(Account.league == league_id) league_players = league_player_query.fetch() master_schedule = [] for player in league_players: master_schedule.append({ 'user': player.key.id(), 'schedule': player.schedule }) return master_schedule
def finish_week(league_id, past_week_num): """ Preform the operations necessary to move on to the next week :param league_id: The league to finish :param past_week_num: The week number to finish This function will - Calculate winners and loosers - Update player records with this information """ league_player_query = Account.query(Account.league == league_id) league_players = league_player_query.fetch() for player in league_players: opponent = player.schedule[past_week_num - 1] # -1 for conversion to 0 based index if opponent != globals.schedule_bye_week: opponent_points = get_total_week_points(opponent, past_week_num) player_points = get_total_week_points(player.key.id(), past_week_num) if opponent_points < player_points: player.record[ past_week_num - 1] = globals.record_win # -1 for conversion to 0 based index elif opponent_points == player_points: #We have to consider tiebreakers, notably bench points if get_bench_points(player.key.id(), past_week_num) > get_bench_points( opponent, past_week_num): player.record[ past_week_num - 1] = globals.record_win # -1 for conversion to 0 based index elif get_bench_points(player.key.id(), past_week_num) < get_bench_points( opponent, past_week_num): player.record[ past_week_num - 1] = globals.record_loss # -1 for conversion to 0 based index else: #Bench points and active points tie, mark it as an actual tie player.record[ past_week_num - 1] = globals.record_tie # -1 for conversion to 0 based index elif opponent_points > player_points: player.record[ past_week_num - 1] = globals.record_loss # -1 for conversion to 0 based index else: # Bye week player.record[ past_week_num - 1] = globals.record_bye # -1 for conversion to 0 based index player.put()
def get(self): # Checks for active Google account session user = users.get_current_user() logout_url = users.create_logout_url('/') account = globals.get_or_create_account(user) league_id = account.league league_query = League.query() league_list = league_query.fetch() league_output = [] for league in league_list: number_of_players = len(Account.query().filter( Account.league == league.key.id()).fetch()) commissioner = "None" if account_key(league.key.id()).get(): commissioner = account_key(league.key.id()).get().nickname league_output.append({ 'name': league.name, 'id': league.key.id(), 'size': number_of_players, 'commissioner': commissioner, 'join_url': '/leagueManagement/joinLeague/' + league.key.id() }) if league_id != '0': if league_key(league_id).get().draft_current_position == 0: league_name = league_key(league_id).get().name else: league_name = globals.draft_started_sentinel else: league_name = "" #Send html data to browser template_values = { 'user': user.nickname(), 'logout_url': logout_url, 'league_list': league_output, 'league_name': league_name } template = JINJA_ENVIRONMENT.get_template('templates/league_list.html') self.response.write(template.render(template_values))
def get_readable_schedule(league_id): league_player_query = Account.query(Account.league == league_id) league_players = league_player_query.fetch() master_schedule = [] for player in league_players: schedule = player.schedule #Convert to nicknames for i, opponent in enumerate(schedule): schedule[i] = account_key(opponent).get().nickname master_schedule.append({'name': player.nickname, 'schedule': schedule}) return master_schedule
def setup_for_next_pick(league_id): """ Set the database so that the next person can make a selection :param league_id: League to do this in If the draft is finished, appropriately call lose_draft If the draft is still in progress, increase the current draft_position by one and reset the timeout """ league = league_key(league_id).get() league_player_query = Account.query(Account.league == league_id) league_players = league_player_query.fetch() number_of_picks = len(league_players) * globals.draft_rounds if league.draft_current_position == number_of_picks: # See if the draft is over close_draft(league_id) else: league.draft_current_position += 1 league.draft_current_timeout = datetime.datetime.utcnow() \ + datetime.timedelta(minutes=globals.draft_time_minutes) league.put()
def finish_week(league_id, past_week_num): league_player_query = Account.query(Account.league == league_id) league_players = league_player_query.fetch() for player in league_players: opponent = player.schedule[past_week_num - 1] # -1 for conversion to 0 based index if opponent != globals.schedule_bye_week: opponent_points = get_total_week_points(opponent, past_week_num) player_points = get_total_week_points(player.key.id(), past_week_num) logging.info(player_points) logging.info(opponent_points) if opponent_points < player_points: player.record[past_week_num - 1] = globals.record_win # -1 for conversion to 0 based index elif opponent_points == player_points: player.record[past_week_num - 1] = globals.record_tie # -1 for conversion to 0 based index elif opponent_points > player_points: player.record[past_week_num - 1] = globals.record_loss # -1 for conversion to 0 based index else: # Bye week player.record[past_week_num - 1] = globals.record_bye # -1 for conversion to 0 based index player.put()
def get_readable_schedule(league_id): """Return the league master schedule for a league id in a readable format""" league_player_query = Account.query(Account.league == league_id) league_players = league_player_query.fetch() master_schedule = [] for player in league_players: schedule = player.schedule #Convert to nicknames for i, opponent in enumerate(schedule): if opponent != globals.schedule_bye_week: schedule[i] = account_key(opponent).get().nickname else: schedule[i] = "Bye" master_schedule.append({'name': player.nickname, 'schedule': schedule}) return master_schedule
def get(self): # Checks for active Google account session user = users.get_current_user() #Current user's id, used to identify their data user_id = user.user_id() logout_url = users.create_logout_url('/') account = globals.get_or_create_account(user) league_id = account.league league_query = League.query() league_list = league_query.fetch() league_output = [] for league in league_list: number_of_players = len(Account.query().filter(Account.league == league.key.id()).fetch()) commissioner = "None" if account_key(league.key.id()).get(): commissioner = account_key(league.key.id()).get().nickname league_output.append({'name': league.name, 'id': league.key.id(), 'size': number_of_players, 'commissioner': commissioner, 'join_url': '/leagueManagement/joinLeague/' + league.key.id() }) if league_id != '0': league_name = league_key(league_id).get().name else: league_name = "" #Send html data to browser template_values = { 'user': user.nickname(), 'logout_url': logout_url, 'league_list': league_output, 'league_name': league_name } template = JINJA_ENVIRONMENT.get_template('templates/league_list.html') self.response.write(template.render(template_values))
def get(self): accountQuery = Account.query() accounts = accountQuery.fetch() for account in accounts: account.key.delete() choiceQuery = Choice.query() choices = choiceQuery.fetch() for choice in choices: choice.key.delete() draftPickQuery = DraftPick.query() draftPicks = draftPickQuery.fetch() for draftPick in draftPicks: draftPick.key.delete() lineupQuery = Lineup.query() lineups = lineupQuery.fetch() for lineup in lineups: lineup.key.delete() leagueQuery = League.query() leagues = leagueQuery.fetch() for league in leagues: league.key.delete()
def remove_from_league(user_id): #Current user's id, used to identify their data account = Account.get_or_insert(user_id) #Remove user's choices and lineup for the league choice = Choice_key(account_key(user_id), account.league).get() if choice: lineup_query = Lineup.query(ancestor=choice.key).fetch() for lineup in lineup_query: lineup.key.delete() choice.key.delete() #If this is the last person in the league, delete it after they leave players = Account.query().filter(Account.league == account.league).fetch() if len(players) == 1: past_league = account.league #Remove User's association with league account.league = '0' account.put() delete_league(past_league) #Remove User's association with league account.league = '0' account.put()
def post(self): """Handles the start of a partner connection""" user = users.get_current_user() account = globals.get_or_create_account(user) partner_name = self.request.get('partner_nickname') partner_name = partner_name.replace("@gmail.com", "") partner = Account.query(Account.nickname == partner_name).fetch() if partner: if partner[0].active_match == globals.no_match_active_id: pair_key_val = pair_key(account.key.id(), partner[0].key.id()) pair = Pair.get_or_insert(pair_key_val.id(), parent=pair_key_val.parent(), current_match_number=-1) pair.put() match_key_val = match_key(pair.current_match_number + 1, pair_key_val) partner[0].active_match = match_key_val.urlsafe() partner[0].put() account.active_match = match_key_val.urlsafe() account.put() match = Match.get_or_insert(match_key_val.id(), parent=match_key_val.parent()) match.put() past_match = Match.get_or_insert(str(pair.current_match_number), parent=pair_key_val) globals.onto_next_match(account, past_match) self.redirect('/') else: self.redirect("/?updated=User in Game Already") else: self.redirect("/?updated=Bad Email Address")
def start_draft(league_id): """ Set up to prepare for a draft :parameter league_id: The league to prepare for a draft Do the following: - Create a random order - Use this order to generate a single list of exactly what pick happens in what order - Use this to create the necessary pick objects with the correct order properties - Place the league in a position to begin the draft """ league_player_query = Account.query(Account.league == league_id) league_players = league_player_query.fetch() shuffle(league_players) # Randomize the order of the draft number_of_players = len(league_players) number_of_picks = number_of_players * globals.draft_rounds snake_draft = league_key(league_id).get().snake_draft direction = DRAFT_INCREASING pick_of_round = 0 display_number = 0 number_of_drafts = 0 while number_of_drafts < number_of_picks: if snake_draft: if direction == DRAFT_INCREASING: if pick_of_round == number_of_players: direction = DRAFT_STATIONARY elif direction == DRAFT_DECREASING: if pick_of_round == 1: direction = DRAFT_STATIONARY elif direction == DRAFT_STATIONARY: if pick_of_round == 1: direction = DRAFT_INCREASING elif pick_of_round == number_of_players: direction = DRAFT_DECREASING else: if pick_of_round == number_of_players: pick_of_round = 0 # 0 will become a 1 down below because direction = DRAFT_INCREASING if direction == DRAFT_INCREASING: pick_of_round += 1 display_number += 1 elif direction == DRAFT_DECREASING: pick_of_round -= 1 display_number -= 1 elif direction == DRAFT_STATIONARY: display_number += 4 player = league_players[pick_of_round - 1] pick_key = draft_pick_key(league_key(league_id), str(number_of_drafts + 1)) pick = DraftPick.get_or_insert(pick_key.id(), parent=pick_key.parent()) pick.display_number = display_number pick.player = player.key.urlsafe() pick.put() number_of_drafts += 1 league = league_key(league_id).get() league.draft_current_position = 0 league.put()
def get(self): """ The draft page contains the draft board, a timer, and a map; all that is necessary for the draft process """ # Checks for active Google account session user = users.get_current_user() logout_url = users.create_logout_url('/') account = globals.get_or_create_account(user) league_id = account.league if league_id != '0': #Make check to see if the time for the current pick has expired current_time = datetime.datetime.utcnow() current_timeout = league_key(league_id).get().draft_current_timeout draft_pick = draft_pick_key( league_key(league_id), league_key(league_id).get().draft_current_position).get() if current_timeout: if current_time > current_timeout: # The time has expired draft_pick.team = 0 # Set the pick to indicate it was forefited draft_pick.put() setup_for_next_pick( league_id) # Move the pick along to the next person #Display update text for the status of the last choice update update_text = self.request.get('updated') if self.request.get('updated') == "Good": update_text = "Team added successfully" league_player_query = Account.query(Account.league == league_id) players_for_the_sake_of_number = league_player_query.fetch() league_players = [] if draft_pick_key(league_key(league_id), 1).get(): # != None for i in range(1, len(players_for_the_sake_of_number) + 1): pick = draft_pick_key(league_key(league_id), i).get() league_players.append(ndb.Key(urlsafe=pick.player).get()) else: league_players = players_for_the_sake_of_number draft_board = [] player_list = [] for player in league_players: player_list.append(player.nickname) number_of_picks = len(league_players) * globals.draft_rounds for position in range(1, number_of_picks + 1): pick_query = DraftPick.query().filter( DraftPick.display_number == position) query_results = pick_query.fetch(1) pick = DraftPick() if len(query_results) != 0: pick = query_results[0] username = (((position % len(league_players)) - 1) % len(league_players)) draft_round = int((position - 1) / len(league_players)) if username == 0: draft_board.append([]) for i in range(0, len(league_players)): draft_board[draft_round].append('-') if pick and pick.team != None: draft_board[draft_round][username] = str(pick.team) if pick.team == 0: draft_board[draft_round][username] = "<i>Forfeited</i>" else: draft_board[draft_round][username] = "<i>TBD</i>" if league_id != '0': if league_key(league_id).get().draft_current_position == 0: league_name = league_key(league_id).get().name else: league_name = globals.draft_started_sentinel else: league_name = "" users_turn = False picking_user = "" draft_pick = draft_pick_key( league_key(league_id), league_key(league_id).get().draft_current_position).get() if draft_pick: users_turn = (draft_pick.player == account.key.urlsafe()) picking_user = ndb.Key( urlsafe=draft_pick.player).get().nickname current_unix_timeout = None if current_timeout: current_unix_timeout = calendar.timegm( current_timeout.timetuple()) current_position = league_key( league_id).get().draft_current_position if current_position == 0: draft_status = "Pre" elif current_position == -1: draft_status = "Post" else: draft_status = "Mid" team_map_data = get_lat_lng_json(league_id) #Send html data to browser template_values = { 'user': user.nickname(), 'logout_url': logout_url, 'draft_board': draft_board, 'player_list': player_list, 'update_text': update_text, 'league_name': league_name, 'users_turn': users_turn, 'picking_user': picking_user, 'current_unix_timeout': current_unix_timeout, 'draft_status': draft_status, 'team_map_data': team_map_data, } template = JINJA_ENVIRONMENT.get_template( 'templates/draft_main.html') self.response.write(template.render(template_values)) else: globals.display_error_page( self, self.request.referer, error_messages.need_to_be_a_member_of_a_league)
def get(self): # Checks for active Google account session user = users.get_current_user() #Force user login if user is None: self.redirect(users.create_login_url(self.request.uri)) else: #Current user's id, used to identify their data user_id = user.user_id() logout_url = users.create_logout_url('/') account = globals.get_or_create_account(user) league_id = account.league #Get user's choices for the current league find_choice_key = choice_key(account_key(user_id), str(league_id)) found_choice = find_choice_key.get() #Display update text for the status of the last choice update update_text = self.request.get('updated') if self.request.get('updated') == "Good": update_text = "Team added successfully" #Display the user's current roster user_roster = [] if found_choice: user_roster = found_choice.current_team_roster #Get list of players in the league and their choices league_table = [{'player_team': 'Roster', 'player_name': 'Player'}] league_player_query = Account.query(Account.league == league_id) league_players = league_player_query.fetch( ) #league_player_query.order(Account.nickname).fetch() for player in league_players: choice = choice_key(account_key(player.key.id()), league_id).get() if choice: league_table.append({ 'player_team': str(choice.current_team_roster), 'player_name': player.nickname }) else: league_table.append({ 'player_team': 'None', 'player_name': player.nickname }) if league_id != '0': if league_key(league_id).get().draft_current_position == 0: league_name = league_key(league_id).get().name else: league_name = globals.draft_started_sentinel else: league_name = "" #Send html data to browser template_values = { 'user': user.nickname(), 'logout_url': logout_url, 'update_text': update_text, 'league_table': league_table, 'league_name': league_name, 'roster': user_roster, 'default_team': self.request.get('team'), } template = JINJA_ENVIRONMENT.get_template( 'templates/pick_up_main.html') self.response.write(template.render(template_values))
def get(self): # Checks for active Google account session user = users.get_current_user() #Force user login if user is None: self.redirect(users.create_login_url(self.request.uri)) else: #Current user's id, used to identify their data user_id = user.user_id() logout_url = users.create_logout_url('/') account = globals.get_or_create_account(user) league_id = account.league #Get user's choices for the current league find_choice_key = choice_key(account_key(user_id), str(league_id)) found_choice = find_choice_key.get() #Display update text for the status of the last choice update update_text = self.request.get('updated') if self.request.get('updated') == "Good": update_text = "Team added successfully" #Display the user's current roster user_roster = [] if found_choice: user_roster = found_choice.current_team_roster #Get list of players in the league and their choices league_table = [{'player_team': 'Roster', 'player_name': 'Player'}] league_player_query = Account.query(Account.league == league_id) league_players = league_player_query.fetch() #league_player_query.order(Account.nickname).fetch() for player in league_players: choice = choice_key(account_key(player.key.id()), league_id).get() if choice: league_table.append( {'player_team': str(choice.current_team_roster), 'player_name': player.nickname}) else: league_table.append({'player_team': 'None', 'player_name': player.nickname}) if league_id != '0': if league_key(league_id).get().draft_current_position == 0: league_name = league_key(league_id).get().name else: league_name = globals.draft_started_sentinel else: league_name = "" #Send html data to browser template_values = { 'user': user.nickname(), 'logout_url': logout_url, 'update_text': update_text, 'league_table': league_table, 'league_name': league_name, 'roster': user_roster, 'default_team': self.request.get('team'), } template = JINJA_ENVIRONMENT.get_template('templates/pick_up_main.html') self.response.write(template.render(template_values))
def get(self): """ The draft page contains the draft board, a timer, and a map; all that is necessary for the draft process """ # Checks for active Google account session user = users.get_current_user() logout_url = users.create_logout_url('/') account = globals.get_or_create_account(user) league_id = account.league if league_id != '0': #Make check to see if the time for the current pick has expired current_time = datetime.datetime.utcnow() current_timeout = league_key(league_id).get().draft_current_timeout draft_pick = draft_pick_key(league_key(league_id), league_key(league_id).get().draft_current_position).get() if current_timeout: if current_time > current_timeout: # The time has expired draft_pick.team = 0 # Set the pick to indicate it was forefited draft_pick.put() setup_for_next_pick(league_id) # Move the pick along to the next person #Display update text for the status of the last choice update update_text = self.request.get('updated') if self.request.get('updated') == "Good": update_text = "Team added successfully" league_player_query = Account.query(Account.league == league_id) players_for_the_sake_of_number = league_player_query.fetch() league_players = [] if draft_pick_key(league_key(league_id), 1).get(): # != None for i in range(1, len(players_for_the_sake_of_number) + 1): pick = draft_pick_key(league_key(league_id), i).get() league_players.append(ndb.Key(urlsafe=pick.player).get()) else: league_players = players_for_the_sake_of_number draft_board = [] player_list = [] for player in league_players: player_list.append(player.nickname) number_of_picks = len(league_players) * globals.draft_rounds for position in range(1, number_of_picks + 1): pick_query = DraftPick.query().filter(DraftPick.display_number == position) query_results = pick_query.fetch(1) pick = DraftPick() if len(query_results) != 0: pick = query_results[0] username = (((position % len(league_players)) - 1) % len(league_players)) draft_round = int((position - 1) / len(league_players)) if username == 0: draft_board.append([]) for i in range(0, len(league_players)): draft_board[draft_round].append('-') if pick and pick.team != None: draft_board[draft_round][username] = str(pick.team) if pick.team == 0: draft_board[draft_round][username] = "<i>Forfeited</i>" else: draft_board[draft_round][username] = "<i>TBD</i>" if league_id != '0': if league_key(league_id).get().draft_current_position == 0: league_name = league_key(league_id).get().name else: league_name = globals.draft_started_sentinel else: league_name = "" users_turn = False picking_user = "" draft_pick = draft_pick_key(league_key(league_id), league_key(league_id).get().draft_current_position).get() if draft_pick: users_turn = (draft_pick.player == account.key.urlsafe()) picking_user = ndb.Key(urlsafe=draft_pick.player).get().nickname current_unix_timeout = None if current_timeout: current_unix_timeout = calendar.timegm(current_timeout.timetuple()) current_position = league_key(league_id).get().draft_current_position if current_position == 0: draft_status = "Pre" elif current_position == -1: draft_status = "Post" else: draft_status = "Mid" team_map_data = get_lat_lng_json(league_id) #Send html data to browser template_values = { 'user': user.nickname(), 'logout_url': logout_url, 'draft_board': draft_board, 'player_list': player_list, 'update_text': update_text, 'league_name': league_name, 'users_turn': users_turn, 'picking_user': picking_user, 'current_unix_timeout': current_unix_timeout, 'draft_status': draft_status, 'team_map_data': team_map_data, } template = JINJA_ENVIRONMENT.get_template('templates/draft_main.html') self.response.write(template.render(template_values)) else: globals.display_error_page(self, self.request.referer,error_messages.need_to_be_a_member_of_a_league)
def generate_schedule(league_id): """ Generate and distribute a schedule based on a round robin system where team members play each other fairly :parameter league_id: The id of the league to generate the schedule for :type: string Generate a random schedule in which all members play each other at least once before playing each other again Take this schedule and use to assign an individual schedule to each player """ player_ids_list = [] league_player_query = Account.query(Account.league == league_id) league_players = league_player_query.fetch() for player in league_players: player_ids_list.append(player.key.id()) shuffle(player_ids_list) if len(player_ids_list) % 2 == 1: # Check if the number of players is odd # Add 0 to represent bye week, added to beginning to solve last player issue player_ids_list.insert(0, globals.schedule_bye_week) number_of_players = len(player_ids_list) if number_of_players > 2: #Now that there's an even number of teams, use a round robin system to assign teams to weeks for player_num, player_id in enumerate(player_ids_list, start=1): if player_id != '0' and player_num != number_of_players: player = account_key(player_id).get() schedule = [] for week in range(1, number_of_players): opponent = (week + (number_of_players - 1) - player_num) % (number_of_players - 1) if opponent == player_num - 1: opponent = number_of_players - 1 schedule.append(player_ids_list[opponent]) #Confirm schedule length is appropriate schedule = make_schedule_fit(schedule) player.schedule = schedule player.put() #For the last player, whose schedule doesn't follow the same pattern last_player = account_key(player_ids_list[number_of_players - 1]).get() last_player_schedule = [] for week in range(1, number_of_players): #This equation comes from a mathematica document. Truss me about it - 2014 season last_player_schedule.append(player_ids_list[int(.25 * ((-1) ** week) * ((number_of_players - 1) + (number_of_players - 3) * ((-1) ** week) + 2 * ((-1) ** week) * week))]) last_player_schedule = make_schedule_fit(last_player_schedule) last_player.schedule = last_player_schedule last_player.put() elif number_of_players == 2: #If there's only two players, they just constantly play each other player1 = league_players[0] schedule1 = [] player2 = league_players[1] schedule2 = [] for week in range(1, globals.number_of_round_robin_weeks + 1): schedule1.append(player_ids_list[0]) schedule2.append(player_ids_list[1]) player1.schedule = schedule1 player2.schedule = schedule2 player1.put() player2.put()
def generate_schedule(league_id): """ Generate and distribute a schedule based on a round robin system where team members play each other fairly :parameter league_id: The id of the league to generate the schedule for :type: string Generate a random schedule in which all members play each other at least once before playing each other again Take this schedule and use to assign an individual schedule to each player """ player_ids_list = [] league_player_query = Account.query(Account.league == league_id) league_players = league_player_query.fetch() for player in league_players: player_ids_list.append(player.key.id()) shuffle(player_ids_list) if len(player_ids_list) % 2 == 1: # Check if the number of players is odd # Add 0 to represent bye week, added to beginning to solve last player issue player_ids_list.insert(0, globals.schedule_bye_week) number_of_players = len(player_ids_list) if number_of_players > 2: #Now that there's an even number of teams, use a round robin system to assign teams to weeks for player_num, player_id in enumerate(player_ids_list, start=1): if player_id != '0' and player_num != number_of_players: player = account_key(player_id).get() schedule = [] for week in range(1, number_of_players): opponent = (week + (number_of_players - 1) - player_num) % (number_of_players - 1) if opponent == player_num - 1: opponent = number_of_players - 1 schedule.append(player_ids_list[opponent]) #Confirm schedule length is appropriate schedule = make_schedule_fit(schedule) player.schedule = schedule player.put() #For the last player, whose schedule doesn't follow the same pattern last_player = account_key(player_ids_list[number_of_players - 1]).get() last_player_schedule = [] for week in range(1, number_of_players): #This equation comes from a mathematica document. Truss me about it - 2014 season last_player_schedule.append(player_ids_list[int( .25 * ((-1)**week) * ((number_of_players - 1) + (number_of_players - 3) * ((-1)**week) + 2 * ((-1)**week) * week))]) last_player_schedule = make_schedule_fit(last_player_schedule) last_player.schedule = last_player_schedule last_player.put() elif number_of_players == 2: #If there's only two players, they just constantly play each other player1 = league_players[0] schedule1 = [] player2 = league_players[1] schedule2 = [] for week in range(1, globals.number_of_round_robin_weeks + 1): schedule1.append(player_ids_list[0]) schedule2.append(player_ids_list[1]) player1.schedule = schedule1 player2.schedule = schedule2 player1.put() player2.put()