def TrainTeams(): state = query(State).first() teams = query(Team).all() for team in teams: # skip the player managed team if team.id == state.team.id: print("skipping player managed team {}".format(team.city)) continue # Adjust team rankings rand = random.random() if rand > 0.5 and team.offense < 5: team.offense += 1 elif rand < 0.5 and team.offense > 1: team.offense -= 1 rand = random.random() if rand > 0.5 and team.defense < 5: team.defense += 1 elif rand < 0.5 and team.defense > 1: team.defense -= 1 rand = random.random() if rand > 0.5 and team.special_teams < 5: team.special_teams += 1 elif rand < 0.5 and team.special_teams > 1: team.special_teams -= 1
def get(self, team_id): team_id = int(team_id) tmpWeek = query(Schedule, func.min( Schedule.week)).filter_by(result=None).first() lastWeek = 0 # subtract a week for last weeks results if tmpWeek[0] is None: tmpWeek = query(Schedule, func.max(Schedule.week)).first() lastWeek = tmpWeek[1] else: lastWeek = int(tmpWeek[1]) if lastWeek == 1: # season hasn't started return "Season not started", 200 lastWeek = lastWeek - 1 games = query(Schedule).filter_by(week=lastWeek).all() lastGame = None for game in games: if game.game.home_id == team_id or game.game.away_id == team_id: lastGame = game if lastGame is None: return "Bye Week", 200 return lastGame.toJSON()
def VerifyState(state): gamesLeft = query(Schedule).filter_by(result=None).all() playoffsLeftList = query(Playoff).filter_by(result=None).all() playoffsLeft = False # ignore the bye weeks for playoff in playoffsLeftList: if playoff.game is not None: playoffsLeft = True break if state is None: newGamePhase = query(Phase).filter_by(phase="NEWGAME").first() state = State(newGamePhase, None) db.session.add(state) db.session.commit() elif state.team is not None and state.phase.phase == "GENERATE_SCHEDULE": state = CreateScheduleController() elif len(gamesLeft) == 0 and state.phase.phase == "REGULARSEASON": state.advancePhase() db.session.commit() state = CreatePlayoffsController() elif not playoffsLeft and state.phase.phase == "POSTSEASON": state.advancePhase() StartOffseasonController() db.session.commit() elif state.phase.phase == "COMPLETEOFFSEASON": startOver = query(Phase).filter_by(phase="GENERATE_SCHEDULE").first() state.phase = startOver db.session.commit() state = CreateScheduleController() return state
def get(self): state = query(State).first() if state.phase.phase != 'DRAFT': return "Can not draft players now", 400 draftData = {} draftPicks = query(DraftPick).order_by(DraftPick.overall_pick).all() for r, pick in groupby(draftPicks, key=lambda x: x.round): draftData[r] = [p.toJSON() for p in pick] return draftData
def __init__(self): self.standings = {} conferences = query(Conference).order_by(Conference.shortName).all() for c in conferences: self.standings[c.name] = {} for d in c.divisions: teams = query(Team).filter_by(division_id=d.id) \ .order_by(Team.wins.desc()) \ .order_by(Team.points_for.desc()) \ .order_by(Team.points_against.asc()).all() self.standings[c.name][d.name] = self.__createStandings(teams)
def __init__(self): self.regular_season_weeks = 17 self.number_of_bye_weeks = 2 self.post_season_teams = 12 self.matchups = {} self.season = query(Season, func.max(Season.id)).first()[0] self.stand = Standings() self.standings = self.stand.standings self.schedule = {} self.__init_matchups() self.teams = {t.id: t for t in query(Team).all()} self.league = {} self.__init_league() self.divisionalMatchups = {}
def get(self): maxWeek = query(Schedule, func.min(Schedule.week)) \ .filter_by(result=None).first() nextWeek = maxWeek[1] if nextWeek is None: return [] games = query(Schedule).filter_by(week=nextWeek).all() for game in games: game.play() db.session.commit() return [game.toJSON() for game in games]
def get(self): games = query(Schedule).all() for game in games: game.play() db.session.commit() return [game.toJSON() for game in games]
def get(self): state = query(State).first() if state.phase.phase != 'FREEAGENCY': return "Can not sign free agents until the season is over", 400 freeAgents = generateFreeAgents() db.session.commit() return [player.toJSON() for player in freeAgents]
def SetTeam(team_id): team = query(Team).filter_by(id=team_id).first() if team is None: return "Not Found", 404 state = query(State).first() print(state.toJSON()) state.setTeam(team) Roster.assignPlayers(team) setStarters(team) db.session.commit() VerifyState(state) return team.toJSON()
def retiringPlayers(): retiringPlayers = [] playersWithoutTeam = getPlayersWithoutTeams() # force players without a team to retire for player in playersWithoutTeam: if player.age > 27: retiringPlayers.append(player.toJSON()) db.session.delete(player) query(TeamToPlayer).filter(TeamToPlayer.player_id == player.id).\ delete(synchronize_session=False) if player.position_ability < 50: retiringPlayers.append(player.toJSON()) db.session.delete(player) query(TeamToPlayer).filter(TeamToPlayer.player_id == player.id).\ delete(synchronize_session=False) # players on the team but retiring players = query(Player).all() for player in players: if player.willPlayerRetire(): retiringPlayers.append(player.toJSON()) db.session.delete(player) query(TeamToPlayer).filter(TeamToPlayer.player_id == player.id).\ delete(synchronize_session=False) return retiringPlayers
def __createPostSeasonSchedule(self, standings): playoffTeams = {} wildCardTeams = {} for conf, divisions in standings.items(): playoffTeams[conf] = [] wildCardTeams[conf] = [] for division, teams in divisions.items(): for rank, team in teams.items(): if rank == 1: playoffTeams[conf].append(team) else: wildCardTeams[conf].append(team) playoffTeams[conf] = sorted(playoffTeams[conf], key=lambda x: x.points_against) playoffTeams[conf] = sorted(playoffTeams[conf], key=lambda x: x.points_for, reverse=True) playoffTeams[conf] = sorted(playoffTeams[conf], key=lambda x: x.wins, reverse=True) wildCardTeams[conf] = sorted(wildCardTeams[conf], key=lambda x: x.points_against) wildCardTeams[conf] = sorted(wildCardTeams[conf], key=lambda x: x.points_for, reverse=True) wildCardTeams[conf] = sorted(wildCardTeams[conf], key=lambda x: x.wins, reverse=True) for conf in query(Conference).all(): # team rank 1 gets a bye playoff = Playoff(conf, playoffTeams[conf.name][0], 1, 1, None) db.session.add(playoff) # team rank 2 gets a bye playoff = Playoff(conf, playoffTeams[conf.name][1], 1, 2, None) db.session.add(playoff) # team rank 4 plays rank 5 game = Game(playoffTeams[conf.name][3], wildCardTeams[conf.name][0]) db.session.add(game) playoff = Playoff(conf, playoffTeams[conf.name][3], 1, 4, game) db.session.add(playoff) playoff = Playoff(conf, wildCardTeams[conf.name][0], 1, 5, game) db.session.add(playoff) # team rank 3 plays rank 6 game = Game(playoffTeams[conf.name][3], wildCardTeams[conf.name][1]) db.session.add(game) playoff = Playoff(conf, playoffTeams[conf.name][2], 1, 3, game) db.session.add(playoff) playoff = Playoff(conf, wildCardTeams[conf.name][1], 1, 6, game) db.session.add(playoff) db.session.commit()
def get(self, team_id): schedule = [] games = query(Schedule).order_by(Schedule.week).all() for game in games: team_id = int(team_id) if (game.game.home.id == team_id or game.game.away.id == team_id): schedule.append({'week': game.week, 'game': game.toJSON()}) return schedule
def get(self): state = query(State).first() if state.phase.phase != 'STARTOFFSEASON': return "Can not retire players unless the season is over", 400 players = retiringPlayers() state.advancePhase() db.session.commit() return players
def __init__(self): self.playoffs = {} self.nextRound = 1 playoffs = query(Playoff).all() playoffs = sorted(playoffs, key=lambda p: p.playoff_round) for pRound, teams in groupby(playoffs, lambda p: p.playoff_round): self.playoffs[pRound] = {} self.nextRound = pRound teams = sorted(teams, key=lambda p: p.conf.name) for conf, pTeams in groupby(teams, lambda p: p.conf.name): self.playoffs[pRound][conf] = sorted(pTeams, key=lambda p: p.rank)
def CreateScheduleController(): state = query(State).first() if state.phase.phase != "GENERATE_SCHEDULE": raise Exception("Can not generate schedule during {}" .format(state.phase.phase)) create = CreateSchedule() create.createRegularSeasonSchedule() state.advancePhase() db.session.commit() return state
def get(self, team_id): team_id = int(team_id) maxWeek = query(Schedule, func.min(Schedule.week)) \ .filter_by(result=None).first() nextWeek = maxWeek[1] if nextWeek is None: return "Regular Season is Over", 200 games = query(Schedule).filter_by(week=nextWeek).all() nextGame = None for game in games: if game.game.home_id == team_id or game.game.away_id == team_id: nextGame = game if nextGame is None: return "Bye Week", 200 return nextGame.toJSON()
def post(self): json_data = request.get_json(force=True) state = query(State).first() if state.phase.phase != 'FREEAGENCY': return "Can not sign free agents until the season is over", 400 for playerId in json_data: print(playerId) ttp = query(TeamToPlayer).filter_by(player_id=playerId).first() player = query(Player).filter_by(id=playerId).first() if ttp is None: print("adding ttp") teamToPlayer = TeamToPlayer(player, state.team, False) db.session.add(teamToPlayer) else: ttp.team = state.team state.advancePhase() db.session.commit() return 200, 200
def CreatePlayoffsController(): state = query(State).first() if state.phase.phase != "STARTPOSTSEASON": raise Exception("Can not start playoffs during {}" .format(state.phase.phase)) create = PostSeasonSchedule() create.advancePostSeasonSchedule() state.advancePhase() db.session.commit() return state
def generateFreeAgents(): maxFreeAgents = 32 freeAgents = getPlayersWithoutTeams() positions = query(Position).all() positionDefaults = getPositionDefaults() while len(freeAgents) < maxFreeAgents: position = choice(positions) freeAgent = generatePlayer( position, minAge=26, **positionDefaults[position.shortName]['abilities']) db.session.add(freeAgent) freeAgents.append(freeAgent) return freeAgents
def StartOffseasonController(): # Set Champion season = query(Season, func.max(Season.id)).first()[0] championshipRound = query(Playoff).filter_by(playoff_round=4).first() championshipGame = championshipRound.game championshipResult = championshipRound.result champion = None if championshipResult.home_score > championshipResult.away_score: champion = Champions(championshipGame.home, season) else: champion = Champions(championshipGame.away, season) db.session.add(champion) # set draft picks for championship for r in range(1, 8): print("champ round {}".format(r)) dp = DraftPick(champion.team, 32 * r) db.session.add(dp) for index, team in enumerate(reversed(Standings.getFullLeagueStandings())): # set draft picks if team.id != champion.team.id: if index == 32: index = 30 for r in range(0, 7): print(team.city, r, index, index + 1 + 32 * r) dp = DraftPick(team, index + 1 + 32 * r) db.session.add(dp) # Copy History history = History(team, season) db.session.add(history) # Reset Team wins team.wins = 0 team.losses = 0 team.points_for = 0 team.points_against = 0 # Clear Schedule query(Schedule).delete() query(Playoff).delete() # Advance Season nextSeason = Season("Season {}".format(season.id + 1)) db.session.add(nextSeason) db.session.commit()
def toJSON(self): results = { "teams": [], "results": [] } if 1 not in self.playoffs: return results confs = [] for conf in query(Conference).all(): confs.append(conf.name) results['teams'].append([self.playoffs[1][confs[0]][0].team.city, None]) results['teams'].append([self.playoffs[1][confs[0]][3].team.city, self.playoffs[1][confs[0]][4].team.city]) results['teams'].append([self.playoffs[1][confs[0]][2].team.city, self.playoffs[1][confs[0]][5].team.city]) results['teams'].append([self.playoffs[1][confs[0]][1].team.city, None]) results['teams'].append([self.playoffs[1][confs[1]][0].team.city, None]) results['teams'].append([self.playoffs[1][confs[1]][3].team.city, self.playoffs[1][confs[1]][4].team.city]) results['teams'].append([self.playoffs[1][confs[1]][2].team.city, self.playoffs[1][confs[1]][5].team.city]) results['teams'].append([self.playoffs[1][confs[1]][1].team.city, None]) for pRound in self.playoffs: weekResults = [] for conf, playoff in self.playoffs[pRound].items(): if pRound == 1: weekResults.append([None, None]) game4v5 = playoff[3].result if game4v5 is None: weekResults.append([None, None]) else: weekResults.append([game4v5.home_score, game4v5.away_score]) game3v6 = playoff[2].result if game3v6 is None: weekResults.append([None, None]) else: weekResults.append([game3v6.home_score, game3v6.away_score]) weekResults.append([None, None]) if pRound == 2: for game in [0, 1]: result = playoff[game].result if result is None: weekResults.append([None, None]) else: weekResults.append([result.home_score, result.away_score]) if pRound == 3: result = playoff[0].result if result is None: weekResults.append([None, None]) else: weekResults.append([result.home_score, result.away_score]) if pRound == 4: result = self.playoffs[pRound][confs[0]][0].result if result is None: weekResults.append([None, None]) else: weekResults.append([result.home_score, result.away_score]) results['results'].append(weekResults) print(results) return results
def advancePostSeasonSchedule(self): standings = Standings().standings playoffs = Playoffs().playoffs if 1 not in playoffs: self.__createPostSeasonSchedule(standings) return currentRound = max(list(playoffs.keys())) if currentRound == 1: for conf in query(Conference).all(): # get result from 3 vs 6 game1 = playoffs[currentRound][conf.name][2].game result1 = playoffs[currentRound][conf.name][2].result print(playoffs[currentRound][conf.name][2].rank) game1Winner = None if result1.home_score > result1.away_score: game1Winner = game1.home else: game1Winner = game1.away game = Game(playoffs[currentRound][conf.name][1].team, game1Winner) db.session.add(game) playoff = Playoff(conf, playoffs[currentRound][conf.name][1].team, 2, 2, game) db.session.add(playoff) playoff = Playoff(conf, game1Winner, 2, 3, game) db.session.add(playoff) # get result form 4 vs 5 game2 = playoffs[currentRound][conf.name][3].game result2 = playoffs[currentRound][conf.name][3].result game2Winner = None if result2.home_score > result2.away_score: game2Winner = game2.home else: game2Winner = game2.away game = Game(playoffs[currentRound][conf.name][0].team, game2Winner) db.session.add(game) playoff = Playoff(conf, playoffs[currentRound][conf.name][0].team, 2, 1, game) db.session.add(playoff) playoff = Playoff(conf, game2Winner, 2, 4, game) db.session.add(playoff) if currentRound == 2: for conf in query(Conference).all(): # get result from 1 vs 4 game1 = playoffs[currentRound][conf.name][0].game result1 = playoffs[currentRound][conf.name][0].result game1Winner = None if result1.home_score > result1.away_score: game1Winner = game1.home else: game1Winner = game1.away # get result form 2 vs 3 game2 = playoffs[currentRound][conf.name][1].game result2 = playoffs[currentRound][conf.name][1].result game2Winner = None if result2.home_score > result2.away_score: game2Winner = game2.home else: game2Winner = game2.away game = Game(game1Winner, game2Winner) db.session.add(game) playoff = Playoff(conf, game1Winner, 3, 1, game) db.session.add(playoff) playoff = Playoff(conf, game2Winner, 3, 2, game) db.session.add(playoff) if currentRound == 3: championship = {} for conf in query(Conference).all(): championship[conf.name] = {'conf': conf, 'team': None} for playoff in playoffs[currentRound][conf.name]: # get result from 1 vs 2 game = playoffs[currentRound][conf.name][0].game result = playoffs[currentRound][conf.name][0].result gameWinner = None if result.home_score > result.away_score: gameWinner = game.home else: gameWinner = game.away championship[conf.name]['team'] = gameWinner confs = list(championship.keys()) homeConf = championship[confs[0]]['conf'] homeTeam = championship[confs[0]]['team'] awayConf = championship[confs[1]]['conf'] awayTeam = championship[confs[1]]['team'] game = Game(homeTeam, awayTeam) db.session.add(game) playoff = Playoff(homeConf, homeTeam, 4, 1, game) db.session.add(playoff) playoff = Playoff(awayConf, awayTeam, 4, 2, game) db.session.add(playoff) db.session.commit()
qb = Position("Quarter Back", "QB", 35, 9, 1, 90) db.session.add(qb) rb = Position("Running Back", "RB", 10, 40, 40, 20) db.session.add(rb) wr = Position("Wide Receiver", "WR", 10, 60, 15, 25) db.session.add(wr) te = Position("Tight End", "TE", 5, 30, 30, 40) db.session.add(te) ol = Position("Offensive Line", "OL", 40, 5, 45, 50) db.session.add(ol) dl = Position("Defensive Line", "DL", 35, 4, 45, 50) db.session.add(dl) lb = Position("Line Backer", "LB", 35, 30, 30, 40) db.session.add(lb) dback = Position("Defensive Back", "DB", 30, 60, 20, 20) db.session.add(dback) k = Position("Kicker", "K", 50, 0, 5, 95) db.session.add(k) p = Position("Punter", "P", 50, 0, 5, 95) db.session.add(p) print("Creating first roster") player = getPositionDefaults() for position in query(Position).all(): for c in range(0, player[position.shortName]['count']): db.session.add( generatePlayer(position, **player[position.shortName]['abilities'])) db.session.commit()
def advance(self): return query(Phase).filter_by(id=self.id + 1).first()
def createRegularSeasonSchedule(self): # 17 week season, 16 games # first 3 division game in first 5 weeks # last 3 games division # 1 bye week per team starting week 7 ending week 14 # 4 games vs another division in conference 2 home 2 away # 4 games vs another division not in conference 2 home 2 away # 2 games vs ranked (not in above) one at home 1 on the road if query(Schedule).count() != 0: return # intra conference matchups teamMatchups = self.__intra_conference_matchups() # set intra-division self.__set_home_away(teamMatchups, 'intraconf', 2) db.session.commit() # set rank self.__set_home_away(teamMatchups, 'rank', 1) db.session.commit() # inter conference matchups teamMatchups = self.__inter_conference_matchups() self.__set_home_away(teamMatchups, 'interconf', 2) db.session.commit() # division matchups teamMatchups = self.__division_matchups() self.__set_home_away(teamMatchups, 'divisionstart', 2) self.__flip_flop_divisional_games('divisionstart', 'divisionend') db.session.commit() self.__convert_matchups() # setup the schedule for week in range(1, self.regular_season_weeks + 1): self.schedule[week] = { 'games': [], 'teams': set() } # schedule the games self.__schedule_games('rank', 'divisionstart', 2, 2, [1, 4]) self.__schedule_games('divisionstart', 'intraconf', 2, 2, [2, 3]) self.__schedule_games('divisionstart', 'interconf', 2, 2, [5, 6]) self.__schedule_games('intraconf', 'interconf', 2, 2, [7, 8]) self.__schedule_games('intraconf', 'interconf', 2, 2, [9, 10]) self.__schedule_games('intraconf', 'dummy', 4, 0, [11]) self.__schedule_games('interconf', 'rank', 2, 2, [13, 14]) self.__schedule_games('divisionend', 'dummy', 4, 0, [15]) self.__schedule_games('divisionend', 'dummy', 4, 0, [16]) self.__schedule_games('divisionend', 'dummy', 4, 0, [17]) # move games around to create bye weeks self.__create_bye_weeks([7, 8, 9, 10, 13, 14], 11, 12) # add the games to the db for week in self.schedule: for game in self.schedule[week]['games']: # print(game.id, week) schedule = Schedule(week, game) db.session.add(schedule) db.session.commit()
def get(self): teams = query(Team).all() return [team.toJSON() for team in teams]
def get(self, team_id): team = query(Team).filter_by(id=team_id).first() if team is None: return 404, 404 else: return team.toJSON()
def get(self): phases = query(Phase).all() return [phase.toJSON() for phase in phases]
def get(self): state = query(State).first() state = VerifyState(state) return state.toJSON()