def populate_games(cls): current_week = GameModel.get_max_week() or 0 current_games = GameModel.get_games_by_week(current_week) for game in current_games: if game.quarter != 'F' and game.quarter != 'FO': return {'message': 'not all games completed yet.'}, 401 return cls.update_games()
def post(self, user_id): data = Game.parser.parse_args() game = GameModel(data['name']) user = UserModel.find_by_id(user_id) game.save_to_db() user.save_game_to_collection(game) return game.json(), 201
def get(self): ingame = GameModel.check_if_in_game(current_identity.username) if ingame != None: return { "board": ingame.boardTiles, "active": ingame.gameopen, "player1": ingame.player1, "player2": ingame.player2, "status": ingame.gameStatus } return GameModel.find_game(current_identity.username)
def validate_pick(cls, data): week = GameModel.get_max_week() GameController.update_games() game = GameModel.find_by_game_id(data['game_id']) nfl_team = NFLTeamModel.find_by_team_name(data['nfl_team_name']) if game is None: return {'message': 'Cannot find game with that id.'}, 401 if nfl_team is None: return {'message': 'Cannot find nfl_team with that name'}, 401 if game.has_started: return { 'message': 'This game has already started. Please try a different game.' }, 403 if data['nfl_team_name'] not in [ game.home_team_name, game.away_team_name ]: return { 'message': 'Team for selected pick is not a part of game with id {}.'. format(data['game_id']) }, 403 if (PickModel.is_duplicate_team_pick(data['team_id'], data['nfl_team_name'])): return {'message': "You've already chosen this team."}, 401 pick = PickModel.find_pick_by_week_and_team_id(week, data['team_id']) if pick is None: pick = PickModel(data['team_id'], data['game_id'], week, data['nfl_team_name']) else: if pick.game.has_started: return { 'message': 'Current pick game already started. Cannot choose new team.' }, 401 pick.game_id = data['game_id'] pick.nfl_team_name = data['nfl_team_name'] try: pick.upsert() except: return {'message': 'error upserting pick.'}, 500 return {'pick': pick.json()}
def get(self): ingame = GameModel.check_if_in_game(current_identity.username) if ingame == None: ingame = GameModel(current_identity.username, "solo", "CPU") return ingame.create_game(current_identity.username, False) return { "board": ingame.boardTiles, "active": ingame.gameopen, "player1": ingame.player1, "player2": ingame.player2, "status": ingame.gameStatus }
def get(self, _id): game = GameModel.find_by_id(_id) if game: return game.json() return {"message": "Item not found."}, 404
def advance_week(cls, league): GameController.update_games() week_num = GameModel.get_max_week() active_teams = PlayerTeamModel.get_active_teams_in_league( league.league_id) losing_nfl_teams = GameController.get_losers_for_week(week_num) deactivated_teams = [] advancing_teams = [] for active_team in active_teams: pick = PickModel.find_pick_by_week_and_team_id( week_num, active_team.team_id) if pick is None: active_team.is_active = False deactivated_teams.append(active_team) else: if pick.nfl_team_name in losing_nfl_teams: active_team.is_active = False deactivated_teams.append(active_team) else: active_team.streak += 1 advancing_teams.append(active_team) active_team.upsert() for team in deactivated_teams: if team.user.receive_notifications: send_email("Sorry, you've been eliminated", Config.MAIL_USERNAME, team.user, team) return { 'deactivated_teams': deactivated_teams, 'advancing_teams': advancing_teams }
def get(self, id): game = GameModel.find_by_id(id) if game: return game.json(), 200 return {'message': 'Game with that ID not found'}, 404
def __init__(self, master=None): super().__init__(master) self.pack() self.master.title('Super AI Gomoku (version {})'.format(VERSION)) self.model = GameModel() self.board_ui = GameBoardUI(self, self.model, height=BOARD_HEIGHT_PIXELS, width=BOARD_WIDTH_PIXELS)
def current_week_pick_required(cls, team_id): team = playerTeam.PlayerTeamModel.find_by_team_id(team_id) if not team.is_active: return False week = GameModel.get_max_week() pick = cls.find_pick_by_week_and_team_id(week, team_id) return pick is None
def delete(self, user_id, game_id): game = GameModel.find_by_id(game_id) user = UserModel.find_by_id(user_id) if game and user: user.remove_game_from_collection(game) return {'message': 'Game removed from collection!'}, 200 return {'message': 'Game with that ID not found.'}, 404
def get(self): user_id = get_jwt_identity() games = [ game.json() for game in GameModel.find_all_by_user_id(user_id) ] if games: return {"games": games}, 200 return {"message": "No games were found."}, 404
def post(self, username): data = GameResource.parser.parse_args() if 'gameId' in data and data['gameId'] is not None: try: game = GameModel.find_by_id(data['gameId']) game.update_to_db(data['cellsState'], data['cellsClicked'], data['minutes'], data['seconds'], data['millis'], data['victory'], data['endGame']) except Exception as e: print(e) return {"message": "An error occurred updating the game."}, 500 else: try: user = UserModel.find_by_username(username) game = GameModel(user.id, data['rows'], data['cols'], data['bombs'], data['board'], data['cellsState'], data['cellsClicked'], data['minutes'], data['seconds'], data['millis'], data['victory'], data['endGame']) game.save_to_db() except Exception as e: print(e) return {"message": "An error occurred creating the game."}, 500 return game.json(), 201
def put(self): data = PlayerMove.parser.parse_args() ingame = GameModel.check_if_in_game(current_identity.username) user = UserModel.find_by_username(ingame.player1) user2 = UserModel.find_by_username(ingame.player2) if ingame.make_move(data['move'], current_identity.username): game = ingame.check_game_status() if game["open"] == True: if ingame.pvp == False: if ingame.cpu_move(): game = ingame.check_game_status() if game["open"] == False: if game["status"] == current_identity.username: user.save_win() elif game["status"] == "Tie": user.save_tie() else: user.save_lose() else: if game["status"] == current_identity.username: user.save_win() if ingame.pvp == True: user2.save_lose() elif game["status"] == "Tie": user.save_tie() if ingame.pvp == True: user2.save_tie() else: user.save_lose() if ingame.pvp == True: user2.save_win() ingame = GameModel.check_if_in_game(current_identity.username) return { "board": ingame.boardTiles, "status": ingame.gameStatus, "active": ingame.gameopen, "player1": ingame.player1, "player2": ingame.player2 }
def put(self, name): data = Game.parser.parse_args() game = GameModel.find_by_name(name) if game is None: game = GameModel(name, data['school_id']) else: game.school_id = data['school_id'] game.save_to_db() return game.json()
def get(self): ingame = GameModel.check_if_in_game(current_identity.username) user = UserModel.find_by_username(current_identity.username) if ingame != None: return { "message": "User in Game", "status": ingame.gameStatus, "active": ingame.gameopen, "board": ingame.boardTiles, "record": user.userRecord(), "player1": ingame.player1, "player2": ingame.player2 } return {"message": "Not in Game"}
def get_losers_for_week(cls, week_num): games = GameModel.get_games_by_week(week_num) losers = [] for game in games: if game.home_team_score == game.away_team_score: losers.append(game.home_team_name) losers.append(game.away_team_name) elif game.home_team_score < game.away_team_score: losers.append(game.home_team_name) else: losers.append(game.away_team_name) return losers
def post(self): data = self.parser.parse_args() user_id = get_jwt_identity() game = GameModel(user_id, data["name"], data["user_score"], data["opponent_score"]) user = UserModel.find_by_id(user_id) if game.user_score > game.opponent_score: user.wins += 1 else: user.losses += 1 user.save_to_db() try: game.save_to_db() except: return { "message": "An error occurred while recording this game." }, 500 return {"message": "Game recorded successfully."}, 201
def put(self): week_num = GameModel.get_max_week() if GameModel.week_has_unfinished_games(week_num): return {'message': 'Not all games finished'} all_leagues = LeagueModel.find_all_started_leagues(week_num) deactivated_teams = [] advancing_teams = [] for league in all_leagues: if league.league_type.league_type_name == LeagueTypes.STANDARD.name: teams_dict = StandardLeagueAdvanceController.advance_week(league) elif league.league_type.league_type_name == LeagueTypes.FREE.name: teams_dict = FreeLeagueAdvanceController.advance_week(league) else: raise NotImplementedError deactivated_teams += (teams_dict['deactivated_teams']) advancing_teams += (teams_dict['advancing_teams']) return { 'deactivated_teams': [team.json_advance_week() for team in deactivated_teams], 'advancing_teams': [team.json_advance_week() for team in advancing_teams] }
async def gameadd(self, ctx, key: str, *name: str): # check if game with key exist db_game = GameModel.getByKey(key) if not db_game: gameName = '{}'.format(' '.join(name)) db_game = GameModel() db_game.key = key db_game.name = gameName db_session.add(db_game) # commit update db_session.commit() gameRole = await ctx.guild.create_role( name=gameName, mentionable=True, ) # get role db_game.roleID = gameRole.id db_session.commit() # create output embed embed = discord.Embed( colour=discord.Colour.green(), title=f'Spiel angelegt' ) Session.close_all() # send embed await ctx.send(ctx.author.mention, embed=embed) else: # create output embed embed = discord.Embed( colour=discord.Colour.red(), title=f'Spiel gefunden' ) embed.add_field( name="Fehler", value=f'Es wurde das Spiel "{db_game.name}" mit dem Key "{db_game.key}" gefunden.', inline=False) # send embed await ctx.send(ctx.author.mention, embed=embed)
def put(self): #TODO:UNCOMMENT week_num = GameModel.get_max_week() # if GameModel.week_has_unfinished_games(week_num): # return {'message': 'Not all games finished'} all_leagues = LeagueModel.find_all_leagues() for league in all_leagues: if league.league_type.league_type_name == LeagueTypes.STANDARD.name: return StandardLeagueAdvanceController.advance_week(league) elif league.league_type.league_type_name == LeagueTypes.FREE.name: return FreeLeagueAdvanceController.advance_week(league) else: return { 'message': 'Advancing for this league type has not been implemented' } return {'message': 'No Leagues found'}
def post(self, name): status = 'failure' if GameModel.find_by_name(name): return {'message': "An item with name '{}' already exists".format(name)}, 400 # bad request. Error-first approach data = Game.parser.parse_args() game = GameModel(name, data['school_id']) # | try: game.save_to_db() status = 'success, game created' except: {'status': status, 'message': 'Some error occurred while inserting the game'}, 500 # Internal Server Error return {"game": game.json(), "status": status}, 201
def delete(self): info = GameModel.check_if_in_game(current_identity.username) if info != None: GameModel.leave_game(current_identity.username) return {'message': "You have left the game"} return {"message": "Not in game"}
def update_games(cls): rss_feed = requests.get(cls.nfl_endpoint) StadiumController.upsert_stadiums() json_data = rss_feed.json() week_info = json_data['week'] week_num = week_info['number'] events = json_data['events'] for event in events: competitions = event['competitions'] competition = competitions[0] teams = competition['competitors'] home_team = next( filter(lambda team: team['homeAway'] == 'home', teams)) away_team = next( filter(lambda team: team['homeAway'] == 'away', teams)) status = event['status'] type = status['type'] has_started = not type['state'] == 'pre' game_id = event['id'] game_model = GameModel.find_by_game_id(game_id) if game_model is None: if 'name' not in home_team['team']: home_team_name = home_team['team']['displayName'] else: home_team_name = home_team['team']['name'] if 'name' not in away_team['team']: away_team_name = away_team['team']['displayName'] else: away_team_name = away_team['team']['name'] home_team_score = home_team['score'] or 0 away_team_score = away_team['score'] or 0 if status['period'] == 0 and type['state'] == 'pre': quarter = 'P' elif type['state'] == 'post': quarter = 'F' else: quarter = status['period'] quarter_time = status['displayClock'] game_date = parser.parse(competition['startDate']) game_date_eastern = game_date - timedelta(hours=5) day_of_week = calendar.day_name[game_date_eastern.weekday()] site_id = competition['venue']['id'] game_model = GameModel(game_id, home_team_name, home_team_score, away_team_name, away_team_score, day_of_week, game_date, quarter, quarter_time, site_id, week_num, has_started) game_model.upsert() else: game_model.home_team_score = home_team['score'] or 0 game_model.away_team_score = away_team['score'] or 0 if status['period'] == 0 and type['state'] == 'pre': quarter = 'P' elif type['state'] == 'post': quarter = 'F' else: quarter = status['period'] game_model.quarter = quarter game_model.quarter_time = status['displayClock'] game_model.has_started = has_started game_date = parser.parse(competition['startDate']) game_date_eastern = game_date - timedelta(hours=5) day_of_week = calendar.day_name[game_date_eastern.weekday()] game_model.game_date = game_date game_model.day_of_week = day_of_week game_model.site_id = competition['venue']['id'] game_model.upsert() if 'odds' in competition: odds = competition['odds'] if odds: odds_model = OddsModel.find_by_game_id(game_id) if odds_model is None: if 'details' in odds[0] and 'overUnder' in odds[0]: odds_model = OddsModel(game_id, odds[0]['details'], odds[0]['overUnder']) odds_model.upsert() else: odds_model.details = odds[0]['details'] odds_model.over_under = odds[0]['overUnder'] odds_model.upsert() if odds_model: game_model.odds_id = odds_model.odds_id return_games = GameModel.get_games_by_week(week_num) return {'games': [game.json() for game in return_games]}
def find_all_picks(cls): prev_week_num = GameModel.get_max_week() - 1 return db.session.query( cls.nfl_team_name, label('count', func.count(cls.nfl_team_name))).filter_by( week_num=prev_week_num).group_by(cls.nfl_team_name).all()
def is_duplicate_team_pick(cls, team_id, nfl_team_name): week_num = GameModel.get_max_week() prev_picks = cls.query.filter(cls.team_id == team_id, cls.nfl_team_name == nfl_team_name, cls.week_num < week_num).first() return prev_picks is not None
def validate(cls, league): return GameModel.week_has_unfinished_games(league.start_week)
def delete(self, name): game = GameModel.find_by_name(name) if game: game.delete_from_db() return {'message': 'Game deleted'} return {'message': 'Game not found'}
def find_previous_week_picks_for_league(cls, league_id): prev_week_num = GameModel.get_max_week() - 1 return db.session.query(cls.nfl_team_name, label('count', func.count(cls.nfl_team_name))).filter_by(week_num=prev_week_num)\ .join(cls.player_team).filter_by(league_id=league_id).group_by(cls.nfl_team_name).all()
def get(self, name): game = GameModel.find_by_name(name) if game: return game.json() return {'message': 'Game not found'}, 404